diff --git a/CHANGELOG.md b/CHANGELOG.md index c6e2528a..865cad4e 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,324 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed — Stage 0 labels a sampled case by the majority of five answers + +A sampling model can answer one case both ways, so one answer labelled the case +by chance. On Qwen3.5-2B / BBH causal judgement at T=0.6 (32 cases), two +independent Stage 0 passes gave a case the same label 17 times out of 32. +`CaseDiscoveryAgent(n_samples=k)` now draws `k` answers per case in one batch +and labels the case by their majority; with five, the same two-pass check gave +25 of 32. `case.observed` is the first answer that earned the label, so scoring +it reproduces the label, and `case.metadata["discovery_votes"]` holds the count. +A failed sample does not vote; an even split is `UNKNOWN`. The default stays +one answer per case. + +The benchmark runner uses five when the task samples and one when it decodes +greedily; `--label-samples` sets it. `baseline.json` gains `label_samples`, +`n_split` (cases that answered both ways) and each case's `votes`. Stage 0 +generates five times as much: 107-114 s became 516-521 s on those 32 cases. +The labels are steadier, not settled: 9 of the 32 cases passed 4 to 6 times in +10, and no vote count makes such a case's label repeatable. + +The fix stage's repeated baseline (`baseline_repeats=k > 1`) now draws `k` +fresh samples instead of counting `case.observed` as the first. That answer is +the one the case was labelled by, and under a majority label it is picked to +agree with it, so counting it pulled the baseline rate toward the label. This +is one more generation per case per baseline. + +### Fixed — the fix search on the explore partition is in the run log + +`loop.run_fix` searches on the explore partition with `record=False` and then +confirms one candidate. `record=False` muted the whole recorder, so the run log +held the confirm phase only: none of the model calls of the candidates that were +searched, and none of the judge calls that proposed them. It now leaves out only +the `fix` outcome event, which the caller writes once for the combined result +(`FixRecorder.muted()` became `without_outcome()`). + +### Changed — hf_local batches multimodal inputs and logprobs; the last per-case loops batch + +`hf_local` now has one batching path for text and multimodal specs. Each input +is encoded on its own, as a single call encodes it, and the encodings are +stacked: token-level tensors are left-padded, image and audio tensors are +concatenated. `generate` is `generate_batch` with one input. A long list is +encoded a window of four batches at a time, so the encodings alive at once do +not grow with the list, and inputs that carry different tensors (with an image, +without one) batch separately. A multimodal family +batches only when it is listed in `BATCHED_MULTIMODAL_FAMILIES`; the others run +one input at a time, as do inputs whose media tensors do not stack. Listed, each +checked on a real checkpoint in float32 with greedy decoding and inputs of +different sizes (batched text identical to one-at-a-time text on every input; +logprobs within 1e-3): `qwen3_5` (Qwen3.5-2B, 10/10), `qwen2_5_vl` +(Qwen2.5-VL-3B, 10/10), `qwen3_vl` (Qwen3-VL-2B, 10/10), `qwen2_vl` +(Qwen2-VL-2B, 10/10), `qwen2_audio` (Qwen2-Audio-7B, 8/8). Not listed because no checkpoint was at hand: LLaVA, +InstructBLIP, Gemma 4, GLM-4V, Kimi-VL, Llama 4, the Qwen omni models and +Nemotron omni. + +`Model.logprobs_batch(inputs)` is new: `hf_local` runs it in padded batches and +ends each row at its own end-of-sequence token, `vllm_offline` hands the engine +the whole list, and every other model calls `logprobs` per input, +`Model.concurrency` at a time. The run log records one +`logprobs` call per input with its `batch_size`. + +Analyzers: + +- `context_shap` asks every context ablation of every case in one round. + `_shapley.coalitions()` lists the coalitions `shapley_values` will evaluate + for given arguments; the sampler never looks at a value, so they can be asked + up front. +- `vl_shap` and `mm_shap` score every masked input of their case up front with + `logprobs_batch`; `vl_shap` does it 64 masked images at a time, since each is + its own copy of the image (a caller-supplied `region_score_fn` / `score_fn` is + still called per coalition). +- `calibration` scores its cases' logprobs in one batch and asks each case on + its own only when that batch fails. +- `arith_audit(generate_missing=True)` and `answer_extraction_audit(reask=True)` + generate their missing chains and re-asks as one batch. + +Left as they are: `verbalized_confidence` and `logprob_entropy` make one model +call for one case, so there is nothing to batch (`calibration` is the batch-level +counterpart of both, and the M1 routes pair them with it). + +Fixed on the way: `verbalized_confidence` built its question as +`str(case.inputs) + elicit`, a bare string, so a vision model was asked without +the case's image. It now keeps the inputs and replaces the prompt. + +### Changed — the examples follow the package's default Claude model + +No example names a Claude model any more. `deco_hallu`, `deco_chair`, +`deco_miss`, `deco_pope`, `musicavqa_videollama2` and `llm_benchmark` read +`judge_model` / `codegen_model` from `config.yaml` when present and otherwise use +`ClaudeModel.DEFAULT_MODEL` (currently `sonnet`); their configs no longer set +either. `deco_hallu_explore`, `mmau_qwen2_audio`, +`audiocaps_hallucination_qwen2_audio` and the `chartqa` / `spatial457` examples +do the same for an empty `--judge-model`, and their compose commands no longer +pass `--judge-model claude-opus-5`. In the audio, `chartqa` and `spatial457` +examples the coder now gets the judge's model; with an empty name it had used +the CLI's session default. Effort settings are unchanged. + +`llm_benchmark` had pinned a full model name on purpose, so that two runs share +one judge. Its config now says to set `judge_model` to a full name for runs that +will be compared. + +`mmau_qwen2_audio/run.py` read `coder_cfg` before assigning it and stopped with +`UnboundLocalError` on every run without `--paper-method-only`; fixed. + +### Fixed — a generated probe no longer loses its input file to the agent that wrote it + +M1 sometimes logged `sandbox produced no parseable result` for a generated +probe. The coding agent writes the script in the sandbox directory, where the +host had already put the cases file. In 3 of 19 sessions the agent tried its +script by overwriting that file with two invented cases and deleted it +afterwards, so the real run failed with `FileNotFoundError`. + +`ExperimentSandbox.put(name, data)` places a file the generated code will read +and keeps its content; `run()` writes back any such file that was changed or +removed. The M1 probe generators, the M2 statistics-tool generator, the explore +agent and the M5 experiment writer place their inputs with it +(`SandboxProtocol` gained `put`). The two probe prompts now say the file is the +real data and must be left alone. With both changes, 12 of 12 sessions produced +a result. + +A failed probe run is logged with what happened (`the probe script exited with +code 1: FileNotFoundError: …`, `was killed after 60s`, `printed no readable +PROBE_RESULT_JSON= line`) in place of the one fixed sentence. + +### Changed — the fix stage asks the model in batches and has no thread pool + +`FixAgent`, `CandidateValidator`, `PipelineCoder` and `run_coded_pipeline` no +longer take `concurrency`. The fix stage hands the model the calls that do not +depend on each other and the model runs them its own way, as M1 does: + +- The fresh baseline samples are one `try_generate_batch`; so is a template + candidate. +- `run_pipeline(model, case, spec, score_fn, capture=, call_logger=)` is replaced + by `run_pipelines(model, cases, spec) -> list[PipelineRun]`. Every case and + every one of a spec's `n_samples` passes advance together, one round of + generation per strategy step. A `PipelineRun` carries the rendered prompt, the + outputs, the winner and each model call; the caller scores the winner. + `SpecPipelineModel` gained `generate_batch` on the same path. +- The coded-pipeline bridge answers the calls that arrive within 50 ms of each + other as one batch, from one host thread. The coder prompt now asks for one + thread per case instead of `max_workers=8`. +- Registered repairs, visual search and the matched baseline call a method on + the model that hooks it while it generates; they run one case at a time. +- The fresh baseline is measured once for a model and a set of cases (their + prompts and recorded answers) and shared by every tier of the search. Each tier had drawn its own 64 samples, so the + tiers of one e-BH family were paired against different baselines. + +`Model.concurrency` (default 1) is how many `generate` calls the default +`generate_batch` runs at once. The `api` backend sets it from +`RuntimeConfig.concurrency`; a `Model` subclass that calls an endpoint sets it on +itself. `APIModel` no longer overrides `generate_batch`. + +This also removes a fault in the previous entry's change: with `--concurrency` +defaulting to 8, the benchmark passed 8 to `FixAgent` on `hf_local` too, so eight +threads generated on one in-process model. In the one run that had it, on a +shared GPU, the fresh-baseline step took 64 min; it took 25 min serially. + +The `llm_benchmark` example drops `fix_concurrency`; its `concurrency` setting +now covers M1 and the fix stage as well. + +### Changed — one setting for requests in flight against an API backend + +`RuntimeConfig.concurrency` (default 8) is how many requests an API model has in +flight, in every stage. `ProbeAgent` runs in-process analyzers one at a time on +the calling thread and each sends its questions as batches; `max_workers` now +only bounds Docker-mode analyzers. Before, up to 8 analyzers ran in threads, +each asking one question at a time. `CaseDiscoveryAgent` no longer takes +`concurrency`: it makes one batch call and the backend decides. The benchmark's +`--concurrency` sets `RuntimeConfig.concurrency` for the `endpoint` and `gemini` +backends and defaults to 8 (was 1, and applied to Stage 0 only). The benchmark +run config no longer records `m1_workers`. + +### Changed — M3 rewrites a test that names evidence M2 did not measure + +M4 does not judge a hypothesis whose test names only identifiers with no M2 +result (a signal name the judge made up, a case id): it reports the test as +unmet. In one 22-minute run that was three of six hypotheses. M3's proposal call +now checks each test the way M4 will and, when one is unmet, asks the judge once +to rewrite it against the signals that have a result, or in plain words. As with +the plain-language check, the second answer is accepted as it is. + +### Changed — M1 is bounded by default + +`ProbeAgent` now caps a probe round at 6 analyzers (`max_analyzers=6`; `None` +removes the cap) and at 30 minutes (`time_budget_sec=1800`; 0 removes it). An +analyzer that has not started when the time is spent is skipped and named in +the selection rationale. The agentic benchmark path had neither limit: one run +selected 17 analyzers and spent 10,081 s in a single M1. + +While M1 runs, the console prints the plan and one line per analyzer as it +finishes (`RunLogger.progress`); it printed nothing until the stage ended. + +Nine analyzers explain one input and read only the first case of a batch +(`rise`, `vl_shap`, `mm_shap`, `logprob_entropy`, `self_consistency`, +`verbalized_confidence`, `attention_rollout`, `cka`, `token_entropy`). They now +declare `single_case = True` and selection does not offer them on a batch of +several cases, where they gave M2 one row. A caller that names one +(`analyzers=[...]`) still gets it. + +A selection is no longer padded up to `max_analyzers`: the static selector +replaces a choice that cannot run, it does not add analyzers the judge or the +caller did not ask for. + +### Added — batch generation is part of the `Model` interface + +`Model.generate_batch(inputs, **kwargs)` returns one answer per input, in order. +`hf_local` pads a text-only spec's prompts into batches of +`RuntimeConfig.batch_size` (default 32, longest first, halved on a CUDA +out-of-memory error); `vllm_offline` passes the engine the whole list, where it +sent one prompt per call before; `api` keeps `RuntimeConfig.concurrency` +(default 8) requests in flight; every other model asks one at a time. +`try_generate_batch` returns an input's exception in its place. Multimodal specs +on `hf_local` still answer one input at a time. + +Measured on Qwen3.5-2B, 24 BBH causal-judgement prompts, one GPU: greedy +decoding 217 s one at a time and 19.8 s batched; sampled at the benchmark's +settings (2048-token cap) about 20 s per prompt one at a time, and batched 4.3 s +at a batch size of 16, 2.8 s at 32 and 1.6 s at 64 (8.4 GB peak). +In float32 the batched answers equal the single ones on 16 of 16 prompts. In +bfloat16 they differ after the first tokens, including for an unpadded batch: +half-precision rounding depends on the batch shape. + +`evalrx.core.analyzer` adds `Ask`, `Probe` and `run_probes`: an analyzer writes +its per-case logic as a generator that yields an `Ask` for the answers it needs, +and `run_probes` batches each round across the cases. `labelled_answers` reads +`case.observed` and asks only for the cases without one. + +Analyzers now on batches: `prompt_contrast`, `cot_faithfulness`, +`perturbation_battery`, `modality_ablation`, `coverage_verification_gap`, +`calibration` (its verbalized-confidence questions), `self_consistency`, +`selfcheck_consistency`, `format_sensitivity`, `knowledge_reasoning_split`, +`self_repair`, `step_rollout_value`, `termination_audit`, `contamination_score`, +`rise`; Stage 0 (`CaseDiscoveryAgent`) on a local backend; and +`ProbeGenerator`'s output collection. Within one analyzer the calls now go out +round by round across cases, not case by case. + +### Changed — decoding settings belong to the model + +`RuntimeConfig.sampling` holds the decoding a model is deployed with; +`hf_local` and `jax_local` apply it to every `generate` call that passes none of +its own, and `vllm_offline` now reads `max_new_tokens`, `do_sample`, `top_p` and +`top_k` where it dropped them. The benchmark sets it from the Stage 0 settings. +Before, Stage 0 labelled the llm tasks under sampling (T=0.6) while analyzers, +which pass no arguments, ran greedy, so an analyzer's "baseline" was not the +answer the label described. + +`pope` and `chair` score the answer the case was labelled on (`case.observed`) +and no longer ask for it again; `ProbeGenerator` reads it too. Analyzers that +pair a baseline against a changed prompt (`prompt_contrast`, +`perturbation_battery`, `cot_faithfulness`, `modality_ablation`) still ask for a +fresh one, now under the same decoding. + +On `hf_local` this changes what the answer-changed signals mean when the model +is deployed with sampling: a flip in `perturbation_battery`, `format_sensitivity`, +`cot_faithfulness`, `modality_ablation` or a `prompt_contrast` pair now includes +decoding noise, as it always did on the API backends. Measured on Qwen3.5-2B / +BBH causal judgement at T=0.6: an unchanged prompt asked again gave the labelled +answer 68 times in 128 (53%), the same for PASS and FAIL cases. For a +deterministic comparison deploy the model greedy (`RuntimeConfig.sampling`); +`perturbation_battery` also takes `gen_kwargs={"do_sample": False}`. + +A model under test must be a `Model`: stages call `generate_batch` on it, so an +object that only has `generate` no longer works. + +### Changed — run log schema v9 + +`model_call.batch_size` marks a call that was one input of a batch; its +`duration_sec` is that input's share of the batch's wall time, so the records +still sum to the time spent. + +### Changed — the Claude judge defaults to `sonnet` + +`ClaudeModel.DEFAULT_MODEL = "sonnet"` is the one place the default lives. The +benchmark CLI (`--judge-model` unset) and the judge auto-detection +(`DEFAULT_CLAUDE_CANDIDATES`) use it; the benchmark's `--judge-effort` default +goes from `high` to `medium`. Measured on prompts recorded from a real run: a +28k-character M3 review took 71-124 s on `claude-fable-5` and 5 s on `sonnet`; a +1.8k-character M4 yes/no took 17 s and 2 s. A 22-minute `qwen_loop_claude` run +spent about 20 of those minutes in judge stages. Pass `--judge-model` to choose +a larger model. + +### Changed — `eval_agent` grouped into `loop/` and `runlog/` + +The loop and its policies live in `evalrx.eval_agent.loop`, the run directory and +event log in `evalrx.eval_agent.runlog`. Top-level imports +(`from evalrx.eval_agent import VLDiagnoseLoop, RunContext, ...`) are unchanged; +deep imports move, with no aliases left behind: + +| Was | Now | +|---|---| +| `evalrx.eval_agent.loop` | `evalrx.eval_agent.loop.diagnose` | +| `evalrx.eval_agent.policy` | `evalrx.eval_agent.loop.state` (`Policy`, `RunState`, `cycle_summary`), `evalrx.eval_agent.loop.fixed` (`FixedOrderPolicy`) | +| `evalrx.eval_agent.agentic` (and `.actions`, `.board`, `.tools`, `.policy`) | `evalrx.eval_agent.loop.judge` (same submodules) | +| `evalrx.eval_agent.loop_reports` | `evalrx.eval_agent.loop.report` | +| `evalrx.eval_agent.loop_fix` | `evalrx.eval_agent.loop.fix` | +| `evalrx.eval_agent.run_metadata` | `evalrx.eval_agent.loop.metadata` | +| `evalrx.eval_agent.run_context` | `evalrx.eval_agent.runlog.context` | +| `evalrx.eval_agent.run_logger` | `evalrx.eval_agent.runlog.logger` | +| `evalrx.eval_agent.run_log_entries` / `run_log_files` / `run_log_tracing` | `evalrx.eval_agent.runlog.entries` / `files` / `tracing` | +| `evalrx.eval_agent.log_schema` (+ `run_log.schema.json`) | `evalrx.eval_agent.runlog.schema` (schema file beside it) | +| `evalrx.eval_agent.narration` | `evalrx.eval_agent.runlog.narration` | +| `evalrx.eval_agent.model_instrumentation` | `evalrx.eval_agent.runlog.instrumentation` | +| `evalrx/eval_agent/RUN_LOGGER.md` | `evalrx/eval_agent/runlog/README.md` | + +The stages leave the loop class. `evalrx.eval_agent.loop.stages.Stages` runs and +records M1 probe, explore, M2, M3, M4 and the held-out M4 pass +(`probe`, `explore`, `analyze`, `diagnose`, `test_hypotheses`, `test_on_holdout`, +`bridge_signals`) and holds the stage dependencies, never the loop. +`VLDiagnoseLoop.stages()` builds one from the loop's current settings for each +run, and a policy reaches them through `RunState.stages` (a new required +field). What outlives a run on the same loop — the explorer notes M3 and the fix +stage read, the default M3 agent, the token count — is one `StageMemory` +(was `loop._explore_context`, `loop._tokens_used`, and a `diagnosis_agent` +assigned on first use). The explore/confirm/test partition is the pure function +`evalrx.eval_agent.loop.partition.split_cases`. Removed from `VLDiagnoseLoop`: +`_do_m1`, `_do_explore`, `_do_m2`, `_do_m3`, `_do_m4`, `_m4_holdout_pass`, +`_bridge_signals`, `_explore_out_dir`, `_get_diagnosis_agent`, `_emit_m1`, +`_finalize_confirmatory_stats` (now `loop.stages.finalize_confirmatory_stats`), +`_strat_key`. The constructor is unchanged. + ### Added — typed judge calls `evalrx.agent_runtime.judge_call.ask_judge(judge, prompt, OutputModel, role=...)` diff --git a/docs/architecture.md b/docs/architecture.md index 61c65b13..ce283825 100755 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -106,9 +106,48 @@ doubled-`.model.` / no-`.model` / fused-experts traps. ```python model.generate(inputs, **kwargs) -> str +model.generate_batch([inputs, ...], **kwargs) -> list[str] # same order as the inputs model.forward(inputs, capture={...}, spec=None) -> Trace ``` +`generate_batch` is the call for several independent questions. Each backend +answers it the fastest way it has: `hf_local` runs left-padded batches of +`RuntimeConfig.batch_size` inputs (32 by default, halved on a CUDA +out-of-memory error), and `vllm_offline` hands the engine the whole list. Any +other model calls `generate` for each input, `Model.concurrency` at a time: 1 by +default, `RuntimeConfig.concurrency` for the `api` backend, and whatever a +`Model` subclass that calls an endpoint sets on itself. `try_generate_batch` +returns an input's exception in its place, for a caller that must keep the other +answers. `logprobs_batch` is the same call for `logprobs`. + +`hf_local` builds a batch by encoding every input on its own, exactly as a +single call does, and stacking the encodings: token-level tensors are padded on +the left, image and audio tensors are concatenated. A long list is encoded a +window of four batches at a time, and inputs with and without an image batch +separately. A text-only spec always batches. A multimodal family batches once it is listed in +`BATCHED_MULTIMODAL_FAMILIES` (`models/backends/hf/model.py`), which means its +batched answers were compared with one-at-a-time answers on a real checkpoint in +float32 and came out identical; an unlisted family, and inputs whose media +tensors do not stack, run one at a time. + +No stage owns a thread pool for the model under test. A stage hands over the +questions that do not depend on each other and the model decides how many run +at once. + +The decoding a model is deployed with lives in `RuntimeConfig.sampling` +(`do_sample`, `temperature`, `top_p`, `top_k`). `hf_local` and `jax_local` apply +it to every call that passes none of its own, so an analyzer that calls +`generate` with no arguments probes the model under the settings its cases were +labelled with. + +A sampling model can answer one case both ways, so one answer labels the case +by chance. `CaseDiscoveryAgent(n_samples=k)` draws `k` answers per case in one +batch and labels the case by their majority; `case.observed` is an answer that +earned that label and `case.metadata["discovery_votes"]` holds the count. The +benchmark runner uses five when the task samples and one when it decodes +greedily (`--label-samples`). The fix stage's repeated baseline does not count +`case.observed` among its samples, because that answer was chosen by the label. + `forward` returns a `Trace`, which is the common carrier for captured internals such as tokens, token ids, attentions, hidden states, logits, and backend-specific extras. @@ -118,6 +157,32 @@ extras. `Analyzer` is the EvalRX analogue of an sklearn estimator. It has explicit constructor parameters, declares required capabilities, and returns a `Result`. +An analyzer that asks the model several questions per case writes them as a +per-case probe: a generator that yields an `Ask` wherever it needs answers and +returns the case's row. `run_probes` advances every case's probe together and +sends each round to `model.generate_batch`, so the code reads as one case at a +time and runs as batches: + +```python +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes + +class MyProbe(Analyzer): + def _run(self, model, cases): + rows = run_probes(model, [self._probe_case(case) for case in cases]) + ... + + def _probe_case(self, case) -> Probe[dict]: + direct, reasoned = yield Ask([case.inputs, with_suffix(case.inputs, COT)]) + (checked,) = yield Ask([follow_up(case.inputs, reasoned)]) # needs the answer above + return {"sample_id": case.id, ...} +``` + +To read the answer a case was labelled on, use `labelled_answers(model, cases)`: +it returns `case.observed` and asks only for the cases that carry none. An +analyzer that compares that answer against a re-ask under a changed prompt asks +for a fresh control instead, because the labelled answer is the one the FAIL +cases were selected on. + ```python analyzer = SomeAnalyzer(**params) result = analyzer.run(model, data) @@ -180,7 +245,7 @@ core contracts described above. Two loops are available — the same M1-M4 stages, two different orchestration strategies: ```text -VLDiagnoseLoop (loop.py — protocol-guided, stops on verified hypothesis) +VLDiagnoseLoop (loop/diagnose.py — protocol-guided, stops on verified hypothesis) ExperimentProtocol ← user's NL description of what to investigate │ M1 · ProbeAgent detect model kind → run ranked analyzers; @@ -193,9 +258,9 @@ VLDiagnoseLoop (loop.py — protocol-guided, stops on verified hypothesis) │ M5 · SurgeryAgent called once post-loop on the best verified hypothesis -The cycle above is the default policy, FixedOrderPolicy (policy.py). +The cycle above is the default policy, FixedOrderPolicy (loop/fixed.py). -VLDiagnoseLoop(policy=JudgePolicy(judge)) (agentic/policy.py — judge-decided, same M1-M4 stages) +VLDiagnoseLoop(policy=JudgePolicy(judge)) (loop/judge/policy.py — judge-decided, same M1-M4 stages) A CLI judge picks the next tool (run_probe / run_stats / explore_data / cluster_failures / search_probes / propose_hypotheses / test_hypothesis / run_surgery / run_fix / stop) each turn from an EvidenceBoard, instead of a @@ -209,7 +274,7 @@ The agent touches models only through the `Model` protocol and stores all evidence in a `Store`. `.run()` on both loops returns the same class, `AutoDiagnoseReport` -(`loop_reports.py`). Each loop populates only the fields relevant to what it +(`loop/report.py`). Each loop populates only the fields relevant to what it ran — see [Stage Input/Output Reference](stage_io.md#loop-level-output) for the full field table. @@ -217,18 +282,25 @@ the full field table. ```text eval_agent/ -├── loop.py VLDiagnoseLoop (current) -├── loop_fix.py run_fix orchestration: fix targets, tier ladder, EXPLORE→CONFIRM -├── loop_reports.py AutoDiagnoseReport — the one report class both policies return -├── policy.py FixedOrderPolicy (default M1→M4 cycles) + RunState, shared by both policies -├── run_metadata.py shared run-provenance + logging-wiring helpers -├── agentic/ JudgePolicy — judge-decided M1-M4 (see below) -├── run_context.py RunContext, Trial — single owner of a run's output directory -├── run_logger.py RunLogger — run.json + per-stage M/log.json event log -├── run_log_entries.py what each logged event records, one pure function per event -├── run_log_files.py atomic JSON writes, inlined sandbox workspaces, saved artifacts -├── run_log_tracing.py each logged event mirrored into Langfuse -├── log_schema.py published event JSON Schema +├── loop/ the diagnosis loop and who picks its next step +│ ├── diagnose.py VLDiagnoseLoop — configuration and the run phases +│ ├── stages.py Stages — runs and records M1, explore, M2, M3, M4 (no loop reference) +│ ├── partition.py split_cases — the EXPLORE / CONFIRM / TEST partition +│ ├── state.py Policy (next-step contract), RunState (what a run carries) +│ ├── fixed.py FixedOrderPolicy — M1→M4 cycles, the default +│ ├── judge/ JudgePolicy — judge-decided M1-M4 (see below) +│ ├── report.py AutoDiagnoseReport — the one report class both policies return +│ ├── fix.py run_fix orchestration: fix targets, tier ladder, EXPLORE→CONFIRM +│ └── metadata.py shared run-provenance + logging-wiring helpers +├── runlog/ a run's output directory and event log (README.md: the layout) +│ ├── context.py RunContext, Trial — single owner of a run's output directory +│ ├── logger.py RunLogger — run.json + per-stage M/log.json event log +│ ├── entries.py what each logged event records, one pure function per event +│ ├── files.py atomic JSON writes, inlined sandbox workspaces, saved artifacts +│ ├── tracing.py each logged event mirrored into Langfuse +│ ├── schema.py published event JSON Schema (run_log.schema.json) +│ ├── narration.py live terminal narration of a run +│ └── instrumentation.py InstrumentedModel — logs each analyzer call to the model ├── hypothesis.py Hypothesis, HypothesisStatus — shared across M3/M4/M5 ├── store.py Store / InMemoryStore / JsonlStore └── stages/ ← M1, M3, M4, M5 stage implementations (M2 lives in evalrx.analysis) @@ -485,7 +557,7 @@ wiring required. files, a logger buried under a `logs/` subdir, hand-built figure-dir paths, and M5 sandboxes living in ephemeral temp dirs deleted on success. One `RunContext` owns the whole run root and hands every producer its -subdirectory, always through `RunLogger` (`evalrx/eval_agent/RUN_LOGGER.md`) — +subdirectory, always through `RunLogger` (`evalrx/eval_agent/runlog/README.md`) — there is no other logger to select: ```text @@ -540,8 +612,8 @@ jq '.probe[-1].findings' run_dir/M1/log.json # latest M1 findings ``` The event format is a **published JSON Schema** (Draft 2020-12), shipped as -package data at `evalrx/eval_agent/run_log.schema.json` and built from -`evalrx/eval_agent/log_schema.py` — so downstream parsers (in any language) +package data at `evalrx/eval_agent/runlog/run_log.schema.json` and built from +`evalrx/eval_agent/runlog/schema.py` — so downstream parsers (in any language) can validate an event instead of guessing field shapes. It's permissive by design: it pins the common envelope (`event`, `schema_version`, `ts`, `trace_id`, `stage`, `span_id`, `event_seq`), the per-event required fields @@ -612,6 +684,16 @@ allowlist is one entry in `BUILTIN_SPECS` (the judge-less fallback list in sentence in `BUILTIN_DESCRIPTIONS`. A new candidate kind is one execution method on `CandidateValidator` plus its entry in the kind map. +The validator asks the model in batches. The fresh baseline samples are one +`try_generate_batch`, drawn once for a model and a set of cases and shared by +every tier of the search; a template candidate is one; a spec (`run_pipelines`) runs +every case and every sample of its strategy as probes, one round of generation +per strategy step. A coded pipeline runs in a sandbox and reaches the model +through a bridge: one host thread answers the calls that arrive together as one +batch, so the coder is told to run one thread per case. Candidates that call a +method on the model itself (registered repairs, visual search, internals, weight +edits) run one case at a time, because they hook the model while it generates. + ```text L1 input space prompt rewrites, instruction strategies diff --git a/docs/contract/README.md b/docs/contract/README.md index c222dfab..603926b6 100644 --- a/docs/contract/README.md +++ b/docs/contract/README.md @@ -23,7 +23,7 @@ changes — adding a field is additive and does not bump it, so a reader must ``` `run.json` + `M1/log.json`..`M5/log.json` are RunLogger's layout (see -`evalrx/eval_agent/RUN_LOGGER.md`): no flat event stream, no separate +`evalrx/eval_agent/runlog/README.md`): no flat event stream, no separate `report/`/`figures/` — generated text/code is inlined into the owning stage's JSON and media is copied into that stage's own `artifacts/`. `contract/` sits alongside it, independently typed and validated. diff --git a/docs/design_jax_backend.md b/docs/design_jax_backend.md index 6122f46b..5fde64f6 100644 --- a/docs/design_jax_backend.md +++ b/docs/design_jax_backend.md @@ -432,10 +432,12 @@ M1-to-fix chain on one cell per modality with `--backend jax_local`. existing hooks, but it touches `fix_internals`, which has a large test suite. Recommendation: yes, in phase 2, behind the current `visual_embedding_boost` test expectations. -- **Concurrency.** `--concurrency` is honoured only for the endpoint backend. - A JAX in-process model wants batching instead; an optional - `generate_batch` on the adapter, used by `CaseDiscoveryAgent` when present, - is the natural later addition and is out of scope here. +- **Concurrency.** `--concurrency` is the number of requests in flight against + an API backend. A JAX in-process model wants batching instead: + `Model.generate_batch` is now the call every stage uses, the fix stage + included, and the JAX model still answers it one input at a time + (`Model.concurrency` stays 1, so it is never entered from two threads). A batched `generate` on the adapter is + the natural later addition and is out of scope here. ## 8. Out of scope diff --git a/docs/extending.md b/docs/extending.md index fb3864d6..56c17e34 100755 --- a/docs/extending.md +++ b/docs/extending.md @@ -401,7 +401,7 @@ sequence assigned under the logger's lock), and stage-specific fields: | `run.json["run_end"]` | envelope only — written when the logger closes (schema 7) | The full, authoritative field contract is the published JSON Schema -(`evalrx/eval_agent/run_log.schema.json`, from `log_schema.py`); validate one +(`evalrx/eval_agent/runlog/run_log.schema.json`, from `log_schema.py`); validate one event with `from evalrx.eval_agent import validate_event` (needs the optional `jsonschema` dep). See `docs/architecture.md` for details, and `evalrx.reporting.run_events.read_run_events(root)` for a flat, ordered view diff --git a/docs/stage_io.md b/docs/stage_io.md index 119d763a..ad82eee3 100644 --- a/docs/stage_io.md +++ b/docs/stage_io.md @@ -457,7 +457,7 @@ Two things the contract will not do for you, both deliberate: grounded. The rest of this section describes the raw run directory — `RunContext`'s -only layout now (`evalrx/eval_agent/RUN_LOGGER.md`; there is no other +only layout now (`evalrx/eval_agent/runlog/README.md`; there is no other logger to select). `contract/` is unaffected by any of this. ### 1. Choose a source of truth diff --git a/evalrx/agent_runtime/judges/autodetect.py b/evalrx/agent_runtime/judges/autodetect.py index 7f6289b2..14dad550 100644 --- a/evalrx/agent_runtime/judges/autodetect.py +++ b/evalrx/agent_runtime/judges/autodetect.py @@ -27,9 +27,8 @@ "Gemini 3.5 Flash (Low)", "Claude Opus 4.6 (Thinking)", ) -# Claude judge candidates: the user's session model first (Fable), then -# cheaper aliases. -DEFAULT_CLAUDE_CANDIDATES: tuple[str, ...] = ("claude-fable-5", "sonnet", "haiku") +# Claude judge candidates: the default first, then the cheaper alias. +DEFAULT_CLAUDE_CANDIDATES: tuple[str, ...] = (ClaudeModel.DEFAULT_MODEL, "haiku") def pick_live_model( diff --git a/evalrx/agent_runtime/judges/claude.py b/evalrx/agent_runtime/judges/claude.py index c42650a0..689cae3f 100644 --- a/evalrx/agent_runtime/judges/claude.py +++ b/evalrx/agent_runtime/judges/claude.py @@ -16,11 +16,16 @@ class ClaudeModel: key = "claude" + #: The model a stage gets when the caller names none. Measured on recorded + #: prompts (2026-11-20): a 28k-char M3 review took 71-124 s on the largest + #: model and 5 s on this one, and a run spends most of its time in judge calls. + DEFAULT_MODEL = "sonnet" + def __init__( self, binary_path: str = "", timeout_sec: int = 240, - model: str = "", + model: str = DEFAULT_MODEL, effort: str = "", ) -> None: from evalrx.core.capability import Capability diff --git a/evalrx/agent_runtime/sandbox.py b/evalrx/agent_runtime/sandbox.py index fe04511f..263eed6a 100755 --- a/evalrx/agent_runtime/sandbox.py +++ b/evalrx/agent_runtime/sandbox.py @@ -180,6 +180,8 @@ def ok(self) -> bool: class SandboxProtocol(Protocol): """Structural type for sandbox backends (subprocess, Docker, SSH, …).""" + def put(self, name: str, data: "str | bytes") -> Path: ... + def run(self, code: str, *, timeout_sec: int = 60) -> SandboxResult: ... def run_project( @@ -288,11 +290,41 @@ def __init__( self._counter_lock = threading.Lock() self._preexec_fn = _make_resource_preexec(max_memory_bytes, max_cpu_seconds) self._cleanup = cleanup + self._inputs: dict[str, bytes] = {} # ------------------------------------------------------------------ # Public interface # ------------------------------------------------------------------ + def put(self, name: str, data: "str | bytes") -> Path: + """Place a file the generated code will read; *name* is relative to ``workdir``. + + The sandbox keeps the content and writes it back before every + :meth:`run`. The coding agent that writes the script works in this same + directory and does not leave it alone: in 3 of 19 probe-writing + sessions it overwrote the input with two invented cases to try its + script, then deleted the file, and the real run found nothing to read. + """ + payload = data.encode("utf-8") if isinstance(data, str) else bytes(data) + self._inputs[name] = payload + path = self.workdir / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(payload) + return path + + def _restore_inputs(self) -> None: + for name, payload in self._inputs.items(): + path = self.workdir / name + try: + intact = path.read_bytes() == payload + except OSError: + intact = False + if not intact: + logger.warning("Sandbox input %s was changed or removed after it was " + "written; restoring it before the run", name) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(payload) + def run(self, code: str, *, timeout_sec: int = 60) -> SandboxResult: """Write *code* to a numbered script file and execute it. @@ -303,6 +335,7 @@ def run(self, code: str, *, timeout_sec: int = 60) -> SandboxResult: Returns: :class:`SandboxResult` with parsed metrics. """ + self._restore_inputs() with self._counter_lock: self._run_counter += 1 counter = self._run_counter diff --git a/evalrx/analysis/DESIGN.md b/evalrx/analysis/DESIGN.md index 26590f63..ae97b7d7 100644 --- a/evalrx/analysis/DESIGN.md +++ b/evalrx/analysis/DESIGN.md @@ -1,7 +1,7 @@ # LAMBDA 探索 × M2/M4 确证 集成设计 > 状态:**Phase A–D 已实现**(2026-06-27)。如何把 LAMBDA 式探索层(`evalrx/analysis/`)接入 M1→M5 诊断-修复链路。 -> 新增模块:[adjudicate.py](adjudicate.py)(宿主裁决)· [operationalize.py](operationalize.py)(recipe→冻结信号 + in-loop 桥接)· [fused_pipeline.py](fused_pipeline.py)(explore→confirm 编排);in-loop 注入在 [loop.py](../eval_agent/loop.py) `VLDiagnoseLoop._bridge_signals`。测试 `tests/test_analysis/test_{adjudicate,operationalize,fused_pipeline,bridge_inloop,integration_fused}.py`(74 项全过)。 +> 新增模块:[adjudicate.py](adjudicate.py)(宿主裁决)· [operationalize.py](operationalize.py)(recipe→冻结信号 + in-loop 桥接)· [fused_pipeline.py](fused_pipeline.py)(explore→confirm 编排);in-loop 注入在 [stages.py](../eval_agent/loop/stages.py) `Stages.bridge_signals`。测试 `tests/test_analysis/test_{adjudicate,operationalize,fused_pipeline,bridge_inloop,integration_fused}.py`(74 项全过)。 > > **延伸(单轮 viz 管线:图表/观察→M3 + dashboard,含 chat 退役)**:本文档接的是**信号→M2 确证**;让 M3 消费/输出 explorer **图表+观察(机制语言)**、把 viz 提成共享核、退役交互 REPL(只留单轮管线)的已实现设计见 [DESIGN_m3_charts.md](DESIGN_m3_charts.md)。历史行号仅用于追溯,当前代码以文件中的函数名为准。 > 一句话:**LAMBDA 提议、M2 扩族确证、M4(gated on M2)验证、FixAgent 修复——永不用一张图来确证。** 核心新部件是 **operationalization bridge**,把 LAMBDA 发现的复合/切片信号编译成冻结 per-case 信号,使其进入 M2 的 e-BH family。 @@ -32,7 +32,7 @@ M1 ProbeAgent analyzers → probe_results(Result.findings["per_case"] 是 → 推论:若 LAMBDA 只在 M2 **之后**提假设,它发现的任何新信号永远拿不到 e-value,M4 判非 decisive,假设全塌成 INCONCLUSIVE。**必须在 M2 跑之前把信号桥接进它的族。** -**已具备的护栏(漏洞已修)**:充分统计量+宿主重算决策(`_reconstruct_decision`,[stats_tool_generator.py](stats_tool_generator.py));候选族 e-BH(`ebh_survivors`,[fix/verdict.py](../eval_agent/stages/fix/verdict.py));留出 CONFIRM split(`_split_explore_confirm`,[loop.py](../eval_agent/loop.py),`(label, probe_type)` 分层、按 id 不相交)。 +**已具备的护栏(漏洞已修)**:充分统计量+宿主重算决策(`_reconstruct_decision`,[stats_tool_generator.py](stats_tool_generator.py));候选族 e-BH(`ebh_survivors`,[fix/verdict.py](../eval_agent/stages/fix/verdict.py));留出 CONFIRM split(`_split_explore_confirm`,[loop.py](../eval_agent/loop/diagnose.py),`(label, probe_type)` 分层、按 id 不相交)。 --- @@ -119,7 +119,7 @@ def compile_recipe(recipe, records) -> dict[str, float]: **Phase C ✅ — 桥接信号接回 in-loop M2(合成-Result 注入)** - [operationalize.py](operationalize.py):`safe_ident`/`per_case_to_records`(转置 + 把 `analyzer.metric` 消歧成 DSL 标识符)/`bridge_recipes_to_result`(recipe 在已有 analyzer 信号上编译 → 合成 `explored` analyzer Result)。 -- [loop.py](../eval_agent/loop.py):`VLDiagnoseLoop` 加 `signal_recipes` 参数 + `_bridge_signals`(M1→M2 之间注入,no-op 默认)。**leak-free by construction**:recipe 必须 out-of-band 预注册(B2 留出集或手写),非窥探本轮 label,故 in-loop 测它等同测预注册 analyzer。 +- [diagnose.py](../eval_agent/loop/diagnose.py):`VLDiagnoseLoop` 加 `signal_recipes` 参数;注入在 [stages.py](../eval_agent/loop/stages.py) `Stages.bridge_signals`(M1→M2 之间注入,no-op 默认)。**leak-free by construction**:recipe 必须 out-of-band 预注册(B2 留出集或手写),非窥探本轮 label,故 in-loop 测它等同测预注册 analyzer。 **Phase D ✅ — 测试**:双盲守卫(explorer 只见 explore、verdict 算在不相交 confirm);宿主裁决(自报 `reject=true`/`e_value=1e9` 被结构性丢弃重算);**不合并**(不同 estimand → 两个独立 e-BH 成员,从不合并 e-value);确定性复现(同 seed 同输出);`expr` 编译/安全;真实 explorer codegen→bridge→M2 端到端。 diff --git a/evalrx/analysis/explorer.py b/evalrx/analysis/explorer.py index fa081820..44d653d7 100755 --- a/evalrx/analysis/explorer.py +++ b/evalrx/analysis/explorer.py @@ -552,8 +552,7 @@ def _run_explore_loop( ) def _write_input(self, rows: list[dict[str, Any]]) -> None: - path = Path(self._sandbox.workdir) / RECORDS_FILENAME - path.write_text(json.dumps(rows, default=str), encoding="utf-8") + self._sandbox.put(RECORDS_FILENAME, json.dumps(rows, default=str)) def _write_code(self, question: str, profile: dict[str, Any]) -> tuple[str, str]: prompt = _GENERATE_PROMPT_RECORDS.format( diff --git a/evalrx/analysis/stats_tool_generator.py b/evalrx/analysis/stats_tool_generator.py index bfd8fa72..d5337968 100755 --- a/evalrx/analysis/stats_tool_generator.py +++ b/evalrx/analysis/stats_tool_generator.py @@ -222,8 +222,7 @@ def _write_input(self, inp: StatsInput) -> None: "scalars": inp.scalars, "groups": inp.groups, } - path = Path(self._sandbox.workdir) / _INPUT_FILENAME - path.write_text(json.dumps(payload), encoding="utf-8") + self._sandbox.put(_INPUT_FILENAME, json.dumps(payload)) def _write_code(self, need: str, inp: StatsInput) -> tuple[str, str]: """Return ``(code, source)`` from the CLI agent or the judge.""" diff --git a/evalrx/analyzers/attention/relative_attn.py b/evalrx/analyzers/attention/relative_attn.py index eff91c81..37f59de0 100755 --- a/evalrx/analyzers/attention/relative_attn.py +++ b/evalrx/analyzers/attention/relative_attn.py @@ -261,7 +261,7 @@ def save_overlay(self, key: str, path: "Any", **kwargs) -> bool: def image_overlays(self, fig_dir: "Any", stem_prefix: str) -> "list[Any]": """Save every available overlay under ``fig_dir``; return the paths. - Hook called by :class:`~evalrx.eval_agent.run_logger.RunLogger` + Hook called by :class:`~evalrx.eval_agent.runlog.logger.RunLogger` (duck-typed — any :class:`Result` subclass may define this) so the overlay PNGs land alongside the bare heatmaps and get forwarded to a multimodal judge the same way. diff --git a/evalrx/analyzers/attention/rollout.py b/evalrx/analyzers/attention/rollout.py index 1a8bd442..fdeec184 100755 --- a/evalrx/analyzers/attention/rollout.py +++ b/evalrx/analyzers/attention/rollout.py @@ -43,6 +43,7 @@ class AttentionRolloutAnalyzer(Analyzer): name = "attention_rollout" requires = frozenset({Capability.ATTENTION}) + single_case = True applies_to_modalities = frozenset({"text", "image"}) top_k: int diff --git a/evalrx/analyzers/geometry/cka.py b/evalrx/analyzers/geometry/cka.py index 249ec9a1..79375530 100755 --- a/evalrx/analyzers/geometry/cka.py +++ b/evalrx/analyzers/geometry/cka.py @@ -43,6 +43,7 @@ class CKAAnalyzer(Analyzer): name = "cka" requires = frozenset({Capability.HIDDEN_STATES}) + single_case = True applies_to_modalities = frozenset({"text", "image"}) def _run(self, model: "Model", cases: "CaseBatch") -> Result: diff --git a/evalrx/analyzers/hallucination/chair.py b/evalrx/analyzers/hallucination/chair.py index 8f6ac34e..bf45b960 100755 --- a/evalrx/analyzers/hallucination/chair.py +++ b/evalrx/analyzers/hallucination/chair.py @@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, Iterable -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, labelled_answers from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -60,8 +60,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: per_case = [] chair_is = [] n_with_hallucination = 0 - for case in cases: - caption = model.generate(case.inputs) + for case, caption in zip(cases, labelled_answers(model, cases)): mentioned = extract_objects(caption, self.object_vocab) gt = case.metadata.get(self.gt_key, []) sc = chair_score(mentioned, gt) diff --git a/evalrx/analyzers/hallucination/pope.py b/evalrx/analyzers/hallucination/pope.py index 862f5654..1337bf37 100755 --- a/evalrx/analyzers/hallucination/pope.py +++ b/evalrx/analyzers/hallucination/pope.py @@ -15,7 +15,7 @@ import re from typing import TYPE_CHECKING, Optional -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, labelled_answers from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -63,9 +63,9 @@ def __init__(self, label_key: str = "pope_label") -> None: def _run(self, model: "Model", cases: "CaseBatch") -> Result: tp = fp = fn = tn = unparsed = 0 per_case = [] - for case in cases: + for case, answer in zip(cases, labelled_answers(model, cases)): gold = str(case.metadata.get(self.label_key, "")).strip().lower() - pred = parse_yes_no(model.generate(case.inputs)) + pred = parse_yes_no(answer) is_correct = pred == gold if gold in {"yes", "no"} and pred is not None else None per_case.append({ "id": case.id, diff --git a/evalrx/analyzers/hallucination/selfcheck.py b/evalrx/analyzers/hallucination/selfcheck.py index 07484020..071c0069 100644 --- a/evalrx/analyzers/hallucination/selfcheck.py +++ b/evalrx/analyzers/hallucination/selfcheck.py @@ -20,7 +20,7 @@ import re from typing import TYPE_CHECKING, Any, Optional -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -96,41 +96,39 @@ def __init__( min_sentence_chars=min_sentence_chars, ) + def _probe_case(self, case: Any) -> Probe[dict[str, Any]]: + baseline = str(case.observed or "").strip() + baseline_from = "observed" + if not baseline: + baseline = str((yield Ask([case.inputs]))[0]) + baseline_from = "generated" + sentences = split_sentences(baseline, self.min_sentence_chars) + entry: dict[str, Any] = { + "sample_id": case.id, + "baseline_from": baseline_from, + "n_sentences": len(sentences), + } + if not sentences: + entry["skipped"] = "no scoreable sentence in the baseline answer" + return entry + samples = [str(s) for s in (yield Ask([case.inputs] * self.n_samples, self.gen_kwargs))] + # SelfCheckGPT scores a sentence by its support in OTHER samples; + # a sentence no resample reproduces is the hallucination suspect. + sentence_scores = [ + 1.0 - max(containment(sent, sample) for sample in samples) + for sent in sentences + ] + entry["selfcheck_inconsistency"] = round( + sum(sentence_scores) / len(sentence_scores), 4 + ) + entry["selfcheck_worst_sentence"] = round(max(sentence_scores), 4) + worst = sentences[sentence_scores.index(max(sentence_scores))] + entry["worst_sentence_text"] = worst[:200] + return entry + def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - baseline = str(case.observed or "").strip() - baseline_from = "observed" - if not baseline: - baseline = str(model.generate(case.inputs)) - baseline_from = "generated" - sentences = split_sentences(baseline, self.min_sentence_chars) - entry: dict[str, Any] = { - "sample_id": case.id, - "baseline_from": baseline_from, - "n_sentences": len(sentences), - } - if not sentences: - entry["skipped"] = "no scoreable sentence in the baseline answer" - per_case.append(entry) - continue - samples = [ - str(model.generate(case.inputs, **self.gen_kwargs)) - for _ in range(self.n_samples) - ] - # SelfCheckGPT scores a sentence by its support in OTHER samples; - # a sentence no resample reproduces is the hallucination suspect. - sentence_scores = [ - 1.0 - max(containment(sent, sample) for sample in samples) - for sent in sentences - ] - entry["selfcheck_inconsistency"] = round( - sum(sentence_scores) / len(sentence_scores), 4 - ) - entry["selfcheck_worst_sentence"] = round(max(sentence_scores), 4) - worst = sentences[sentence_scores.index(max(sentence_scores))] - entry["worst_sentence_text"] = worst[:200] - per_case.append(entry) + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) scored = [c["selfcheck_inconsistency"] for c in per_case if "selfcheck_inconsistency" in c] temperature = self.gen_kwargs.get("temperature") diff --git a/evalrx/analyzers/perturbation/_shapley.py b/evalrx/analyzers/perturbation/_shapley.py index f55ae744..5a7fdb7b 100755 --- a/evalrx/analyzers/perturbation/_shapley.py +++ b/evalrx/analyzers/perturbation/_shapley.py @@ -52,3 +52,20 @@ def val(kept: set) -> float: phi[p] += cur - prev prev = cur return {p: phi[p] / n_samples for p in players} + + +def coalitions(players: Iterable, n_samples: int = 64, seed: int = 0) -> "list[frozenset]": + """Every coalition :func:`shapley_values` evaluates for these arguments. + + The sampler never looks at a value, so an analyzer can ask the model for + all of them in one batch and hand :func:`shapley_values` a lookup. In + first-use order; the empty coalition is first. + """ + seen: "dict[frozenset, None]" = {} + + def record(kept: set) -> float: + seen.setdefault(frozenset(kept)) + return 0.0 + + shapley_values(players, record, n_samples=n_samples, seed=seed) + return list(seen) diff --git a/evalrx/analyzers/perturbation/context_shap.py b/evalrx/analyzers/perturbation/context_shap.py index bce10258..4e62a04d 100644 --- a/evalrx/analyzers/perturbation/context_shap.py +++ b/evalrx/analyzers/perturbation/context_shap.py @@ -24,8 +24,8 @@ import re from typing import TYPE_CHECKING, Any, Callable, Optional -from evalrx.analyzers.perturbation._shapley import shapley_values -from evalrx.core.analyzer import Analyzer +from evalrx.analyzers.perturbation._shapley import coalitions, shapley_values +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -108,56 +108,8 @@ def __init__( self.context_fn = context_fn or default_context_fn def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - context = self.context_fn(case) - prompt = case.inputs.prompt or "" - entry: dict[str, Any] = {"sample_id": case.id} - if not context: - entry["skipped"] = "no context supplied (metadata['context'] or context_fn)" - per_case.append(entry) - continue - if prompt.count(context) != 1: - entry["skipped"] = ( - "context must occur exactly once verbatim in the prompt " - f"(found {prompt.count(context)} occurrences)" - ) - per_case.append(entry) - continue - chunks = split_chunks(context, self.granularity, self.max_chunks) - entry["n_chunks"] = len(chunks) - if len(chunks) < 2: - entry["skipped"] = "context has a single chunk — nothing to attribute" - per_case.append(entry) - continue - - baseline = str(case.observed or "") or str(model.generate(case.inputs)) - - def value_fn(kept: set) -> float: - kept_text = "\n\n".join(chunks[i] for i in sorted(kept)) - ablated = prompt.replace(context, kept_text, 1) - answer = str(model.generate(dataclasses.replace(case.inputs, prompt=ablated))) - return _similarity(answer, baseline) - - coalition_cache: dict[frozenset, float] = {} - - def cached_value(kept: set) -> float: - key = frozenset(kept) - if key not in coalition_cache: - coalition_cache[key] = value_fn(set(key)) - return coalition_cache[key] - - phi = shapley_values( - range(len(chunks)), cached_value, n_samples=self.n_samples, seed=self.seed - ) - no_context = cached_value(set()) - top_index = max(phi, key=lambda k: abs(phi[k])) - total_abs = sum(abs(v) for v in phi.values()) or 1.0 - entry["context_dependence"] = round(1.0 - no_context, 4) - entry["top_chunk_index"] = int(top_index) - entry["top_chunk_share"] = round(abs(phi[top_index]) / total_abs, 4) - entry["shapley"] = {str(k): round(v, 4) for k, v in phi.items()} - per_case.append(entry) + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) deps = [c["context_dependence"] for c in per_case if "context_dependence" in c] findings: dict[str, Any] = { @@ -178,3 +130,48 @@ def cached_value(kept: set) -> float: ), } return Result(analyzer=self.name, model=repr(model), cases=cases, findings=findings) + + def _probe_case(self, case: "FailureCase") -> Probe[dict[str, Any]]: + """One case's row: every context ablation the estimate needs, asked at once.""" + context = self.context_fn(case) + prompt = case.inputs.prompt or "" + entry: dict[str, Any] = {"sample_id": case.id} + if not context: + entry["skipped"] = "no context supplied (metadata['context'] or context_fn)" + return entry + if prompt.count(context) != 1: + entry["skipped"] = ( + "context must occur exactly once verbatim in the prompt " + f"(found {prompt.count(context)} occurrences)" + ) + return entry + chunks = split_chunks(context, self.granularity, self.max_chunks) + entry["n_chunks"] = len(chunks) + if len(chunks) < 2: + entry["skipped"] = "context has a single chunk — nothing to attribute" + return entry + + players = range(len(chunks)) + kept_sets = coalitions(players, n_samples=self.n_samples, seed=self.seed) + ablated = [ + dataclasses.replace(case.inputs, prompt=prompt.replace( + context, "\n\n".join(chunks[i] for i in sorted(kept)), 1)) + for kept in kept_sets + ] + baseline = str(case.observed or "") + if baseline: + answers = yield Ask(ablated) + else: + baseline, *answers = yield Ask([case.inputs, *ablated]) + value = {kept: _similarity(str(answer), str(baseline)) + for kept, answer in zip(kept_sets, answers)} + + phi = shapley_values(players, lambda kept: value[frozenset(kept)], + n_samples=self.n_samples, seed=self.seed) + top_index = max(phi, key=lambda k: abs(phi[k])) + total_abs = sum(abs(v) for v in phi.values()) or 1.0 + entry["context_dependence"] = round(1.0 - value[frozenset()], 4) + entry["top_chunk_index"] = int(top_index) + entry["top_chunk_share"] = round(abs(phi[top_index]) / total_abs, 4) + entry["shapley"] = {str(k): round(v, 4) for k, v in phi.items()} + return entry diff --git a/evalrx/analyzers/perturbation/cot_faithfulness.py b/evalrx/analyzers/perturbation/cot_faithfulness.py index a2a570e5..960e9f65 100644 --- a/evalrx/analyzers/perturbation/cot_faithfulness.py +++ b/evalrx/analyzers/perturbation/cot_faithfulness.py @@ -35,7 +35,7 @@ import re from typing import TYPE_CHECKING, Any, Callable, Optional -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -120,52 +120,17 @@ def __init__( self.grader = grader or _default_grader def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] + selected = list(cases.stratified_head(self.max_cases)) + per_case = run_probes(model, [self._probe_case(case) for case in selected]) + # Contract: numeric vectors must not sit in a per-case row (they read + # as signals and reach no statistic). The trajectory moves to + # findings["answer_trajectory_by_case"]; its scalar reductions + # (first_correct_frac/drift_away/late_rescue/...) stay on the row. answer_trajectory_by_case: dict[str, list[int]] = {} - for case in cases.stratified_head(self.max_cases): - prompt = case.inputs.prompt or "" - direct = str(model.generate(case.inputs)) - cot_out = str( - model.generate(dataclasses.replace(case.inputs, prompt=f"{prompt}\n\n{_COT_SUFFIX}")) - ) - full_answer = _normalize(self.answer_fn(cot_out)) - direct_answer = _normalize(self.answer_fn(direct)) - sentences = _split_reasoning(cot_out) - entry: dict[str, Any] = { - "sample_id": case.id, - "cot_sentences": len(sentences), - } - if not full_answer or not sentences: - entry["skipped"] = "no extractable answer or empty reasoning" - per_case.append(entry) - continue - entry["cot_changed_answer"] = int(direct_answer != full_answer) - matches = 0 - early_outputs: list[str] = [] - # never replay the WHOLE chain as an "early" probe (trivial match) - cap = len(sentences) - 1 if len(sentences) > 1 else 1 - for frac in self.truncation_fracs: - keep = max(1, min(cap, math.ceil(frac * len(sentences)))) - partial = " ".join(sentences[:keep]) - early_prompt = ( - f"{prompt}\n\nReasoning so far:\n{partial}\n\n" - "Given only this reasoning, give the final answer now in the " - "form 'Answer: '." - ) - early = str(model.generate(dataclasses.replace(case.inputs, prompt=early_prompt))) - early_outputs.append(early) - if _normalize(self.answer_fn(early)) == full_answer: - matches += 1 - entry["early_answer_match_rate"] = round(matches / len(self.truncation_fracs), 4) - entry.update(self._trajectory_columns(case, early_outputs, cot_out, direct)) - # Contract: numeric vectors must not sit in a per-case row (they read - # as signals and reach no statistic). The trajectory moves to - # findings["answer_trajectory_by_case"]; its scalar reductions - # (first_correct_frac/drift_away/late_rescue/...) stay on the row. + for entry in per_case: trajectory = entry.pop("answer_trajectory", None) if trajectory is not None: - answer_trajectory_by_case[case.id] = trajectory - per_case.append(entry) + answer_trajectory_by_case[entry["sample_id"]] = trajectory rates = [c["early_answer_match_rate"] for c in per_case if "early_answer_match_rate" in c] graded = [c for c in per_case if "final_correct" in c] @@ -211,6 +176,42 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: return Result(analyzer=self.name, model=repr(model), cases=cases, findings=findings) # ------------------------------------------------------------------ + def _probe_case(self, case: Any) -> Probe[dict[str, Any]]: + prompt = case.inputs.prompt or "" + # The direct answer is asked again rather than read from + # ``case.observed``: it is the control the chain's answer is compared to. + direct, cot_out = map(str, (yield Ask([ + case.inputs, + dataclasses.replace(case.inputs, prompt=f"{prompt}\n\n{_COT_SUFFIX}"), + ]))) + full_answer = _normalize(self.answer_fn(cot_out)) + direct_answer = _normalize(self.answer_fn(direct)) + sentences = _split_reasoning(cot_out) + entry: dict[str, Any] = { + "sample_id": case.id, + "cot_sentences": len(sentences), + } + if not full_answer or not sentences: + entry["skipped"] = "no extractable answer or empty reasoning" + return entry + entry["cot_changed_answer"] = int(direct_answer != full_answer) + # never replay the WHOLE chain as an "early" probe (trivial match) + cap = len(sentences) - 1 if len(sentences) > 1 else 1 + early_prompts = [] + for frac in self.truncation_fracs: + keep = max(1, min(cap, math.ceil(frac * len(sentences)))) + partial = " ".join(sentences[:keep]) + early_prompts.append(dataclasses.replace(case.inputs, prompt=( + f"{prompt}\n\nReasoning so far:\n{partial}\n\n" + "Given only this reasoning, give the final answer now in the " + "form 'Answer: '." + ))) + early_outputs = [str(out) for out in (yield Ask(early_prompts))] + matches = sum(_normalize(self.answer_fn(early)) == full_answer for early in early_outputs) + entry["early_answer_match_rate"] = round(matches / len(self.truncation_fracs), 4) + entry.update(self._trajectory_columns(case, early_outputs, cot_out, direct)) + return entry + def _trajectory_columns( self, case: Any, early_outputs: list[str], cot_out: str, direct: str ) -> dict[str, Any]: diff --git a/evalrx/analyzers/perturbation/format_sensitivity.py b/evalrx/analyzers/perturbation/format_sensitivity.py index 91769ec7..a8f14c37 100644 --- a/evalrx/analyzers/perturbation/format_sensitivity.py +++ b/evalrx/analyzers/perturbation/format_sensitivity.py @@ -27,7 +27,7 @@ from collections import Counter from typing import TYPE_CHECKING, Any, Optional -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -167,55 +167,48 @@ def _variant_prompt( rotated, ) - def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - options, block = extract_options(case) - entry: dict[str, Any] = {"sample_id": case.id, "n_options": len(options)} - if len(options) < 2: - entry["skipped"] = "no multiple-choice options found (2..26 required)" - per_case.append(entry) - continue - prompt = case.inputs.prompt or "" - shifts = list(range(1, min(self.n_variants, len(options) - 1) + 1)) - chosen_contents: list[str] = [] - chosen_letters: list[str] = [] - n_unparsed = 0 - # Identity variant: reuse the recorded baseline answer only when the - # prompt contains the lettered block the letters decode against; - # otherwise every variant (identity included) uses OUR rendered - # block, so all letters map to options the model actually saw. - if block is not None and case.observed: - base_out = str(case.observed) - else: - identity_prompt, _ = self._variant_prompt(prompt, block, options, 0) - base_out = str( - model.generate(dataclasses.replace(case.inputs, prompt=identity_prompt)) - ) - base_letter = parse_choice(base_out, len(options)) - if base_letter: - chosen_letters.append(base_letter) - chosen_contents.append(options[ord(base_letter) - 65]) - else: + def _probe_case(self, case: Any) -> Probe[dict[str, Any]]: + options, block = extract_options(case) + entry: dict[str, Any] = {"sample_id": case.id, "n_options": len(options)} + if len(options) < 2: + entry["skipped"] = "no multiple-choice options found (2..26 required)" + return entry + prompt = case.inputs.prompt or "" + shifts = list(range(1, min(self.n_variants, len(options) - 1) + 1)) + # Identity variant: reuse the recorded baseline answer only when the + # prompt contains the lettered block the letters decode against; + # otherwise every variant (identity included) uses OUR rendered + # block, so all letters map to options the model actually saw. + reuse = block is not None and bool(case.observed) + variants = [self._variant_prompt(prompt, block, options, shift) + for shift in ([] if reuse else [0]) + shifts] + outs = [str(out) for out in (yield Ask( + [dataclasses.replace(case.inputs, prompt=text) for text, _ in variants]))] + answered = [(str(case.observed), options)] if reuse else [] + answered += [(out, rotated) for out, (_, rotated) in zip(outs, variants)] + chosen_contents: list[str] = [] + chosen_letters: list[str] = [] + n_unparsed = 0 + for out, shown in answered: + letter = parse_choice(out, len(shown)) + if not letter: n_unparsed += 1 - for shift in shifts: - variant_prompt, rotated = self._variant_prompt(prompt, block, options, shift) - out = str(model.generate(dataclasses.replace(case.inputs, prompt=variant_prompt))) - letter = parse_choice(out, len(rotated)) - if not letter: - n_unparsed += 1 - continue - chosen_letters.append(letter) - chosen_contents.append(rotated[ord(letter) - 65]) - entry["n_variants"] = 1 + len(shifts) - entry["n_unparsed"] = n_unparsed - if chosen_contents: - content_modal = Counter(chosen_contents).most_common(1)[0][1] - letter_modal = Counter(chosen_letters).most_common(1)[0] - entry["format_flip_rate"] = round(1.0 - content_modal / len(chosen_contents), 4) - entry["positional_bias"] = round(letter_modal[1] / len(chosen_letters), 4) - entry["modal_letter"] = letter_modal[0] - per_case.append(entry) + continue + chosen_letters.append(letter) + chosen_contents.append(shown[ord(letter) - 65]) + entry["n_variants"] = 1 + len(shifts) + entry["n_unparsed"] = n_unparsed + if chosen_contents: + content_modal = Counter(chosen_contents).most_common(1)[0][1] + letter_modal = Counter(chosen_letters).most_common(1)[0] + entry["format_flip_rate"] = round(1.0 - content_modal / len(chosen_contents), 4) + entry["positional_bias"] = round(letter_modal[1] / len(chosen_letters), 4) + entry["modal_letter"] = letter_modal[0] + return entry + + def _run(self, model: "Model", cases: "CaseBatch") -> Result: + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) flips = [c["format_flip_rate"] for c in per_case if "format_flip_rate" in c] letters = Counter(c.get("modal_letter") for c in per_case if c.get("modal_letter")) diff --git a/evalrx/analyzers/perturbation/mm_shap.py b/evalrx/analyzers/perturbation/mm_shap.py index 14733665..a54edb44 100755 --- a/evalrx/analyzers/perturbation/mm_shap.py +++ b/evalrx/analyzers/perturbation/mm_shap.py @@ -28,7 +28,7 @@ from typing import TYPE_CHECKING, Callable, Optional -from evalrx.analyzers.perturbation._shapley import shapley_values +from evalrx.analyzers.perturbation._shapley import coalitions, shapley_values from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability from evalrx.core.case import MEDIA_SLOTS, Inputs @@ -51,6 +51,7 @@ class MMShapAnalyzer(Analyzer): name = "mm_shap" requires = frozenset({Capability.LOGPROBS}) + single_case = True applies_to_modalities = frozenset({"text", "image", "audio", "video"}) signal_docs = { 'audio_contribution': 'How much the audio drove the answer.', @@ -87,30 +88,34 @@ def __init__( ) -> None: super().__init__(score_fn=score_fn, n_samples=n_samples, mask_token=mask_token, top_k=top_k, seed=seed) - def _default_scorer(self, model: "Model") -> Callable[[Inputs], float]: - def score(inputs: Inputs) -> float: - lps = model.logprobs(inputs) - return sum(t.logprob for t in lps) / len(lps) if lps else 0.0 - return score - def _run(self, model: "Model", cases: "CaseBatch") -> Result: case = cases[0] words = str(case.inputs.prompt).split() filled = [s for s in MEDIA_SLOTS if getattr(case.inputs, s, None) is not None] - score = self.score_fn or self._default_scorer(model) - players: list = list(range(len(words))) players += [_slot_player(s) for s in filled] - def value(kept: set) -> float: - masked = " ".join(w if i in kept else self.mask_token for i, w in enumerate(words)) + def masked(kept: "set | frozenset") -> Inputs: + prompt = " ".join(w if i in kept else self.mask_token for i, w in enumerate(words)) slots = { s: (getattr(case.inputs, s) if _slot_player(s) in kept else None) for s in filled } - return score(Inputs(prompt=masked, **slots)) - - shap = shapley_values(players, value, n_samples=self.n_samples, seed=self.seed) + return Inputs(prompt=prompt, **slots) + + if self.score_fn is not None: + score_fn = self.score_fn + shap = shapley_values(players, lambda kept: score_fn(masked(kept)), + n_samples=self.n_samples, seed=self.seed) + else: + # The model's mean answer logprob: every masked input the estimate + # needs is scored in one batch, then looked up. + kept_sets = coalitions(players, n_samples=self.n_samples, seed=self.seed) + rows = model.logprobs_batch([masked(kept) for kept in kept_sets]) + values = {kept: (sum(t.logprob for t in lps) / len(lps) if lps else 0.0) + for kept, lps in zip(kept_sets, rows)} + shap = shapley_values(players, lambda kept: values[frozenset(kept)], + n_samples=self.n_samples, seed=self.seed) text_contrib = sum(abs(shap[i]) for i in range(len(words))) media_contrib = {s: abs(shap.get(_slot_player(s), 0.0)) for s in filled} total = text_contrib + sum(media_contrib.values()) or 1.0 diff --git a/evalrx/analyzers/perturbation/modality_ablation.py b/evalrx/analyzers/perturbation/modality_ablation.py index c563abe7..16b9c4e2 100644 --- a/evalrx/analyzers/perturbation/modality_ablation.py +++ b/evalrx/analyzers/perturbation/modality_ablation.py @@ -143,24 +143,34 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: ungrounded = {s: 0 for s in MEDIA_SLOTS} modes_used: dict[str, str] = {} + # 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]]]] = [] + asked: list[Any] = [] for case in selected: - base_answer = str(model.generate(case.inputs)) + asked.append(case.inputs) + ablations: list[tuple[str, str]] = [] + for slot in self._slots_of(case): + donor: Any = self._donor(selected, slot, case) if self.mode == "swap" 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")) + asked.append(dataclasses.replace(case.inputs, **{slot: donor})) + plan.append((case, ablations)) + answers = iter(str(out) for out in model.generate_batch(asked)) + + for case, ablations in plan: + base_answer = next(answers) 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 in self._slots_of(case): - donor: Any = self._donor(selected, slot, case) if self.mode == "swap" else None - # swap with no donor degrades to drop rather than skipping: the - # weaker evidence is still evidence, and silently probing nothing - # would look identical to a fully-grounded model. - effective = "swap" if donor is not None else "drop" + for slot, effective in ablations: modes_used[slot] = effective - ablated = dataclasses.replace(case.inputs, **{slot: donor}) - - answer = str(model.generate(ablated)) + answer = next(answers) changed = _norm_answer(answer) != base_key probed[slot] += 1 diff --git a/evalrx/analyzers/perturbation/perturbation_battery.py b/evalrx/analyzers/perturbation/perturbation_battery.py index 6b560ce1..24a13157 100644 --- a/evalrx/analyzers/perturbation/perturbation_battery.py +++ b/evalrx/analyzers/perturbation/perturbation_battery.py @@ -31,7 +31,7 @@ from typing import TYPE_CHECKING, Any, Callable, Optional from evalrx.analyzers.reasoning._text import extract_answer, normalize_answer -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -165,9 +165,9 @@ def __init__( self.answer_fn = answer_fn or extract_answer def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - per_case.append(self._probe_case(model, case)) + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)], + tolerant=True) scored = [c for c in per_case if "invariance_break_rate" in c] applied = {name for c in scored for name in c.get("applied", [])} @@ -204,50 +204,46 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: return Result(analyzer=self.name, model=repr(model), cases=cases, findings=findings) # ------------------------------------------------------------------ - def _probe_case(self, model: "Model", case: "FailureCase") -> dict[str, Any]: + def _probe_case(self, case: "FailureCase") -> Probe[dict[str, Any]]: prompt = str(case.inputs.prompt or "") entry: dict[str, Any] = {"sample_id": case.id} if not prompt.strip(): entry["skipped"] = "empty prompt" return entry - # Treat a transient backend failure as missing evidence for this case. - # Letting it escape aborts the whole battery, which makes the most - # relevant M1 evidence disappear after just one timed-out audio clip. - try: - baseline = normalize_answer( - self.answer_fn(model.generate(case.inputs, **self.gen_kwargs)) - ) - except Exception as exc: - entry["skipped"] = f"baseline request failed: {type(exc).__name__}: {str(exc)[:160]}" - return entry - entry["baseline_answer"] = baseline[:80] - - applied: list[str] = [] - preserving_flips: list[int] = [] - altering_flips: list[int] = [] + variants: list[tuple[str, str, str]] = [] for name, kind, fn in self.perturbations: try: variant = fn(prompt) except Exception: # pragma: no cover - user-supplied perturbation variant = None - if not variant or variant == prompt: - continue - applied.append(name) - try: - answer = normalize_answer( - self.answer_fn( - model.generate( - dataclasses.replace(case.inputs, prompt=variant), **self.gen_kwargs - ) - ) - ) - except Exception as exc: + if variant and variant != prompt: + variants.append((name, kind, variant)) + # The baseline is asked again with the variants rather than read from + # ``case.observed``: it is the control each variant's answer is compared to. + baseline_out, *variant_outs = yield Ask( + [case.inputs, *(dataclasses.replace(case.inputs, prompt=v) for _, _, v in variants)], + self.gen_kwargs) + # A failed request is missing evidence for this case. Letting it escape + # aborts the whole battery, which makes the most relevant M1 evidence + # disappear after just one timed-out audio clip. + if isinstance(baseline_out, Exception): + entry["skipped"] = (f"baseline request failed: {type(baseline_out).__name__}: " + f"{str(baseline_out)[:160]}") + return entry + baseline = normalize_answer(self.answer_fn(baseline_out)) + entry["baseline_answer"] = baseline[:80] + + applied = [name for name, _, _ in variants] + preserving_flips: list[int] = [] + altering_flips: list[int] = [] + for (name, kind, _), out in zip(variants, variant_outs): + if isinstance(out, Exception): entry.setdefault("request_errors", {})[name] = ( - f"{type(exc).__name__}: {str(exc)[:160]}" + f"{type(out).__name__}: {str(out)[:160]}" ) continue - flipped = int(answer != baseline) + flipped = int(normalize_answer(self.answer_fn(out)) != baseline) entry[f"{name}_flipped"] = flipped (preserving_flips if kind == PRESERVING else altering_flips).append(flipped) diff --git a/evalrx/analyzers/perturbation/prompt_contrast.py b/evalrx/analyzers/perturbation/prompt_contrast.py index eb9fb723..03f261d8 100755 --- a/evalrx/analyzers/perturbation/prompt_contrast.py +++ b/evalrx/analyzers/perturbation/prompt_contrast.py @@ -185,23 +185,26 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: # mixes both, which the McNemar (flips) and the no-free-lunch check # (breaks of correct answers) each need. selected = cases.stratified_head(self.max_cases) - for case in selected: - prompt = str(getattr(case.inputs, "prompt", "")) - for strat, template in self.strategies.items(): - rewritten = template.format(prompt=prompt) - # dataclasses.replace, not a bare Inputs(prompt=..., image=...): - # this analyzer is also compatible with audio models (it - # declares "text" in applies_to_modalities, which intersects - # any modality set that includes text prompts) — a fresh - # Inputs(image=...) silently dropped .audio, so the re-ask - # would have answered without hearing the clip. - out = str(model.generate(dataclasses.replace(case.inputs, prompt=rewritten))) - verdict = score(case, out) - answers[strat][case.id] = out[:200] - if verdict is None: - n_unscored += 1 - continue - by_strategy[strat][case.id] = float(bool(verdict)) + # dataclasses.replace, not a bare Inputs(prompt=..., image=...): this + # analyzer is also compatible with audio models (it declares "text" in + # applies_to_modalities, which intersects any modality set that + # includes text prompts) — a fresh Inputs(image=...) silently dropped + # .audio, so the re-ask would have answered without hearing the clip. + # The baseline strategy is asked again too, not read from + # ``case.observed``: it is the control the other strategies are paired + # against. + 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): + out = str(out) + verdict = score(case, out) + answers[strat][case.id] = out[:200] + if verdict is None: + n_unscored += 1 + continue + by_strategy[strat][case.id] = float(bool(verdict)) # Per-case repair/breakage flags relative to baseline — stored in # ARTIFACTS, not findings["per_case"]. As label-association signals diff --git a/evalrx/analyzers/perturbation/rise.py b/evalrx/analyzers/perturbation/rise.py index 86877d8f..6805498a 100755 --- a/evalrx/analyzers/perturbation/rise.py +++ b/evalrx/analyzers/perturbation/rise.py @@ -44,6 +44,7 @@ class RISEAnalyzer(Analyzer): name = "rise" requires = frozenset({Capability.GENERATE}) + single_case = True applies_to_modalities = frozenset({"text"}) score_fn: Optional[Callable[[str], float]] @@ -76,14 +77,13 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: n = len(words) sal = [0.0] * n cnt = [0] * n - n_calls = 0 - for _ in range(self.n_masks): - mask = [rng.random() < self.keep_prob for _ in range(n)] - if not any(mask): - continue - masked = " ".join(w if m else self.mask_token for w, m in zip(words, mask)) - score = float(self.score_fn(model.generate(masked))) - n_calls += 1 + masks = [mask for mask in ([rng.random() < self.keep_prob for _ in range(n)] + for _ in range(self.n_masks)) if any(mask)] + outputs = model.generate_batch([ + " ".join(w if m else self.mask_token for w, m in zip(words, mask)) for mask in masks]) + n_calls = len(masks) + for mask, output in zip(masks, outputs): + score = float(self.score_fn(output)) for j, keep in enumerate(mask): if keep: sal[j] += score diff --git a/evalrx/analyzers/perturbation/vl_shap.py b/evalrx/analyzers/perturbation/vl_shap.py index 177904ae..2383b3c2 100755 --- a/evalrx/analyzers/perturbation/vl_shap.py +++ b/evalrx/analyzers/perturbation/vl_shap.py @@ -25,13 +25,15 @@ import math from typing import TYPE_CHECKING, Callable, Optional -from evalrx.analyzers.perturbation._shapley import shapley_values +from evalrx.analyzers.perturbation._shapley import coalitions, shapley_values from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability from evalrx.core.case import Inputs from evalrx.core.registry import register_analyzer from evalrx.core.result import Result +_MASKED_IMAGES_AT_ONCE = 64 + if TYPE_CHECKING: from evalrx.core.case import CaseBatch from evalrx.core.model import Model @@ -43,6 +45,7 @@ class VLShapAnalyzer(Analyzer): name = "vl_shap" requires = frozenset({Capability.LOGPROBS}) + single_case = True applies_to_modalities = frozenset({"image"}) # Its default scorer dereferences case.inputs.image, so an omni model on an # audio batch matched here and then raised on the first case. @@ -66,6 +69,11 @@ def __init__( n_samples=n_samples, top_k=top_k, seed=seed) def _default_region_value(self, model: "Model", case) -> Callable[[set], float]: + """The model's mean answer logprob with only the kept regions visible. + + Every masked image the estimate needs is scored up front, in + ``logprobs_batch`` calls; the returned function looks the value up. + """ from PIL import Image # lazy image = case.inputs.image @@ -75,17 +83,26 @@ def _default_region_value(self, model: "Model", case) -> Callable[[set], float]: W, H = image.size cw, ch = W / side, H / side - def value(kept: set) -> float: - masked = image.copy() + def masked(kept: frozenset) -> Inputs: + visible = image.copy() black = Image.new(image.mode, (max(1, int(cw)), max(1, int(ch))), 0) for r in range(self.n_regions): if r in kept: continue gx, gy = r % side, r // side - masked.paste(black, (int(gx * cw), int(gy * ch))) - lps = model.logprobs(Inputs(prompt=case.inputs.prompt, image=masked)) - return sum(t.logprob for t in lps) / len(lps) if lps else 0.0 - return value + visible.paste(black, (int(gx * cw), int(gy * ch))) + return Inputs(prompt=case.inputs.prompt, image=visible) + + kept_sets = coalitions(range(self.n_regions), n_samples=self.n_samples, seed=self.seed) + values: dict[frozenset, float] = {} + # A chunk at a time: each coalition is its own copy of the image, and + # the defaults ask for several hundred of them. + for start in range(0, len(kept_sets), _MASKED_IMAGES_AT_ONCE): + chunk = kept_sets[start:start + _MASKED_IMAGES_AT_ONCE] + rows = model.logprobs_batch([masked(kept) for kept in chunk]) + values.update((kept, sum(t.logprob for t in lps) / len(lps) if lps else 0.0) + for kept, lps in zip(chunk, rows)) + return lambda kept: values[frozenset(kept)] def _run(self, model: "Model", cases: "CaseBatch") -> Result: case = cases[0] diff --git a/evalrx/analyzers/reasoning/answer_extraction_audit.py b/evalrx/analyzers/reasoning/answer_extraction_audit.py index 5a8a768b..55b951c6 100644 --- a/evalrx/analyzers/reasoning/answer_extraction_audit.py +++ b/evalrx/analyzers/reasoning/answer_extraction_audit.py @@ -185,14 +185,18 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: raise CapabilityError( analyzer=self.name, model=repr(model), missing={Capability.GENERATE} ) - per_case: list[dict[str, Any]] = [] - n_reasked = 0 - for case in cases.stratified_head(self.max_cases): - entry = self._audit_case(case) - if self.reask and entry.get("extraction_suspect") == 1: - entry.update(self._reask(model, case)) - n_reasked += 1 - per_case.append(entry) + selected = list(cases.stratified_head(self.max_cases)) + per_case = [self._audit_case(case) for case in selected] + suspect = [(case, entry) for case, entry in zip(selected, per_case) + if self.reask and entry.get("extraction_suspect") == 1] + n_reasked = len(suspect) + # The audit itself needs no model; only a re-ask does. + answers = model.generate_batch([ + dataclasses.replace(case.inputs, prompt=f"{case.inputs.prompt or ''}\n\n{_REASK_SUFFIX}") + for case, _ in suspect]) if suspect else [] + for (case, entry), answer in zip(suspect, answers): + entry["reask_answer"] = str(answer)[:120] + entry["reask_correct"] = int(bool(self.match_fn(str(answer), case.expected))) gradable = [c for c in per_case if "extraction_suspect" in c] failing = [c for c in gradable if c["labelled_fail"] == 1] @@ -321,11 +325,3 @@ def _audit_case(self, case: "FailureCase") -> dict[str, Any]: if answer_dir is not None: entry["answered_yes"] = int(answer_dir == "yes") return entry - - def _reask(self, model: "Model", case: "FailureCase") -> dict[str, Any]: - prompt = f"{case.inputs.prompt or ''}\n\n{_REASK_SUFFIX}" - answer = str(model.generate(dataclasses.replace(case.inputs, prompt=prompt))) - return { - "reask_answer": answer[:120], - "reask_correct": int(bool(self.match_fn(answer, case.expected))), - } diff --git a/evalrx/analyzers/reasoning/arith_audit.py b/evalrx/analyzers/reasoning/arith_audit.py index 6cac0a6c..6966887d 100644 --- a/evalrx/analyzers/reasoning/arith_audit.py +++ b/evalrx/analyzers/reasoning/arith_audit.py @@ -103,13 +103,17 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: raise CapabilityError( analyzer=self.name, model=repr(model), missing={Capability.GENERATE} ) - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - text = case.observed - if not str(text or "").strip() and self.generate_missing: - prompt = f"{case.inputs.prompt or ''}\n\n{_COT_SUFFIX}" - text = str(model.generate(dataclasses.replace(case.inputs, prompt=prompt))) - per_case.append(self._audit(case, text)) + selected = list(cases.stratified_head(self.max_cases)) + texts: list[Any] = [case.observed for case in selected] + if self.generate_missing: + missing = [i for i, text in enumerate(texts) if not str(text or "").strip()] + fresh = model.generate_batch([ + dataclasses.replace( + selected[i].inputs, prompt=f"{selected[i].inputs.prompt or ''}\n\n{_COT_SUFFIX}") + for i in missing]) + for i, text in zip(missing, fresh): + texts[i] = str(text) + per_case = [self._audit(case, text) for case, text in zip(selected, texts)] classified = [c for c in per_case if c.get("error_class") not in (None, UNKNOWN)] wrong = [c for c in classified if c["answer_correct"] == 0] diff --git a/evalrx/analyzers/reasoning/contamination.py b/evalrx/analyzers/reasoning/contamination.py index a908151d..b2f5edff 100644 --- a/evalrx/analyzers/reasoning/contamination.py +++ b/evalrx/analyzers/reasoning/contamination.py @@ -31,7 +31,7 @@ from typing import TYPE_CHECKING, Any, Optional from evalrx.analyzers.reasoning._text import word_ngrams -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -122,9 +122,8 @@ def __init__( ) def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - per_case.append(self._probe_case(model, case)) + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) scored = [c for c in per_case if "guided_overlap" in c] flagged = [c for c in scored if c["verbatim_flag"] == 1] @@ -162,7 +161,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: return Result(analyzer=self.name, model=repr(model), cases=cases, findings=findings) # ------------------------------------------------------------------ - def _probe_case(self, model: "Model", case: "FailureCase") -> dict[str, Any]: + def _probe_case(self, case: "FailureCase") -> Probe[dict[str, Any]]: from evalrx.core.case import Label text = str(case.inputs.prompt or "") @@ -175,19 +174,12 @@ def _probe_case(self, model: "Model", case: "FailureCase") -> dict[str, Any]: cut = max(1, int(len(words) * self.split_frac)) first_half, second_half = " ".join(words[:cut]), " ".join(words[cut:]) - general = str(model.generate(_bare(case, _GENERAL.format(first_half=first_half)))) - guided = str( - model.generate( - _bare( - case, - _GUIDED.format( - first_half=first_half, - dataset=self.dataset_name, - split=self.split, - ), - ) - ) - ) + general, guided, *named_out = map(str, (yield Ask([ + _bare(case, _GENERAL.format(first_half=first_half)), + _bare(case, _GUIDED.format( + first_half=first_half, dataset=self.dataset_name, split=self.split)), + *([_bare(case, _PROVENANCE.format(text=text[:1500]))] if self.ask_provenance else []), + ]))) general_overlap = overlap_score(general, second_half, self.ngram) guided_overlap = overlap_score(guided, second_half, self.ngram) entry.update( @@ -203,8 +195,8 @@ def _probe_case(self, model: "Model", case: "FailureCase") -> dict[str, Any]: ), } ) - if self.ask_provenance: - named = str(model.generate(_bare(case, _PROVENANCE.format(text=text[:1500])))) + if named_out: + named = named_out[0] entry["named_dataset"] = named.strip()[:80] entry["named_correct"] = int( self.dataset_name.lower().split()[0] in named.lower() diff --git a/evalrx/analyzers/reasoning/knowledge_split.py b/evalrx/analyzers/reasoning/knowledge_split.py index 7e5bef2c..af74c9cc 100644 --- a/evalrx/analyzers/reasoning/knowledge_split.py +++ b/evalrx/analyzers/reasoning/knowledge_split.py @@ -30,7 +30,7 @@ from typing import TYPE_CHECKING, Any, Callable, Optional from evalrx.analyzers.reasoning._text import answer_equal, extract_answer -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -99,12 +99,8 @@ def __init__( self.grader = grader or _default_grader def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - if case.expected is None: - per_case.append({"sample_id": case.id, "skipped": "no gold answer"}) - continue - per_case.append(self._probe_case(model, case)) + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) scored = [c for c in per_case if "deficit_class" in c] failed = [c for c in scored if c["baseline_correct"] == 0] @@ -165,30 +161,26 @@ def _share(cls: str) -> Optional[float]: return Result(analyzer=self.name, model=repr(model), cases=cases, findings=findings) # ------------------------------------------------------------------ - def _probe_case(self, model: "Model", case: "FailureCase") -> dict[str, Any]: + def _probe_case(self, case: "FailureCase") -> Probe[dict[str, Any]]: + if case.expected is None: + return {"sample_id": case.id, "skipped": "no gold answer"} entry: dict[str, Any] = {"sample_id": case.id} - baseline = self.grader(model.generate(self._ask(case, _BASELINE)), case) - decomposed = self.grader(model.generate(self._ask(case, _DECOMPOSE)), case) + baseline_out, decomposed_out, facts = yield Ask([ + self._ask(case, _BASELINE), self._ask(case, _DECOMPOSE), self._ask(case, _RECALL)]) + baseline = self.grader(baseline_out, case) + decomposed = self.grader(decomposed_out, case) - facts = str(model.generate(self._ask(case, _RECALL))) - fact_lines = [ln.strip() for ln in facts.splitlines() if ln.strip()] + fact_lines = [ln.strip() for ln in str(facts).splitlines() if ln.strip()] entry["n_listed_facts"] = len(fact_lines) entry["own_facts_parsed"] = int(bool(fact_lines)) - own_facts = None - if fact_lines: - own_facts = self.grader( - model.generate( - self._ask(case, _FROM_FACTS.format(facts="\n".join(fact_lines))) - ), - case, - ) - context = self._context_for(case) - open_book = None - if context: - open_book = self.grader( - model.generate(self._ask(case, _OPEN_BOOK.format(context=context))), case - ) + # Answering from its own facts needs the facts; the open-book question rides along. + second = iter((yield Ask([ + *([self._ask(case, _FROM_FACTS.format(facts="\n".join(fact_lines)))] if fact_lines else []), + *([self._ask(case, _OPEN_BOOK.format(context=context))] if context else []), + ]))) + own_facts = self.grader(next(second), case) if fact_lines else None + open_book = self.grader(next(second), case) if context else None if baseline is None: entry["skipped"] = "ungradable baseline" diff --git a/evalrx/analyzers/reasoning/self_repair.py b/evalrx/analyzers/reasoning/self_repair.py index bc0e5b0d..b94803ac 100644 --- a/evalrx/analyzers/reasoning/self_repair.py +++ b/evalrx/analyzers/reasoning/self_repair.py @@ -34,7 +34,7 @@ extract_answer, normalize_answer, ) -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -101,18 +101,8 @@ def __init__( self.answer_fn = answer_fn or extract_answer def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - baseline = case.observed - if not str(baseline or "").strip(): - if not self.generate_missing: - per_case.append( - {"sample_id": case.id, "skipped": "no stored answer to revise"} - ) - continue - baseline = str(model.generate(case.inputs)) - entry = self._probe_case(model, case, str(baseline)) - per_case.append(entry) + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) graded = [c for c in per_case if "baseline_correct" in c] failed = [c for c in graded if c["baseline_correct"] == 0] @@ -175,13 +165,20 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: return Result(analyzer=self.name, model=repr(model), cases=cases, findings=findings) # ------------------------------------------------------------------ - def _probe_case(self, model: "Model", case: "FailureCase", baseline: str) -> dict[str, Any]: + def _probe_case(self, case: "FailureCase") -> Probe[dict[str, Any]]: + baseline = str(case.observed or "") + if not baseline.strip(): + if not self.generate_missing: + return {"sample_id": case.id, "skipped": "no stored answer to revise"} + baseline = str((yield Ask([case.inputs]))[0]) entry: dict[str, Any] = {"sample_id": case.id} base_grade = self.grader(baseline, case) - critique = str(model.generate(self._ask(case, _CRITIQUE, baseline))) + critique, revised, *told_out = map(str, (yield Ask([ + self._ask(case, _CRITIQUE, baseline), self._ask(case, _REVISE_BLIND, baseline), + *([self._ask(case, _REVISE_TOLD, baseline)] if self.revise_with_critique else []), + ]))) says_incorrect = _parse_verdict(critique) - revised = str(model.generate(self._ask(case, _REVISE_BLIND, baseline))) revised_grade = self.grader(revised, case) entry["self_says_incorrect"] = ( @@ -207,9 +204,8 @@ def _probe_case(self, model: "Model", case: "FailureCase", baseline: str) -> dic if says_incorrect is not None: entry["detection_correct"] = int(says_incorrect == (not base_grade)) - if self.revise_with_critique: - told = str(model.generate(self._ask(case, _REVISE_TOLD, baseline))) - told_grade = self.grader(told, case) + if told_out: + told_grade = self.grader(told_out[0], case) if told_grade is not None: entry["told_correct"] = int(told_grade) entry["told_repaired"] = int(not base_grade and told_grade) diff --git a/evalrx/analyzers/reasoning/step_rollout_value.py b/evalrx/analyzers/reasoning/step_rollout_value.py index bd870ec3..9c5ef465 100644 --- a/evalrx/analyzers/reasoning/step_rollout_value.py +++ b/evalrx/analyzers/reasoning/step_rollout_value.py @@ -28,7 +28,7 @@ from typing import TYPE_CHECKING, Any, Callable, Optional from evalrx.analyzers.reasoning._text import answer_equal, extract_answer -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -109,22 +109,10 @@ def __init__( self.answer_fn = answer_fn or extract_answer def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) step_values_by_case: dict[str, list[float]] = {} - for case in cases.stratified_head(self.max_cases): - if case.expected is None: - per_case.append({"sample_id": case.id, "skipped": "no gold answer"}) - continue - chain = case.observed - if not str(chain or "").strip(): - chain = str( - model.generate( - dataclasses.replace( - case.inputs, prompt=f"{case.inputs.prompt or ''}\n\n{_COT_SUFFIX}" - ) - ) - ) - entry = self._probe_case(model, case, str(chain)) + for entry in per_case: # Contract: a per-case row carries one level of scalars — a numeric # vector there looks like a signal and reaches no statistic. The # trajectory moves to findings["step_values_by_case"]; every scalar @@ -133,7 +121,6 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: values = entry.pop("step_values", None) if values is not None: step_values_by_case[entry["sample_id"]] = values - per_case.append(entry) scored = [c for c in per_case if "break_step_idx" in c] breaks = [c["break_step_idx"] for c in scored if c["break_step_idx"] is not None] @@ -166,29 +153,31 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: return Result(analyzer=self.name, model=repr(model), cases=cases, findings=findings) # ------------------------------------------------------------------ - def _probe_case(self, model: "Model", case: "FailureCase", chain: str) -> dict[str, Any]: + def _probe_case(self, case: "FailureCase") -> Probe[dict[str, Any]]: + if case.expected is None: + return {"sample_id": case.id, "skipped": "no gold answer"} + chain = str(case.observed or "") + if not chain.strip(): + chain = str((yield Ask([dataclasses.replace( + case.inputs, prompt=f"{case.inputs.prompt or ''}\n\n{_COT_SUFFIX}")]))[0]) steps = split_steps(chain, self.max_steps) entry: dict[str, Any] = {"sample_id": case.id, "n_steps": len(steps)} if not steps: entry["skipped"] = "no reasoning steps to roll out from" return entry + # Every step's rollouts are independent of each other: one Ask. + prefixes = [dataclasses.replace(case.inputs, prompt=( + f"{case.inputs.prompt or ''}\n\n" + + _CONTINUE.format(prefix=chr(10).join(steps[: i + 1])))) + for i in range(len(steps))] + rollouts = iter((yield Ask( + [prefix for prefix in prefixes for _ in range(self.n_rollouts)], self.gen_kwargs))) values: list[float] = [] - for i in range(len(steps)): - prefix = "\n".join(steps[: i + 1]) - prompt = f"{case.inputs.prompt or ''}\n\n{_CONTINUE.format(prefix=prefix)}" - hits = 0 - graded = 0 - for _ in range(self.n_rollouts): - out = model.generate( - dataclasses.replace(case.inputs, prompt=prompt), **self.gen_kwargs - ) - verdict = self.grader(out, case) - if verdict is None: - continue - graded += 1 - hits += int(verdict) - values.append(round(hits / graded, 4) if graded else 0.0) + for _ in prefixes: + verdicts = [self.grader(next(rollouts), case) for _ in range(self.n_rollouts)] + graded = [v for v in verdicts if v is not None] + values.append(round(sum(map(int, graded)) / len(graded), 4) if graded else 0.0) entry["step_values"] = values entry["initial_value"] = values[0] diff --git a/evalrx/analyzers/reasoning/termination_audit.py b/evalrx/analyzers/reasoning/termination_audit.py index f26215a7..9fc4e002 100644 --- a/evalrx/analyzers/reasoning/termination_audit.py +++ b/evalrx/analyzers/reasoning/termination_audit.py @@ -36,7 +36,7 @@ looks_truncated, repetition_score, ) -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -116,16 +116,8 @@ def __init__( self.match_fn = match_fn or answer_equal def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - text = case.observed - if not str(text or "").strip(): - # no stored output — generate one so the class is about THIS model - text = str(model.generate(case.inputs)) - entry = self._classify(case, text) - if self.continue_non_clean and entry["termination_class"] != CLEAN: - entry.update(self._continue(model, case, text)) - per_case.append(entry) + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) n = len(per_case) counts = { @@ -220,11 +212,21 @@ def _classify(self, case: "FailureCase", text: Any) -> dict[str, Any]: "output_words": len(raw.split()), } - def _continue(self, model: "Model", case: "FailureCase", text: Any) -> dict[str, Any]: - prompt = ( - f"{case.inputs.prompt or ''}\n\nPartial response:\n{text}\n\n{_CONTINUE_SUFFIX}" - ) - continuation = str(model.generate(dataclasses.replace(case.inputs, prompt=prompt))) + def _probe_case(self, case: "FailureCase") -> Probe[dict[str, Any]]: + text = case.observed + if not str(text or "").strip(): + # no stored output — generate one so the class is about THIS model + text = str((yield Ask([case.inputs]))[0]) + entry = self._classify(case, text) + if self.continue_non_clean and entry["termination_class"] != CLEAN: + prompt = ( + f"{case.inputs.prompt or ''}\n\nPartial response:\n{text}\n\n{_CONTINUE_SUFFIX}" + ) + (continuation,) = yield Ask([dataclasses.replace(case.inputs, prompt=prompt)]) + entry.update(self._continued(case, str(continuation))) + return entry + + def _continued(self, case: "FailureCase", continuation: str) -> dict[str, Any]: out: dict[str, Any] = { "continuation_has_answer": int(has_answer_tag(continuation)), "continuation_chars": len(continuation), diff --git a/evalrx/analyzers/uncertainty/calibration.py b/evalrx/analyzers/uncertainty/calibration.py index 40331805..6b92e78f 100644 --- a/evalrx/analyzers/uncertainty/calibration.py +++ b/evalrx/analyzers/uncertainty/calibration.py @@ -37,6 +37,7 @@ from evalrx.core.result import Result if TYPE_CHECKING: + from evalrx.core.case import FailureCase from evalrx.core.model import Model _ELICIT = ( @@ -99,6 +100,27 @@ class CalibrationAnalyzer(Analyzer): def __init__(self, n_bins: int = 10, max_cases: int = 0, elicit: str = _ELICIT) -> None: super().__init__(n_bins=max(2, int(n_bins)), max_cases=max_cases, elicit=elicit) + @staticmethod + def _logprob_rows(model: "Model", cases: "list[FailureCase]") -> "list[Any]": + """Each case's answer logprobs, or the error that case raised. + + An API timeout is evidence missing for one case, not a reason to + discard an otherwise useful calibration run (Gemini's transport can + time out one multimodal request while the next clip succeeds). When + the batch fails, each case is asked on its own so the failed one stays + visible and the summary denominators count only what was measured. + """ + try: + return list(model.logprobs_batch([case.inputs for case in cases])) + except Exception: # noqa: BLE001 - find which case it was + rows: list[Any] = [] + for case in cases: + try: + rows.append(model.logprobs(case.inputs)) + except Exception as exc: # noqa: BLE001 - recorded on the case's row + rows.append(exc) + return rows + def _run(self, model: "Model", cases: "CaseBatch") -> Result: per_case: list[dict[str, Any]] = [] lp_pairs: list[tuple[float, bool]] = [] @@ -106,21 +128,20 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: labelled = CaseBatch([c for c in cases if c.label in (Label.PASS, Label.FAIL)]) n_unlabelled = len(list(cases)) - len(list(labelled)) has_logprobs = Capability.LOGPROBS in getattr(model, "capabilities", frozenset()) - for case in labelled.stratified_head(self.max_cases): + selected = list(labelled.stratified_head(self.max_cases)) + # A failed request is evidence missing for one case, so the batch is + # asked for errors in place rather than raising on the first. + verbalized = model.try_generate_batch([ + dataclasses.replace(case.inputs, prompt=(case.inputs.prompt or "") + self.elicit) + for case in selected]) + scored = self._logprob_rows(model, selected) if has_logprobs else [[] for _ in selected] + for case, raw, toks in zip(selected, verbalized, scored): correct = case.label == Label.PASS entry: dict[str, Any] = {"sample_id": case.id, "correct": int(correct)} - # An API timeout is evidence missing for one case, not a reason to - # discard an otherwise useful calibration run. In particular, - # Gemini's transport can time out a single multimodal request while - # the next clip succeeds. Keep the failed case visible and carry - # on; summary denominators below then honestly reflect only the - # successful confidence measurements. - try: - toks = model.logprobs(case.inputs) if has_logprobs else [] - except Exception as exc: + if isinstance(toks, Exception): + entry["logprob_error"] = f"{type(toks).__name__}: {str(toks)[:160]}" toks = [] - entry["logprob_error"] = f"{type(exc).__name__}: {str(exc)[:160]}" lps = [t.logprob for t in toks] conf_lp = math.exp(sum(lps) / len(lps)) if lps else None if conf_lp is not None: @@ -128,16 +149,11 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: entry["conf_logprob"] = round(conf_lp, 4) lp_pairs.append((conf_lp, correct)) - elicited = dataclasses.replace( - case.inputs, prompt=(case.inputs.prompt or "") + self.elicit - ) - try: - raw = str(model.generate(elicited)) - except Exception as exc: - entry["verbalized_error"] = f"{type(exc).__name__}: {str(exc)[:160]}" + if isinstance(raw, Exception): + entry["verbalized_error"] = f"{type(raw).__name__}: {str(raw)[:160]}" per_case.append(entry) continue - conf_vb = _parse_conf(raw) + conf_vb = _parse_conf(str(raw)) if conf_vb is not None: entry["conf_verbal"] = round(conf_vb, 4) vb_pairs.append((conf_vb, correct)) diff --git a/evalrx/analyzers/uncertainty/coverage_gap.py b/evalrx/analyzers/uncertainty/coverage_gap.py index 3805efab..53d62669 100644 --- a/evalrx/analyzers/uncertainty/coverage_gap.py +++ b/evalrx/analyzers/uncertainty/coverage_gap.py @@ -36,7 +36,7 @@ extract_answer, normalize_answer, ) -from evalrx.core.analyzer import Analyzer +from evalrx.core.analyzer import Analyzer, Ask, Probe, run_probes from evalrx.core.capability import Capability from evalrx.core.registry import register_analyzer from evalrx.core.result import Result @@ -104,12 +104,8 @@ def __init__( self.answer_fn = answer_fn or extract_answer def _run(self, model: "Model", cases: "CaseBatch") -> Result: - per_case: list[dict[str, Any]] = [] - for case in cases.stratified_head(self.max_cases): - if case.expected is None: - per_case.append({"sample_id": case.id, "skipped": "no gold answer"}) - continue - per_case.append(self._probe_case(model, case)) + per_case = run_probes( + model, [self._probe_case(case) for case in cases.stratified_head(self.max_cases)]) scored = [c for c in per_case if "coverage_gap" in c] degenerate = bool(scored) and all(c["n_unique"] == 1 for c in scored) @@ -144,10 +140,10 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: return Result(analyzer=self.name, model=repr(model), cases=cases, findings=findings) # ------------------------------------------------------------------ - def _probe_case(self, model: "Model", case: "FailureCase") -> dict[str, Any]: - samples = [ - str(model.generate(case.inputs, **self.gen_kwargs)) for _ in range(self.k) - ] + def _probe_case(self, case: "FailureCase") -> Probe[dict[str, Any]]: + if case.expected is None: + return {"sample_id": case.id, "skipped": "no gold answer"} + samples = [str(s) for s in (yield Ask([case.inputs] * self.k, self.gen_kwargs))] answers = [self.answer_fn(s) for s in samples] grades = [self.grader(s, case) for s in samples] graded = [g for g in grades if g is not None] @@ -179,12 +175,10 @@ def _probe_case(self, model: "Model", case: "FailureCase") -> dict[str, Any]: listing = "\n".join( f"{i + 1}. {a}" for i, a in enumerate(dict.fromkeys(answers)) ) - chosen = model.generate( - dataclasses.replace( - case.inputs, - prompt=f"{case.inputs.prompt or ''}\n\n{_VERIFY.format(candidates=listing)}", - ) - ) + (chosen,) = yield Ask([dataclasses.replace( + case.inputs, + prompt=f"{case.inputs.prompt or ''}\n\n{_VERIFY.format(candidates=listing)}", + )]) verdict = self.grader(chosen, case) if verdict is not None: entry["verify_correct"] = int(verdict) diff --git a/evalrx/analyzers/uncertainty/entropy.py b/evalrx/analyzers/uncertainty/entropy.py index bdd70013..891d5ade 100755 --- a/evalrx/analyzers/uncertainty/entropy.py +++ b/evalrx/analyzers/uncertainty/entropy.py @@ -50,6 +50,7 @@ class TokenEntropyAnalyzer(Analyzer): name = "token_entropy" requires = frozenset({Capability.LOGITS}) + single_case = True top_k: int diff --git a/evalrx/analyzers/uncertainty/logprob_entropy.py b/evalrx/analyzers/uncertainty/logprob_entropy.py index 91dba53b..8bf67359 100755 --- a/evalrx/analyzers/uncertainty/logprob_entropy.py +++ b/evalrx/analyzers/uncertainty/logprob_entropy.py @@ -38,9 +38,12 @@ class LogprobEntropyAnalyzer(Analyzer): name = "logprob_entropy" requires = frozenset({Capability.LOGPROBS}) + single_case = True applies_to_modalities = frozenset({"text", "image"}) def _run(self, model: "Model", cases: "CaseBatch") -> Result: + # One case, one call: nothing to batch. `calibration` scores a whole + # batch's logprobs in one `logprobs_batch`. case = cases[0] toks = model.logprobs(case.inputs) # list[TokenLogprob] lps = [t.logprob for t in toks] diff --git a/evalrx/analyzers/uncertainty/self_consistency.py b/evalrx/analyzers/uncertainty/self_consistency.py index 41fd7db5..78cf9b99 100755 --- a/evalrx/analyzers/uncertainty/self_consistency.py +++ b/evalrx/analyzers/uncertainty/self_consistency.py @@ -105,6 +105,7 @@ class SelfConsistencyAnalyzer(Analyzer): name = "self_consistency" requires = frozenset({Capability.GENERATE}) + single_case = True applies_to_modalities = frozenset({"text", "image"}) signal_docs = { 'consistency': ('Answer stability', 'How often the model gave the same answer when asked the same question repeatedly. Low means unstable reasoning.'), @@ -134,7 +135,7 @@ def __init__( def _run(self, model: "Model", cases: "CaseBatch") -> Result: case = cases[0] - samples = [model.generate(case.inputs, **self.gen_kwargs) for _ in range(self.n)] + samples = model.generate_batch([case.inputs] * self.n, **self.gen_kwargs) 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/analyzers/uncertainty/verbalized_conf.py b/evalrx/analyzers/uncertainty/verbalized_conf.py index 4a255f0a..cc393f69 100755 --- a/evalrx/analyzers/uncertainty/verbalized_conf.py +++ b/evalrx/analyzers/uncertainty/verbalized_conf.py @@ -12,6 +12,7 @@ from __future__ import annotations +import dataclasses import re from typing import TYPE_CHECKING, Optional @@ -38,6 +39,7 @@ class VerbalizedConfidenceAnalyzer(Analyzer): name = "verbalized_confidence" requires = frozenset({Capability.GENERATE}) + single_case = True applies_to_modalities = frozenset({"text", "image"}) elicit: str @@ -54,8 +56,13 @@ def _parse(text: str) -> Optional[float]: return max(0.0, min(1.0, val / 100.0 if val > 1.0 else val)) def _run(self, model: "Model", cases: "CaseBatch") -> Result: + # One case, one call: nothing to batch. `calibration` is the analyzer + # that asks this of a whole batch (and scores it against the labels). case = cases[0] - raw = model.generate(str(case.inputs) + self.elicit) + # dataclasses.replace keeps the image: str(inputs) + elicit asked a + # VLM the question without its picture. + raw = model.generate(dataclasses.replace( + case.inputs, prompt=(case.inputs.prompt or "") + self.elicit)) conf = self._parse(raw) return Result( analyzer=self.name, diff --git a/evalrx/benchmark/run.py b/evalrx/benchmark/run.py index 8051e0fc..41de6de2 100644 --- a/evalrx/benchmark/run.py +++ b/evalrx/benchmark/run.py @@ -29,10 +29,10 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "L3a/L3b); jax_local = in-process JAX through the gemma library (Gemma " "E2B/E4B, white-box reads, fix ladder clamped to L2 for now); gemini = " "Google Gen AI API through google-genai (forced for the gemini family)") - p.add_argument("--concurrency", type=int, default=1, - help="Cases generated at once during baseline discovery. Honoured only for " - "--backend endpoint (a local backend shares one GPU and is not " - "thread-safe); a served model can only batch requests it has in hand.") + p.add_argument("--concurrency", type=int, default=8, + help="Requests in flight at once against an API backend (endpoint, gemini), " + "in every stage. A local backend batches on the GPU instead " + "(RuntimeConfig.batch_size).") p.add_argument("--base-url", default="http://host.docker.internal:8020/v1") p.add_argument("--api-key", default=None, help="endpoint: bearer token (default EMPTY, what vllm serve expects); " @@ -68,6 +68,9 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "tasks — greedy Qwen3.5 loops to the cap on reasoning prompts — else 0 = greedy)") p.add_argument("--top-p", type=float, default=0.95) p.add_argument("--top-k", type=int, default=20) + p.add_argument("--label-samples", type=int, default=None, + help="answers Stage 0 samples per case; the label is their majority " + "(default: 5 when sampling, 1 greedy; use an odd number)") p.add_argument("--fix-baseline-repeats", type=int, default=None, help="baseline samples per case in the fix stage (default: 5 when sampling, 1 greedy)") p.add_argument("--enable-thinking", action="store_true", @@ -75,8 +78,8 @@ def build_parser(p: argparse.ArgumentParser | None = None) -> argparse.ArgumentP "gemini: leave the API's default level instead of sending the floor)") p.add_argument("--judge-provider", choices=["agy", "claude", "codex", "gemini"], default="claude") p.add_argument("--judge-model", default=None, - help="default per provider: claude -> claude-opus-5, codex -> gpt-5.6-terra") - p.add_argument("--judge-effort", default="high") + help="default per provider: claude -> sonnet, codex -> gpt-5.6-terra") + p.add_argument("--judge-effort", default="medium") p.add_argument("--coder-provider", choices=["gemini_cli"], default=None, help="Override the coding agent independently of the judge (requires an installed, authenticated CLI)") p.add_argument("--coder-model", default=None, help="Model for the coding-agent override") diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 596d045f..21a4d1e6 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -38,7 +38,7 @@ def _print_fix_progress(event): def _benchmark_agentic_registry(loop, state): """Keep repair/CONFIRM access outside the adaptive controller.""" - from evalrx.eval_agent.agentic.tools import ToolRegistry, build_default_registry + from evalrx.eval_agent.loop.judge.tools import ToolRegistry, build_default_registry full = build_default_registry(loop, state) registry = ToolRegistry() @@ -99,6 +99,7 @@ def load_model(resolved: Resolved, args, task: T.Task): extra_body["top_k"] = gen["top_k"] runtime = openai_runtime(base_url=args.base_url, api_key=args.api_key, extra_body=extra_body, **sampling) + runtime.concurrency = max(1, int(args.concurrency)) # the endpoint's generate_fn carries the sampling itself; per-call kwargs are not forwarded return compose(spec, "api", runtime, set()), {}, spec if resolved.backend == "gemini": @@ -120,9 +121,13 @@ def load_model(resolved: Resolved, args, task: T.Task): with_logprobs="auto", logprobs_model=spec.hf_repo or spec.key, top_logprobs=5, **sampling) + runtime.concurrency = max(1, int(args.concurrency)) return compose(spec, "api", runtime, set()), {}, spec from evalrx.models.backends.base import RuntimeConfig + # The decoding Stage 0 labels with is the model's own: a probe that calls + # generate() with no arguments then answers under the same settings. + sampling = {name: value for name, value in gen.items() if name != "max_new_tokens"} if resolved.backend == "jax_local": # The JAX twin: same spec (template kwargs, modalities, caveats), the # gemma library underneath; text, image and audio inputs. apply_chat_template @@ -134,7 +139,7 @@ def load_model(resolved: Resolved, args, task: T.Task): # modalities it can serve accordingly engine_kwargs["text_only"] = task.modality == "llm" runtime = RuntimeConfig(device=args.device or "auto", dtype=args.dtype, max_new_tokens=max_new, - apply_chat_template=True, engine_kwargs=engine_kwargs) + apply_chat_template=True, engine_kwargs=engine_kwargs, sampling=sampling) return compose(spec, "jax_local", runtime, set()), gen, spec device = args.device or (resolved.size.default_device if resolved.size is not None else "cuda") @@ -145,7 +150,7 @@ def load_model(resolved: Resolved, args, task: T.Task): # tokenises the raw prompt — completion mode — and Qwen3.5 opens its own # block and runs to the cap (the llm smokes of 2026-08-21). runtime = RuntimeConfig(device=device, dtype=args.dtype, attn_impl=attn, max_new_tokens=max_new, - apply_chat_template=True) + apply_chat_template=True, sampling=sampling) want = {Capability.ATTENTION} if attn == "eager" else set() model = compose(spec, "hf_local", runtime, want) return model, gen, spec @@ -197,7 +202,7 @@ def load_weights(model, resolved: Resolved, args, task: T.Task): def build_judge(args): """``(judge, coder_provider, coder_model, coder_extra_args)`` — the same three providers as the m1_m5 examples; the benchmark CLI defaults to - Claude / claude-opus-5 / high.""" + Claude / sonnet / medium.""" if args.judge_provider == "gemini": adaptive = getattr(args, "diagnosis_mode", "agentic") == "agentic" probe_codegen = adaptive and args.allow_codegen @@ -219,9 +224,10 @@ def build_judge(args): coder = ("antigravity", args.judge_model, (("--effort", args.judge_effort) if args.judge_effort else ())) elif args.judge_provider == "claude": - name = args.judge_model or "claude-opus-5" from evalrx.eval_agent import ClaudeModel + name = args.judge_model or ClaudeModel.DEFAULT_MODEL + judge = ClaudeModel(model=name, effort=args.judge_effort, timeout_sec=300) coder = ("claude_code", name, (("--effort", args.judge_effort) if args.judge_effort else ())) else: @@ -417,22 +423,42 @@ def _run_config(args, task: T.Task, resolved: Resolved, spec, gen_kwargs: dict, } -def _discover(model, candidates, protocol, gen_kwargs: dict, args): - """Stage 0: generate an answer per candidate and label it. ``(discovery, seconds)``.""" +def label_samples(task: T.Task, args) -> int: + """Answers Stage 0 draws per case. A sampling model can answer one case + both ways, so a single answer labels it by chance; the majority of five + is the default there, and one answer when decoding is greedy.""" + if args.label_samples is not None: + return max(1, int(args.label_samples)) + return 5 if generation_settings(task, args)["do_sample"] else 1 + + +def _discover(model, candidates, protocol, gen_kwargs: dict, args, task: T.Task): + """Stage 0: sample each candidate's answers and label it. ``(discovery, seconds)``.""" from evalrx.eval_agent import CaseDiscoveryAgent started = time.monotonic() discovery = CaseDiscoveryAgent( scorer=T.label_case, generation_kwargs=gen_kwargs, include_unknown=False, - concurrency=getattr(args, "concurrency", 1), + n_samples=label_samples(task, args), ).discover(model, candidates, protocol=protocol) return discovery, time.monotonic() - started def _case_labels(cases) -> list[dict[str, Any]]: - return [{ - "id": c.id, "expected": c.expected, "observed": str(c.observed), "label": c.label.value, - } for c in cases] + """One row per case; ``votes`` when the label is a majority of several answers.""" + rows = [] + for c in cases: + row = {"id": c.id, "expected": c.expected, "observed": str(c.observed), "label": c.label.value} + if "discovery_votes" in c.metadata: + row["votes"] = c.metadata["discovery_votes"] + rows.append(row) + return rows + + +def _split_votes(cases) -> int: + """Cases whose sampled answers did not all score the same.""" + votes = [c.metadata.get("discovery_votes", {}) for c in cases] + return sum(1 for v in votes if v.get("pass") and v.get("fail")) def _mark_short_answers_stopped(task: T.Task, cases) -> None: @@ -452,7 +478,7 @@ def _label_validation_set(model, val_manifest: Path, protocol, gen_kwargs: dict, single frozen-winner gate. """ val_candidates, _ = T.build_cases(task, val_manifest, int(getattr(args, "val_limit", 0) or 0)) - val_discovery, val_elapsed = _discover(model, val_candidates, protocol, gen_kwargs, args) + val_discovery, val_elapsed = _discover(model, val_candidates, protocol, gen_kwargs, args, task) val_cases = val_discovery.cases val_accuracy = val_discovery.n_pass / max(1, len(val_cases)) (run_dir / "baseline_val.json").write_text(json.dumps({ @@ -460,6 +486,7 @@ def _label_validation_set(model, val_manifest: Path, protocol, gen_kwargs: dict, "n": len(val_cases), "n_pass": val_discovery.n_pass, "n_fail": val_discovery.n_fail, "n_unknown": val_discovery.n_unknown, "accuracy": round(val_accuracy, 4), "seconds": round(val_elapsed, 1), "manifest": str(val_manifest), + "label_samples": label_samples(task, args), "n_split": _split_votes(val_cases), "cases": _case_labels(val_cases), }, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(f"Validation baseline: PASS={val_discovery.n_pass}, FAIL={val_discovery.n_fail}, " @@ -486,12 +513,6 @@ def _probe_agent(args, task: T.Task, resolved: Resolved, model, judge, coder_cfg if Capability.LOGPROBS in model.capabilities and "logprob_entropy" not in pinned: pinned.append("logprob_entropy") overrides = _sampling_analyzer_overrides(resolved, args) - # In-process generation shares one accelerator model. Concurrent Python - # generation loops contend heavily on HF models; JAX already serializes - # model access. Keep native probes on the calling thread, while serving - # backends can continue issuing concurrent requests. - probe_workers = 1 if resolved.backend in {"hf_local", "jax_local"} else 8 - config["m1_workers"] = probe_workers agentic = _is_agentic(args) m1_codegen = agentic and args.allow_codegen config["m1_codegen"] = bool(m1_codegen) @@ -505,12 +526,11 @@ def _probe_agent(args, task: T.Task, resolved: Resolved, model, judge, coder_cfg judge=None, max_analyzers=len(pinned), max_cases_per_analyzer=args.analyzer_max_cases, analyzer_overrides=overrides, - max_workers=probe_workers, ) return ProbeAgent(judge=judge, allow_codegen=m1_codegen, codegen_config=coder_cfg, max_cases_per_analyzer=args.analyzer_max_cases, - analyzer_overrides=overrides, max_workers=probe_workers) + analyzer_overrides=overrides) def _stats_agent(args, task: T.Task, judge, coder_cfg, ctx): @@ -533,8 +553,8 @@ def _fix_agent(args, task: T.Task, judge, coder_cfg, gen_kwargs: dict, ctx, raw_ fix_kwargs: dict[str, Any] = {} sampled = bool(gen_kwargs.get("do_sample")) - # Noise model for a sampled baseline: per-case PASS RATE over k samples (the - # frozen Stage 0 output + k-1 fresh), as llm_benchmark does; greedy = 1. + # Noise model for a sampled baseline: per-case PASS RATE over k fresh + # samples; greedy = 1, the Stage 0 answer itself. fix_kwargs["baseline_repeats"] = (args.fix_baseline_repeats if args.fix_baseline_repeats is not None else (5 if sampled else 1)) if task.modality == "llm": @@ -564,7 +584,6 @@ def _fix_agent(args, task: T.Task, judge, coder_cfg, gen_kwargs: dict, ctx, raw_ max_repair_rounds=max(1, args.fix_repair_rounds), exec_timeout_sec=args.fix_exec_timeout, prewritten_code=prewritten_code, - concurrency=getattr(args, "concurrency", 1), floor_candidates=() if _is_agentic(args) else ("self_consistency_5",), progress_callback=_print_fix_progress, **fix_kwargs, @@ -662,7 +681,7 @@ def run(args, task: T.Task, resolved: Resolved) -> int: discovery_model = model if not args.baseline_only: from evalrx.eval_agent import RunContext - from evalrx.eval_agent.model_instrumentation import InstrumentedModel + from evalrx.eval_agent.runlog.instrumentation import InstrumentedModel # Create the run log before Stage-0 so each discovery request is durable # as it happens, including its real latency and any transport error. @@ -680,7 +699,7 @@ def run(args, task: T.Task, resolved: Resolved) -> int: batch_case_ids=[c.id for c in candidates], ) - discovery, elapsed = _discover(discovery_model, candidates, protocol, gen_kwargs, args) + discovery, elapsed = _discover(discovery_model, candidates, protocol, gen_kwargs, args, task) cases = discovery.cases if ctx is not None: ctx.config["n_cases"] = len(cases) @@ -692,6 +711,7 @@ def run(args, task: T.Task, resolved: Resolved) -> int: "accuracy": round(accuracy, 4), "seconds": round(elapsed, 1), "generation_kwargs": gen_kwargs, "enable_thinking": bool(args.enable_thinking), "manifest": str(manifest), "limit": limit, + "label_samples": label_samples(task, args), "n_split": _split_votes(cases), "cases": _case_labels(cases), } version = _api_model_version(model) @@ -702,6 +722,9 @@ def run(args, task: T.Task, resolved: Resolved) -> int: encoding="utf-8") print(f"Baseline: PASS={discovery.n_pass}, FAIL={discovery.n_fail}, UNKNOWN={discovery.n_unknown}, " f"accuracy={accuracy:.3f} ({elapsed:.0f}s, {elapsed / max(1, len(cases)):.1f}s/case)") + if baseline["label_samples"] > 1: + print(f" labels are the majority of {baseline['label_samples']} sampled answers; " + f"{baseline['n_split']} of {len(cases)} cases answered both ways") if task.modality == "llm" and not 0.15 <= accuracy <= 0.85: print(" NOTE accuracy is outside the usable band [0.15, 0.85]: M2 has little to contrast " "and the paired tests downstream are short of power (results valid, weak)") @@ -731,7 +754,7 @@ def run(args, task: T.Task, resolved: Resolved) -> int: extra_args=coder_extra) policy = None if _is_agentic(args): - from evalrx.eval_agent.agentic import JudgePolicy + from evalrx.eval_agent.loop.judge import JudgePolicy policy = JudgePolicy(judge, max_actions=args.max_actions, registry_factory=_benchmark_agentic_registry) diff --git a/evalrx/contract/export.py b/evalrx/contract/export.py index a246f043..7b18c39b 100644 --- a/evalrx/contract/export.py +++ b/evalrx/contract/export.py @@ -137,7 +137,7 @@ def _layout_doc() -> str: "```", "", "`run.json` + `M1/log.json`..`M5/log.json` are RunLogger's layout (see", - "`evalrx/eval_agent/RUN_LOGGER.md`): no flat event stream, no separate", + "`evalrx/eval_agent/runlog/README.md`): no flat event stream, no separate", "`report/`/`figures/` — generated text/code is inlined into the owning", "stage's JSON and media is copied into that stage's own `artifacts/`.", "`contract/` sits alongside it, independently typed and validated.", diff --git a/evalrx/core/analyzer.py b/evalrx/core/analyzer.py index 0fc907cf..f07efffe 100755 --- a/evalrx/core/analyzer.py +++ b/evalrx/core/analyzer.py @@ -16,16 +16,97 @@ import inspect from abc import ABC, abstractmethod -from typing import TYPE_CHECKING, Any +from collections.abc import Generator, Iterable, Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, TypeVar from evalrx.core.capability import Capability, CapabilityError -from evalrx.core.case import CaseBatch, as_casebatch +from evalrx.core.case import CaseBatch, FailureCase, as_casebatch if TYPE_CHECKING: from evalrx.core.model import Model from evalrx.core.result import Result +def labelled_answers(model: "Model", cases: Iterable[FailureCase], **kwargs: Any) -> list[str]: + """Each case's answer to its own prompt, as the case was labelled. + + A case from Stage 0 carries that answer in ``observed``; only the cases + that carry none are asked, in one batch. This *reads* the model's answer. + An analyzer that compares it against a re-ask under a changed prompt needs + a fresh control from ``model.generate_batch`` instead: the labelled answer + is the one the FAIL cases were selected on, so a fresh sample beats it by + regression to the mean alone. + """ + cases = list(cases) + answers = ["" if case.observed is None else str(case.observed) for case in cases] + missing = [i for i, answer in enumerate(answers) if not answer] + if missing: + fresh = model.generate_batch([cases[i].inputs for i in missing], **kwargs) + for i, text in zip(missing, fresh): + answers[i] = str(text) + return answers + + +@dataclass +class Ask: + """What one case's probe wants generated next: *inputs*, all with *kwargs*. + + Inputs in one ``Ask`` must not depend on each other's answers; a probe that + needs an answer before it can write the next prompt yields twice. + """ + + inputs: list[Any] + kwargs: dict[str, Any] = field(default_factory=dict) + + +_T = TypeVar("_T") +#: A per-case probe: yields each :class:`Ask`, is sent that Ask's answers (one +#: per input, in order), and returns the case's row. +Probe = Generator[Ask, list[Any], _T] + + +def run_probes(model: "Model", probes: Sequence[Probe[_T]], *, tolerant: bool = False) -> list[_T]: + """Run one probe per case, batching what they ask for across the cases. + + The probes advance together: every probe's current :class:`Ask` goes to the + model in one ``generate_batch`` (one per distinct ``kwargs``), each probe is + resumed with its own answers, and the next round collects what they ask + next. A probe is ordinary sequential code for one case; the batching is + here. Results come back in the order of *probes*. + + With ``tolerant`` a failed generation reaches its probe as the exception + instead of ending the run, for a probe that records it and carries on. + """ + results: dict[int, _T] = {} + waiting: dict[int, Ask] = {} + + def advance(index: int, answers: "list[Any] | None") -> None: + try: + waiting[index] = next(probes[index]) if answers is None else probes[index].send(answers) + except StopIteration as done: + waiting.pop(index, None) + results[index] = done.value + + for index in range(len(probes)): + advance(index, None) + generate = model.try_generate_batch if tolerant else model.generate_batch + while waiting: + answers: dict[int, list[Any]] = {index: [] for index in waiting} + groups: dict[str, list[tuple[int, Any]]] = {} + for index, ask in waiting.items(): + groups.setdefault(repr(sorted(ask.kwargs.items())), []).extend( + (index, item) for item in ask.inputs) + for members in groups.values(): + kwargs = waiting[members[0][0]].kwargs + outputs = generate([item for _, item in members], **kwargs) + for (index, _), output in zip(members, outputs): + answers[index].append(output) + for index in list(waiting): + advance(index, answers[index]) + return [results[index] for index in range(len(probes))] + + class Analyzer(ABC): """Abstract base for every analysis (sklearn-estimator style). @@ -55,6 +136,11 @@ class Analyzer(ABC): #: ran and reported ``n_trajectories: 0``. Selection gates on this against #: the batch actually in hand. requires_trajectories: bool = False + #: True when the analysis explains ONE input: given a batch it reads the + #: first case and ignores the rest. Fine for ``analyzer.run(model, prompt)``; + #: on a labelled batch it yields one row, which no PASS-versus-FAIL + #: statistic can use, so selection does not offer it there. + single_case: bool = False #: Modality slots that must actually be FILLED in the batch for this analysis #: to mean anything — the data-shape counterpart of ``applies_to_modalities``. #: diff --git a/evalrx/core/model.py b/evalrx/core/model.py index 3f732641..76992aed 100755 --- a/evalrx/core/model.py +++ b/evalrx/core/model.py @@ -16,8 +16,10 @@ from __future__ import annotations from abc import ABC, abstractmethod +from collections.abc import Sequence +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Callable, Protocol +from typing import TYPE_CHECKING, Any, Callable, Protocol, TypeVar from evalrx.core.capability import Capability @@ -27,6 +29,8 @@ from evalrx.core.tokentype import TokenTypeMap from evalrx.core.tool import ChatTurn +_R = TypeVar("_R") + @dataclass class CaptureSpec: @@ -124,6 +128,10 @@ class Model(ABC): #: Modalities this model handles (e.g. {"text"}, {"text","image"}). Analyzers #: declare ``applies_to_modalities`` and are matched against this. modalities: frozenset[str] = frozenset({"text"}) + #: How many :meth:`generate` calls :meth:`generate_batch` runs at once. 1 + #: for a model that computes in this process; a model whose ``generate`` is + #: a network request sets its number of requests in flight. + concurrency: int = 1 def unembed_weight(self): """Optional: the unembedding matrix ``(vocab, dim)`` for logit-lens analyzers. @@ -136,6 +144,43 @@ def unembed_weight(self): def generate(self, inputs: Any, **kwargs) -> str: """Produce a text response for *inputs* (a prompt or :class:`Inputs`).""" + def generate_batch(self, inputs: Sequence[Any], **kwargs: Any) -> list[str]: + """Text for each of *inputs*, in the same order. + + The call to use for several independent questions. A backend answers + it the fastest way it has — padded batches (``hf_local``), an engine's + own batching (``vllm_offline``). The default here calls + :meth:`generate` for each input, :attr:`concurrency` at a time. + """ + return self._each(lambda item: self.generate(item, **kwargs), inputs) + + def try_generate_batch(self, inputs: Sequence[Any], **kwargs: Any) -> "list[str | Exception]": + """:meth:`generate_batch` that returns an input's error in its place. + + For callers that must keep every other answer when one input fails. A + backend with a real batch call gets it tried first, and each input is + asked on its own only if that raises. + """ + if type(self).generate_batch is not Model.generate_batch: + try: + return list(self.generate_batch(inputs, **kwargs)) + except Exception: # noqa: BLE001 - find which input it was + pass + return self._each(lambda item: self._generate_or_error(item, kwargs), inputs) + + def _each(self, ask: "Callable[[Any], _R]", inputs: Sequence[Any]) -> "list[_R]": + workers = min(len(inputs), max(1, int(self.concurrency))) + if workers < 2: + return [ask(item) for item in inputs] + with ThreadPoolExecutor(max_workers=workers) as pool: + return list(pool.map(ask, inputs)) + + def _generate_or_error(self, item: Any, kwargs: dict[str, Any]) -> "str | Exception": + try: + return self.generate(item, **kwargs) + except Exception as exc: # noqa: BLE001 - the caller reads it + return exc + @abstractmethod def forward( self, @@ -172,6 +217,14 @@ def logprobs(self, inputs: Any, **kwargs) -> "list[TokenLogprob]": f"{type(self).__name__} does not implement logprobs(); it is not LOGPROBS-capable." ) + def logprobs_batch(self, inputs: Sequence[Any], **kwargs: Any) -> "list[list[TokenLogprob]]": + """:meth:`logprobs` for each of *inputs*, in the same order. + + The default calls :meth:`logprobs` for each input, :attr:`concurrency` + at a time; ``hf_local`` runs padded batches. + """ + return self._each(lambda item: self.logprobs(item, **kwargs), inputs) + # ------------------------------------------------------------------ # Capability checks diff --git a/evalrx/eval_agent/__init__.py b/evalrx/eval_agent/__init__.py index 67480214..a15cb73c 100755 --- a/evalrx/eval_agent/__init__.py +++ b/evalrx/eval_agent/__init__.py @@ -121,12 +121,6 @@ fdr_correct, run_stats_tool, ) -from evalrx.eval_agent.agentic import ( - JudgePolicy, - ToolOutcome, - ToolRegistry, - ToolSpec, -) from evalrx.eval_agent.hypothesis import ( Hypothesis, HypothesisGenerator, @@ -135,19 +129,25 @@ hypothesis_from_dict, hypothesis_to_dict, ) -from evalrx.eval_agent.log_schema import ( +from evalrx.eval_agent.loop.diagnose import VLDiagnoseLoop +from evalrx.eval_agent.loop.fixed import FixedOrderPolicy +from evalrx.eval_agent.loop.judge import ( + JudgePolicy, + ToolOutcome, + ToolRegistry, + ToolSpec, +) +from evalrx.eval_agent.loop.report import AutoDiagnoseReport +from evalrx.eval_agent.nl_runner import scaffold_from_description +from evalrx.eval_agent.runlog.context import RunContext +from evalrx.eval_agent.runlog.logger import RunLogger +from evalrx.eval_agent.runlog.schema import ( RUN_LOG_SCHEMA_VERSION, SCHEMA_PATH, build_schema, load_schema, validate_event, ) -from evalrx.eval_agent.loop import VLDiagnoseLoop -from evalrx.eval_agent.loop_reports import AutoDiagnoseReport -from evalrx.eval_agent.nl_runner import scaffold_from_description -from evalrx.eval_agent.policy import FixedOrderPolicy -from evalrx.eval_agent.run_context import RunContext -from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.case_discovery import ( CaseDiscoveryAgent, CaseDiscoveryReport, diff --git a/evalrx/eval_agent/loop/__init__.py b/evalrx/eval_agent/loop/__init__.py new file mode 100644 index 00000000..0bfca415 --- /dev/null +++ b/evalrx/eval_agent/loop/__init__.py @@ -0,0 +1,13 @@ +"""The diagnosis loop and who picks its next step. + + diagnose.py VLDiagnoseLoop — configuration and the run phases (run, run_analysis, + run_confirm, run_m5, run_fix) + stages.py Stages — runs and records M1 probe, explore, M2, M3, M4; StageMemory + partition.py split_cases — the EXPLORE / CONFIRM / TEST partition + state.py Policy (the next-step contract) and RunState (what a run carries) + fixed.py FixedOrderPolicy — M1→M4 cycles, the default + judge/ JudgePolicy — a judge picks each next stage + report.py AutoDiagnoseReport and its stopped_by values + fix.py the post-loop fix stage: targets, tier ladder, EXPLORE→CONFIRM + metadata.py run provenance and logger wiring shared by the loop and policies +""" diff --git a/evalrx/eval_agent/loop.py b/evalrx/eval_agent/loop/diagnose.py similarity index 58% rename from evalrx/eval_agent/loop.py rename to evalrx/eval_agent/loop/diagnose.py index 59a1eb45..93a8bbbd 100755 --- a/evalrx/eval_agent/loop.py +++ b/evalrx/eval_agent/loop/diagnose.py @@ -13,10 +13,10 @@ loop stops — propose a fix for the best verified hypothesis (Plan A), or propose + execute a fix (Plan B). -The order of the stages is a policy (:mod:`evalrx.eval_agent.policy`): the -default :class:`~evalrx.eval_agent.policy.FixedOrderPolicy` runs the cycle +The order of the stages is a policy (:mod:`evalrx.eval_agent.loop.fixed`, :mod:`evalrx.eval_agent.loop.judge`): the +default :class:`~evalrx.eval_agent.loop.fixed.FixedOrderPolicy` runs the cycle above; ``VLDiagnoseLoop(..., policy=JudgePolicy(judge))`` lets a judge pick -each next stage instead (:class:`~evalrx.eval_agent.agentic.JudgePolicy`). +each next stage instead (:class:`~evalrx.eval_agent.loop.judge.JudgePolicy`). Usage:: @@ -36,12 +36,10 @@ from __future__ import annotations import logging -import random -import time from pathlib import Path from typing import TYPE_CHECKING, Any -from evalrx.eval_agent.loop_fix import ( +from evalrx.eval_agent.loop.fix import ( _climb_ladder, _confirm_from_explore, _fix_context_from_report, @@ -50,7 +48,14 @@ _merge_rungs, _unverified_hypotheses, ) -from evalrx.eval_agent.loop_reports import ( +from evalrx.eval_agent.loop.fixed import FixedOrderPolicy +from evalrx.eval_agent.loop.metadata import ( + _attach_run_logger, + _coerce_explore_context, + _run_config, +) +from evalrx.eval_agent.loop.partition import split_cases +from evalrx.eval_agent.loop.report import ( STOPPED_BY_ANALYSIS, STOPPED_BY_CRITERIA, STOPPED_BY_DIAG_ERROR, @@ -59,18 +64,11 @@ STOPPED_BY_NO_PROBE, AutoDiagnoseReport, ) -from evalrx.eval_agent.policy import FixedOrderPolicy, Policy -from evalrx.eval_agent.run_metadata import ( - _attach_run_logger, - _coerce_explore_context, - _log_generated_tools, - _make_intervention_result_from_test, - _run_config, -) +from evalrx.eval_agent.loop.stages import StageMemory, Stages, finalize_confirmatory_stats +from evalrx.eval_agent.loop.state import Policy from evalrx.eval_agent.store import InMemoryStore, Store if TYPE_CHECKING: - from collections.abc import Mapping from evalrx.analysis.stats_agent import StatsAnalysisAgent from evalrx.core.case import CaseBatch @@ -80,47 +78,6 @@ logger = logging.getLogger(__name__) -def _exact_size(picked: "list", pool: "list", n: int, seed: int) -> "list": - """Top a stratified draw up to exactly *n* items, deterministically. - - :func:`~evalrx.stats.subset_sampling.stratified_subset` returns at most - *n* items but per-stratum rounding can under-allocate by one or two; the - train/val/test split promises exact 1:1:1 counts, so the shortfall is - filled from a seeded shuffle of the untaken remainder of *pool*. - """ - if len(picked) >= n: - return picked[:n] - picked_ids = {id(c) for c in picked} - leftover = [c for c in pool if id(c) not in picked_ids] - random.Random(seed + 7919).shuffle(leftover) - return picked + leftover[: n - len(picked)] - - -def _diagnose_with_optional_context( - diag_agent: "Any", stats_report: "Any", prior_cycles: "Any", explore_context: "Any | None", - failure_modes: "Any | None" = None, cases: "Any | None" = None, -) -> "Any": - """Call ``diag_agent.diagnose`` passing ``explore_context``/``failure_modes``/ - ``cases`` only when the agent accepts them, so custom/legacy diagnosis - agents keep working unchanged. ``cases`` (the explore-split batch M1/M2 - ran on) only feeds the critic's label summary -- never the proposer.""" - import inspect as _inspect - - kwargs: dict[str, Any] = {"prior_cycles": prior_cycles or None} - optional = {"explore_context": explore_context, "failure_modes": failure_modes, - "cases": cases} - if any(v is not None for v in optional.values()): - params: "Mapping[str, _inspect.Parameter]" - try: - params = _inspect.signature(diag_agent.diagnose).parameters - except (TypeError, ValueError): - params = {} - for name, value in optional.items(): - if value is not None and name in params: - kwargs[name] = value - return diag_agent.diagnose(stats_report, **kwargs) - - class VLDiagnoseLoop: """M1→M2→M3→M4 failure-analysis loop for VL tasks (Plan A architecture). @@ -201,9 +158,9 @@ class VLDiagnoseLoop: training cases. Mutually exclusive with ``test_split > 0``. policy: Who picks the next stage: - :class:`~evalrx.eval_agent.policy.FixedOrderPolicy` + :class:`~evalrx.eval_agent.loop.fixed.FixedOrderPolicy` (default) or - :class:`~evalrx.eval_agent.agentic.JudgePolicy`. + :class:`~evalrx.eval_agent.loop.judge.JudgePolicy`. max_cycles: Hard cap on M1→M4 iterations (default 1: one diagnosis pass, then the caller moves on to M5/fix — with fix-on-unverified enabled the @@ -211,7 +168,7 @@ class VLDiagnoseLoop: tripled the wall-clock; raise it to keep mining when a cycle's M4 designs feed the next cycle's M1). - run_logger: Optional :class:`~evalrx.eval_agent.run_logger.RunLogger`. + run_logger: Optional :class:`~evalrx.eval_agent.runlog.logger.RunLogger`. token_budget: Stop early when accumulated token usage reaches this limit (0 = unlimited). analysis_only: Run only M1→M2 and stop before hypothesis generation. @@ -344,18 +301,17 @@ def __init__( # UNCONFIRMED: passed to M3's hypothesis-proposal prompt ONLY — never to the # M2 confirmatory family, M4 testing, or the fix gate. Accepts an # ExploreContext, a report dict (fused_report.json), or None. - self._explore_context = _coerce_explore_context(explore_report) + self._memory = StageMemory(explore_context=_coerce_explore_context(explore_report)) # In-cycle explore step (off by default): a free-form EDA pass over the # M1 per-case table, run between M1 and M2. Same standing as a Step-1 # explore_report — descriptive notes for M3 + files for the report. # Under a JudgePolicy it is the judge-decided `explore_data` tool # instead of the fixed in-cycle call. self.explorer = explorer - # Who picks the next stage (see evalrx.eval_agent.policy). + # Who picks the next stage (see evalrx.eval_agent.loop.state.Policy). self.policy: Policy = policy if policy is not None else FixedOrderPolicy() self._explore_dir = Path(explore_dir) if explore_dir is not None else None self._explore_question = str(explore_question or "") - self._tokens_used: int = 0 self._run_id: str = "" self._emitter: "Any | None" = None @@ -417,65 +373,16 @@ def publish_report(self, *, model: "Any | None" = None) -> "Any": if self.run_logger is None: raise RuntimeError("publish_report needs a run_logger with a durable run directory") if model is None: - model = getattr(self.diagnosis_agent, "judge", None) + model = getattr(self.diagnosis_agent or self._memory.diagnosis_agent, "judge", None) from evalrx.reporting.dynamic import publish_report return publish_report(self.run_logger.run_dir, model=model, run_logger=self.run_logger) - @staticmethod - def _strat_key(case: "Any") -> "tuple": - """Stratify the explore/confirm split by label + probe_type when present - (keeps the no-free-lunch control mix, e.g. present-detections, in both - partitions). Falls back to label alone for generic batches.""" - label = getattr(getattr(case, "label", None), "value", "?") - probe = (getattr(case, "metadata", {}) or {}).get("probe_type") - return (label, probe) - def _split_partitions(self, data: "CaseBatch"): - """Deterministic, stratified (explore, confirm, test) partition. - - The single source of truth for how a batch is divided; every stage - re-derives the identical partition from the same input batch. When - ``confirm_split <= 0`` (or the batch is too small to split), returns - ``(data, None, None)`` — a no-op, so existing runs are byte-for-byte - unchanged. When ``test_split <= 0`` the third element is ``None`` (the - two-way explore/confirm behaviour). With both fractions set, CONFIRM is - drawn first (same seed as the two-way split), then TEST from the - remainder (seed+1); EXPLORE is what is left. - """ - from evalrx.core.case import CaseBatch - from evalrx.stats.subset_sampling import stratified_subset - - cases = list(data) - frac = self.confirm_split - if frac <= 0.0 or len(cases) < 4: - return data, None, None - n_confirm = round(len(cases) * frac) - if n_confirm <= 0 or n_confirm >= len(cases): - return data, None, None - three_way = self.test_split > 0.0 - confirm = stratified_subset(cases, self._strat_key, n_confirm, - seed=self.confirm_split_seed) - if three_way: - # ``stratified_subset`` guarantees at MOST n (per-stratum rounding - # can under-allocate by one or two); the train/val/test mode - # promises exact counts, so top the draw up deterministically. - # The two-way path is left untouched — byte-for-byte reproducible. - confirm = _exact_size(confirm, cases, n_confirm, - self.confirm_split_seed) - confirm_ids = {id(c) for c in confirm} - rest = [c for c in cases if id(c) not in confirm_ids] - if not three_way: - return CaseBatch(rest), CaseBatch(confirm), None - n_test = round(len(cases) * self.test_split) - if n_test <= 0 or n_test >= len(rest): - return CaseBatch(rest), CaseBatch(confirm), None - test = stratified_subset(rest, self._strat_key, n_test, - seed=self.confirm_split_seed + 1) - test = _exact_size(test, rest, n_test, self.confirm_split_seed + 1) - test_ids = {id(c) for c in test} - explore = [c for c in rest if id(c) not in test_ids] - return CaseBatch(explore), CaseBatch(confirm), CaseBatch(test) + """This loop's (explore, confirm, test) partition of *data* + (see :func:`~evalrx.eval_agent.loop.partition.split_cases`).""" + return split_cases(data, confirm_split=self.confirm_split, + test_split=self.test_split, seed=self.confirm_split_seed) def _split_explore_confirm(self, data: "CaseBatch"): """The (explore, confirm) view of :meth:`_split_partitions`. @@ -488,536 +395,27 @@ def _split_explore_confirm(self, data: "CaseBatch"): explore, confirm, _test = self._split_partitions(data) return explore, confirm - def _bridge_signals(self, probe_results: "dict[str, Any]", data: "Any | None") -> None: - """Compile pre-registered signal recipes into a synthetic analyzer Result - and inject it into *probe_results* so M2/M3/M4 see the bridged composite - signals through the standard findings["per_case"] contract. No-op when no - recipes are configured. Never raises into the loop.""" - if not self._signal_recipes: - return - # Never silently overwrite a real analyzer that already used this key. - name = self._bridge_analyzer_name - if name in probe_results: - base, n = name, 1 - while name in probe_results: - name, n = f"{base}_bridge{n}", n + 1 - logger.warning( - "bridge analyzer name %r collides with a real analyzer; " - "injecting under %r instead", base, name, - ) - try: - from evalrx.analysis.operationalize import bridge_recipes_to_result - - synth = bridge_recipes_to_result( - self._signal_recipes, probe_results, data, - model_repr=repr(self.model), - analyzer_name=name, - ) - except Exception as exc: # bridging must never sink the loop - logger.warning("signal bridge failed: %s", exc) - return - if synth is None: - return - probe_results[name] = synth - self.store.add_result(synth) - # The bridged signals ARE the discovered candidates — they must be tested, - # not optional. The plan caps at the stats agent's max_signal_tools and - # appends bridged signals LAST, so a low cap silently drops them. Raise the - # cap to cover the expanded family (more multiplicity = more conservative, - # never less — e-BH still controls FDR over whatever is tested). - agent = getattr(self, "stats_agent", None) - if agent is not None and hasattr(agent, "_max_signal_tools"): - try: - from evalrx.analysis.stats_tools import build_stats_input - - n_signals = len(build_stats_input(probe_results, data).per_case) - current = getattr(agent, "_max_signal_tools", None) - if current is not None: - agent._max_signal_tools = max(int(current), n_signals) - except Exception as exc: # never let the cap-bump break the loop - logger.debug("bridge: could not raise stats signal cap: %s", exc) - logger.info( - "bridged %d signal row(s) into M2 as analyzer %r", - len(synth.findings.get("per_case", [])), name, - ) - # ────────────────────────────────────────────────────────────────── - # Stage helpers (shared by run / run_analysis / run_confirm) + # Public API # ────────────────────────────────────────────────────────────────── - def _get_diagnosis_agent(self) -> "Any": - """Resolve M3 lazily: a DiagnosisAgent() built eagerly would raise if - GEMINI_API_KEY is absent even when the caller passed diagnosis_agent=None.""" - if self.diagnosis_agent is not None: - return self.diagnosis_agent - from evalrx.eval_agent.stages.diagnosis import DiagnosisAgent - return DiagnosisAgent() - - def _do_m1( - self, cycle: int, data: "Any", all_hypotheses: "list[Any]", - timings: "dict[str, float]", *, log: bool = True, - analyzers: "list[str] | None" = None, - analyzer_params: "dict[str, dict[str, Any]] | None" = None, - ) -> "tuple[dict[str, Any], list]": - """M1: protocol-guided probing + signal bridge. - - Returns ``(probe_results, artifact_pngs)``; ``probe_results`` is empty - when M1 produced nothing (caller decides whether to stop). When - ``log`` is False the probe events are not written — used by - :meth:`run_confirm` when it only needs to regenerate the stats the - tester reads (M1/M2 already belong to the analysis phase's log). - - ``analyzers`` / ``analyzer_params`` name the probes and their arguments - explicitly, bypassing selection (see :meth:`ProbeAgent.probe`); the - agentic loop's ``run_probe`` tool passes them through.""" - prior_modes = list(dict.fromkeys( - h.predicted_failure_mode for h in all_hypotheses - if getattr(h, "predicted_failure_mode", None) - )) - # Named calls run exactly what was named (no cap, no backfill). - named: dict[str, Any] = {"analyzers": analyzers, "exact": True} if analyzers is not None else {} - if analyzer_params: - named["analyzer_params"] = analyzer_params - _t0 = time.monotonic() - probe_results = self.probe_agent.probe( - self.model, - data, - protocol=self.protocol, - prior_hypotheses=all_hypotheses or None, - hint_failure_modes=prior_modes or None, - **named, - ) - _dt = time.monotonic() - _t0 - timings["m1"] = timings.get("m1", 0.0) + _dt - artifact_pngs: list = [] - if log and self.run_logger: - artifact_pngs = self.run_logger.log_probe( - cycle, probe_results, schema=self.probe_agent.last_schema, - cases=data, - judge_prompt=getattr(self.probe_agent, "last_selection_prompt", ""), - judge_raw=getattr(self.probe_agent, "last_selection_raw", ""), - duration_sec=_dt, - ) or [] - _log_generated_tools(self.run_logger, cycle, "m1_probe", self.probe_agent) - self._emit_m1(cycle, probe_results, data, _dt) - if not probe_results: - return {}, [] - for r in probe_results.values(): - self.store.add_result(r) - # Operationalization bridge: pre-registered recipes -> synthetic - # "explored" analyzer Result (no-op when none configured). - self._bridge_signals(probe_results, data) - return probe_results, artifact_pngs - - def _emit_m1(self, cycle: int, probe_results: "dict[str, Any]", data: "Any", - duration_sec: float) -> None: - """Emit M1's ProbeOutput, including how analyzer routing was decided. - - The three modality sets are recorded separately because they can differ - and the difference is the diagnosis: an omni model on an audio benchmark - declares four modalities, fills one, and is routed on one. - """ - if self.emitter is None: - return - from evalrx.contract.emit import from_probe_results - from evalrx.core.case import probed_modalities - - selector = self.probe_agent.selector if hasattr(self.probe_agent, "selector") else None - declared = sorted(getattr(self.model, "modalities", frozenset({"text"})) or {"text"}) - probed = sorted(probed_modalities(data)) - routed = sorted( - selector.routed_slots(self.model, data) if selector is not None else probed - ) - # Trajectories in the batch, not declared TOOL_CALLS: the api backend - # reports tool_calls for every chat model, which made a single-turn text - # run record itself as an agent run. - from evalrx.eval_agent.stages.probe import _carries_trajectories - - is_agent = bool(data is not None and _carries_trajectories(data)) - self._emit(f"c{cycle}.m1", lambda: from_probe_results( - probe_results, - trace_id=self.emitter.trace_id, cycle=cycle, model=self.model, - model_modalities=declared, probed_modalities=probed, routed_on=routed, - is_agent=is_agent, - selector="llm_judge" if getattr(self.probe_agent, "judge", None) else "static_strategy", - generated=list(getattr(self.probe_agent, "generated_probes", []) or []), - failed_analyzers=dict(getattr(self.probe_agent, "_failed_analyzers", {}) or {}), - duration_sec=duration_sec, - )) - - def _explore_out_dir(self) -> "Path | None": - """Where the explore step persists its report/tables/figures. - - Explicit ``explore_dir`` wins. Otherwise it is derived from the run - logger so the files land INSIDE the run, beside the log, where the - report reader looks (``reporting.run_data``: ``/explore``, else a - sibling ``explore/``): - - - a :class:`~evalrx.eval_agent.run_context.RunContext`-backed logger - → ``ctx.explore_dir``, an ephemeral tree under ``ctx.runtime_root`` - (captured into ``M2/log.json`` and deleted at ``finalize()``; - writing straight to ``/explore`` would leak real files - outside the JSON-only run artifact); - - a standalone ``RunLogger("/logs")`` / ``logs_confirm`` … → - ``/explore`` (a sibling of the ``logs*/`` dir, the llm_benchmark - layout — under the log dir it would be two levels down for a - ``logs_confirm/`` carrier log and the report would miss it); - - any other standalone run dir → ``/explore``. - - ``None`` (nothing persisted, context in memory only) without a logger.""" - if self._explore_dir is not None: - return self._explore_dir - if self.run_logger is None: - return None - ctx = getattr(self.run_logger, "_context", None) - if ctx is not None and hasattr(ctx, "explore_dir"): - return ctx.explore_dir - run_dir = getattr(self.run_logger, "run_dir", None) - if run_dir is None: - return None - run_dir = Path(run_dir) - if run_dir.name.startswith("logs"): - return run_dir.parent / "explore" - return run_dir / "explore" - - def _do_explore( - self, cycle: int, probe_results: "dict[str, Any]", data: "Any", - timings: "dict[str, float]", *, log: bool = True, question: str | None = None, - ) -> "Any | None": - """Optional in-cycle explore step: free-form EDA over M1's per-case table. - - Runs between M1 and M2 when an ``explorer`` is configured. The explorer - sees exactly what M2 sees — ``build_stats_input`` → ``per_case_to_records`` - (M1 analyzer per-case signals + PASS/FAIL labels) — writes tables and - chart specs, and the host renders the charts. The result feeds: - - - M3, as an :class:`~evalrx.eval_agent.stages.diagnosis.ExploreContext` - (observations / rendered charts / caveats — descriptive, UNCONFIRMED, - used only to decide WHICH hypotheses to propose); - - the report, via ``exploratory_report.json`` + ``tables/`` + - ``figures/`` under :meth:`_explore_out_dir` (one directory, rewritten - each cycle — it always holds what the *latest* M3 was shown; the - per-cycle ``explore`` run-log events keep every cycle's counts and - observations). - - It never touches M2's confirmatory family, M4, or the fix gate: the - explorer's candidate-signal verdicts are host-adjudicated IN-SAMPLE - (labelled so) and dropped from the M3 context by construction. Held-out - confirmation of explorer recipes is the fused pipeline's job, not this - step's. Best-effort: any failure logs a warning and returns ``None`` — - an explorer outage must not cost the M2/M3 that already have their data. - - Returns the explorer report (or ``None``).""" - if self.explorer is None: - return None - from evalrx.analysis.operationalize import per_case_to_records - from evalrx.analysis.stats_tools import build_stats_input - from evalrx.eval_agent.stages.diagnosis import ExploreContext - - _t0 = time.monotonic() - report: Any = None - out_dir = self._explore_out_dir() - try: - inp = build_stats_input(probe_results, data) - records = per_case_to_records(inp.per_case, inp.labels) - if not records: - logger.info("explore: M1 produced no per-case signals — skipping.") - return None - question = question or self._explore_question - if not question: - from evalrx.eval_agent.prompts.explore_step import default_explore_question - - question = default_explore_question(self.protocol) - report = self.explorer.explore_records( - records, question=question, outcome_col="label", - ) - # Host firewall: recompute every candidate verdict from sufficient - # statistics with the M2 core (in-sample here — labelled as such so - # nothing downstream mistakes it for a held-out result). - try: - from evalrx.analysis.adjudicate import adjudicate_report - - adjudicate_report(report, split_label="in_sample") - except Exception as exc: # adjudication is a verdict layer, not the data - logger.warning("explore: host adjudication failed: %s", exc) - if out_dir is not None: - from evalrx.analysis.explore_run import write_report_artifacts - - # Renders chart specs from the copied tables/ CSVs, so the - # persisted report carries each chart's absolute figure_path — - # the PNGs M3 is shown and the report displays. - write_report_artifacts(report, out_dir) - ctx = ExploreContext.from_report( - report.to_dict() if hasattr(report, "to_dict") else None - ) - if ctx is not None: - ctx.source = "loop_explorer" - self._explore_context = ctx - elif getattr(report, "ok", False): - logger.info("explore: report carried no observations/charts — " - "M3 keeps its previous explore context.") - except Exception as exc: # the explorer must never sink the loop - logger.warning( - "explore step failed at cycle %d (%s) — M2/M3 continue without " - "explorer notes.", cycle, exc, - ) - _dt = time.monotonic() - _t0 - timings["explore"] = timings.get("explore", 0.0) + _dt - if log and self.run_logger is not None: - try: - self.run_logger.log_explore( - cycle, report, out_dir=out_dir, duration_sec=_dt, - ) - except Exception as exc: # logging must never break the run - logger.warning("explore: could not log the explore event: %s", exc) - return report - - def _do_m2( - self, cycle: int, probe_results: "dict[str, Any]", data: "Any", - artifact_pngs: "list", timings: "dict[str, float]", *, log: bool = True, - confirmatory: bool = True, - ) -> "Any": - """M2: protocol-aware rigorous stats analysis (effect sizes + charts). - - ``confirmatory=False`` defers the e-BH validity verdict (the analysis - phase shows distributions only); the confirm phase recomputes it.""" - _t0 = time.monotonic() - stats_report = self.stats_agent.analyze( - probe_results, - model_name=repr(self.model), - protocol=self.protocol, - data=data, - extra_figures=artifact_pngs, - confirmatory=confirmatory, - ) - _dt = time.monotonic() - _t0 - timings["m2"] = timings.get("m2", 0.0) + _dt - if log and self.run_logger: - self.run_logger.log_analysis(cycle, stats_report, duration_sec=_dt) - _log_generated_tools(self.run_logger, cycle, "m2_stats", self.stats_agent) - if self.emitter is not None: - from evalrx.contract.emit import from_stats_report - - self._emit(f"c{cycle}.m2", lambda: from_stats_report( - stats_report, trace_id=self.emitter.trace_id, cycle=cycle, - raw_results_ref=f"contract/c{cycle}.m1.json", duration_sec=_dt, - )) - return stats_report - - def _do_m3( - self, cycle: int, stats_report: "Any", prior_cycles: "list[Any]", - timings: "dict[str, float]", *, log: bool = True, - failure_modes: "Any | None" = None, cases: "Any | None" = None, - ) -> "Any | None": - """M3: hypothesis generation. Returns the diagnosis result, or ``None`` - when M3 could not run (judge unavailable / timeout / quota) — the caller - stops gracefully on ``None`` (regression guard: an M3 timeout must not - kill the whole run after M1+M2 succeeded). Also accrues token usage. - - ``failure_modes`` (optional clustered ``FailureModeReport``) is passed - through to the diagnosis agent only when it accepts the parameter — - ``None`` (the default, always the case for ``VLDiagnoseLoop``) adds - nothing to the prompt and costs no extra call.""" - _t0 = time.monotonic() - for attempt in range(self.diagnosis_retries + 1): - try: - diag_agent = self._get_diagnosis_agent() - self.diagnosis_agent = diag_agent - diag = _diagnose_with_optional_context( - diag_agent, stats_report, prior_cycles, self._explore_context, - failure_modes, cases=cases, - ) - break - except Exception as exc: - retrying = attempt < self.diagnosis_retries - error = f"{type(exc).__name__}: {exc}" - logger.warning("M3 attempt %d failed (%s); retrying=%s", - attempt + 1, error, retrying) - if self.run_logger is not None: - # A JudgeError carries what the judge was asked and answered. - for call in (e.record() for e in getattr(exc, "exchanges", ())): - self.run_logger.log_model_exchange( - "M3", cycle=cycle, role=call["role"], operation=call["operation"], - inputs=call["inputs"], output=call["output"], error=call["error"], - duration_sec=call["duration_sec"], metadata=call["metadata"], - ) - self.run_logger.log_model_exchange( - stage="M3", cycle=cycle, role="diagnosis", operation="diagnose", - inputs=None, output=None, error=error, - metadata={"attempt": attempt + 1, "retrying": retrying}, - duration_sec=time.monotonic() - _t0, - ) - if not retrying: - timings["m3"] = timings.get("m3", 0.0) + time.monotonic() - _t0 - return None - _dt = time.monotonic() - _t0 - timings["m3"] = timings.get("m3", 0.0) + _dt - - _tok = getattr(diag, "tokens_used", None) - if _tok is None: - _tok = max(1, len(diag.raw_judge_output) // 4) - self._tokens_used += _tok - - if log and self.run_logger: - # Log only the figures that actually existed (the same existence - # filter M3 applies) so the audit trail reflects what the judge saw. - _explore_figs = None - if self._explore_context is not None: - from pathlib import Path as _P - - _explore_figs = [ - f for f in self._explore_context.figure_paths if _P(f).exists() - ] - self.run_logger.log_diagnosis( - cycle, diag, duration_sec=_dt, explore_figures=_explore_figs or None - ) - if self.emitter is not None: - from evalrx.contract.emit import from_diagnosis - - self._emit(f"c{cycle}.m3", lambda: from_diagnosis( - diag, trace_id=self.emitter.trace_id, cycle=cycle, duration_sec=_dt, - )) - return diag - - @staticmethod - def _finalize_confirmatory_stats(stats_report: "Any") -> None: - """Promote a descriptive (analysis-phase) stats report to confirmatory. - - The analysis phase runs M2 with the e-BH validity verdict DEFERRED - (``descriptive_only=True``). The confirm phase recomputes e-BH FDR - correction over the report's stats results so M4 and the report see - the family-level reject decision. No-op when already confirmatory.""" - if stats_report is None: - return - corr = getattr(stats_report, "corrected_rejections", None) or {} - if getattr(stats_report, "descriptive_only", False) or corr.get("deferred"): - from evalrx.analysis.stats_tools import fdr_correct + def stages(self) -> Stages: + """The stages bound to this loop's current configuration, for one run. - stats_report.corrected_rejections = fdr_correct( - list(getattr(stats_report, "stats_results", None) or []) - ) - stats_report.descriptive_only = False - - def _do_m4( - self, cycle: int, hypotheses: "list[Any]", stats_report: "Any", - data: "Any", timings: "dict[str, float]", *, log: bool = True, - split_label: "str | None" = None, - ) -> "list[Any]": - """M4: statistical test + protocol consistency for each hypothesis, - writing the verdict back onto ``hypothesis.status``. - - ``split_label`` tags each result's evidence with which data split the - test read (``"confirm_holdout"`` for the held-out pass) BEFORE the - result is logged, so the marker reaches the run log too.""" - _t0 = time.monotonic() - test_results = self.hypothesis_tester.test( - hypotheses, - stats_report, - data, - protocol=self.protocol, - ) - _dt = time.monotonic() - _t0 - timings["m4"] = timings.get("m4", 0.0) + _dt - for tr in test_results: - tr.hypothesis.status = tr.status - if split_label and isinstance(getattr(tr, "evidence", None), dict): - tr.evidence["split"] = split_label - if log and self.run_logger: - # M4 results are logged through the surgery slot. - for tr in test_results: - _iv = _make_intervention_result_from_test(tr) - self.run_logger.log_surgery( - cycle, tr.hypothesis, _iv, duration_sec=_dt, - validation_cases=data, - judge_prompt=getattr(tr, "judge_prompt", None) or None, - judge_raw=getattr(tr, "judge_raw", None) or None, - ) - if log and self.emitter is not None: - from evalrx.contract.emit import from_test_results - - # M4 has no stage log of its own — it reuses the per-hypothesis - # surgery slot — so this is the first place the whole verdict set - # exists as one object a reader can load. - split = "confirm" if split_label == "confirm_holdout" else "explore" - self._emit(f"c{cycle}.m4", lambda: from_test_results( - test_results, trace_id=self.emitter.trace_id, cycle=cycle, - split=split, duration_sec=_dt, - stopping_criteria_met=bool( - self.hypothesis_tester.stopping_criteria_met(test_results, self.protocol) - ), - )) - return test_results - - def _m4_holdout_pass( - self, - hypotheses: "list[Any]", - confirm: "Any", - analyzer_names: "list[str]", - timings: "dict[str, float]", - ) -> "tuple[list[Any], str]": - """The M4 pass — on the held-out confirm split. - - With a confirm split in play this is the ONLY hypothesis test: M3's - hypotheses are taken straight to data M1/M2/M3 never mined. The same - analyzers as the last explore cycle are re-run on the confirm split - (pinned via ``ProbeAgent.probe(analyzers=)`` — a fresh judge selection - could miss the designated signals); with no names to pin (a reloaded - run without a stats report) the probe agent selects normally. - - Returns ``(test_results, status)`` with status ``"confirmed"`` (the - pass ran) or ``"failed"`` (the confirm re-probe produced nothing — no - hypothesis can be verified this run). + Built fresh each time so a setting changed after construction applies; + what outlives a run (explorer notes, the default M3 agent, the token + count) is in the loop's :class:`~evalrx.eval_agent.loop.stages.StageMemory`. """ - pinned = [n for n in analyzer_names if not n.startswith("generated:")] - logger.info( - "M4 (held-out): testing %d hypothesis(es) on the %d-case confirm " - "split (analyzers: %s)", - len(hypotheses), len(list(confirm)), - ", ".join(pinned) or "", + return Stages( + model=self.model, protocol=self.protocol, probe_agent=self.probe_agent, + stats_agent=self.stats_agent, hypothesis_tester=self.hypothesis_tester, + store=self.store, run_logger=self.run_logger, emitter=self.emitter, + memory=self._memory, diagnosis_agent=self.diagnosis_agent, + diagnosis_retries=self.diagnosis_retries, explorer=self.explorer, + explore_dir=self._explore_dir, explore_question=self._explore_question, + signal_recipes=self._signal_recipes, + bridge_analyzer_name=self._bridge_analyzer_name, ) - # Stamped BEFORE probe() (not just before log_probe below): ProbeAgent - # tags every model call it makes with whatever current_cycle reads AT - # CALL TIME, and probe() is where those calls happen. Setting this - # only right before log_probe(-1, ...) tagged this whole confirm-split - # re-probe's model calls with the previous explore cycle's number. - if self.run_logger: - self.run_logger.current_cycle = -1 - _t0 = time.monotonic() - if pinned: - probe_results = self.probe_agent.probe( - self.model, confirm, protocol=self.protocol, - prior_hypotheses=hypotheses or None, analyzers=pinned, - ) - else: - probe_results = self.probe_agent.probe( - self.model, confirm, protocol=self.protocol, - prior_hypotheses=hypotheses or None, - ) - timings["m4_holdout_m1"] = timings.get("m4_holdout_m1", 0.0) + ( - time.monotonic() - _t0) - if not probe_results: - logger.warning( - "M4 (held-out): the confirm-split re-probe produced no results " - "— no hypothesis can be verified this run." - ) - return [], "failed" - self._bridge_signals(probe_results, confirm) - if self.run_logger: - self.run_logger.log_probe( - -1, probe_results, - schema=getattr(self.probe_agent, "last_schema", None), - cases=confirm, - ) - stats_confirm = self._do_m2( - -1, probe_results, confirm, [], timings, confirmatory=True - ) - results = self._do_m4(-1, hypotheses, stats_confirm, confirm, timings, - split_label="confirm_holdout") - return results, "confirmed" - - # ────────────────────────────────────────────────────────────────── - # Public API - # ────────────────────────────────────────────────────────────────── def run(self, data: "CaseBatch") -> AutoDiagnoseReport: """Drive the M1→M2→M3→M4 loop to convergence. @@ -1030,7 +428,7 @@ def run(self, data: "CaseBatch") -> AutoDiagnoseReport: :class:`AutoDiagnoseReport` with the final state. Call :meth:`run_m5` on this to get a fix proposal (Plan A). """ - self._tokens_used = 0 + self._memory.tokens_used = 0 # Per-stage wall-clock totals (seconds) for the loop_end cost profile. timings: dict[str, float] = {} report = self.policy.run(self, data, timings) @@ -1096,7 +494,7 @@ def _start_run_log( def _end_run(self, report: AutoDiagnoseReport, timings: dict[str, float]) -> AutoDiagnoseReport: if self.run_logger: - self.run_logger.log_loop_end(report, tokens_used=self._tokens_used, timings=timings) + self.run_logger.log_loop_end(report, tokens_used=self._memory.tokens_used, timings=timings) return report def run_analysis(self, data: "CaseBatch") -> AutoDiagnoseReport: @@ -1120,7 +518,7 @@ def run_analysis(self, data: "CaseBatch") -> AutoDiagnoseReport: Unlike :meth:`run`, there is no M4 stopping signal, so this is a single pass (one M1→M2→M3), not a multi-cycle loop; ``max_cycles`` is ignored. """ - self._tokens_used = 0 + self._memory.tokens_used = 0 timings: dict[str, float] = {} # Same deterministic explore/confirm partition as run() / run_fix() — @@ -1140,20 +538,21 @@ def run_analysis(self, data: "CaseBatch") -> AutoDiagnoseReport: final_stats_report = None stopped_by = STOPPED_BY_ANALYSIS - probe_results, artifact_pngs = self._do_m1(0, data, all_hypotheses, timings) + stages = self.stages() + probe_results, artifact_pngs = stages.probe(0, data, all_hypotheses, timings) if not probe_results: logger.info("M1 produced no probe results — stopping.") stopped_by = STOPPED_BY_NO_PROBE else: # Optional explore step (descriptive EDA → M3 notes + report files). - self._do_explore(0, probe_results, data, timings) + stages.explore(0, probe_results, data, timings) # Descriptive M2: effect sizes + charts, but DEFER the e-BH validity # verdict to run_confirm so the analysis report shows no # "supported/not-supported" claim (Q2: no validity before confirm). - final_stats_report = self._do_m2( + final_stats_report = stages.analyze( 0, probe_results, data, artifact_pngs, timings, confirmatory=False ) - diag = self._do_m3(0, final_stats_report, [], timings, cases=data) + diag = stages.diagnose(0, final_stats_report, [], timings, cases=data) if diag is None or not diag.hypotheses: # Stats + report are still valid; just no hypotheses to confirm. if diag is not None: @@ -1201,7 +600,7 @@ def run_confirm( ``verified_hypotheses`` populated. Feed it into :meth:`run_m5` / :meth:`run_fix` for the repair step. """ - self._tokens_used = 0 + self._memory.tokens_used = 0 timings: dict[str, float] = {} hypotheses = list(hypotheses or []) @@ -1228,7 +627,7 @@ def run_confirm( # from the descriptive analysis phase (e-BH deferred), compute e-BH now, # flip descriptive_only off, and log the confirmatory M2 so the report # surfaces the signal validity it withheld before confirmation. - self._finalize_confirmatory_stats(stats_report) + finalize_confirmatory_stats(stats_report) if self.run_logger and stats_report is not None: self.run_logger.log_analysis(0, stats_report) @@ -1261,14 +660,15 @@ def _confirm_stats( analysis phase, and re-logging them would double up the report's analysis story. """ - probe_results, artifact_pngs = self._do_m1(0, data, hypotheses, timings, log=False) + stages = self.stages() + probe_results, artifact_pngs = stages.probe(0, data, hypotheses, timings, log=False) if not probe_results: logger.warning( "run_confirm: probe produced no results and no stats_report " "was supplied — cannot confirm." ) return None - return self._do_m2(0, probe_results, data, artifact_pngs, timings, log=False) + return stages.analyze(0, probe_results, data, artifact_pngs, timings, log=False) def _m4_verdicts( self, hypotheses: "list[Any]", stats_report: "Any", data: "CaseBatch", @@ -1282,12 +682,12 @@ def _m4_verdicts( self.store.add_hypothesis(h) holdout_target = self._holdout_target(confirm) if holdout_target is None: - return self._do_m4(0, hypotheses, stats_report, data, timings), None + return self.stages().test_hypotheses(0, hypotheses, stats_report, data, timings), None # The one M4 pass, on held-out data (never the explore stats the # hypotheses were mined from). The analyzer set to re-run there is # recovered from the supplied/regenerated stats report's signal keys; # with none recoverable the probe agent selects on the holdout itself. - return self._m4_holdout_pass( + return self.stages().test_on_holdout( hypotheses, holdout_target, _analyzer_names_from_stats(stats_report), timings, ) @@ -1459,7 +859,7 @@ def run_fix( context = _fix_context_from_report( report, example_cases=explore if final_data is not None else None, - explore_context=self._explore_context, + explore_context=self._memory.explore_context, protocol=self.protocol, refuted=refuted_notes, refuted_ids=refuted_ids, diff --git a/evalrx/eval_agent/loop_fix.py b/evalrx/eval_agent/loop/fix.py similarity index 99% rename from evalrx/eval_agent/loop_fix.py rename to evalrx/eval_agent/loop/fix.py index 2f1f42eb..af022e11 100644 --- a/evalrx/eval_agent/loop_fix.py +++ b/evalrx/eval_agent/loop/fix.py @@ -3,7 +3,7 @@ Which hypotheses a fix targets, the tier ladder, the EXPLORE→CONFIRM split, and the run-log record of the outcome. Free functions over the loop's report and fix agent; ``VLDiagnoseLoop.run_fix`` / ``run_m5`` call them. -This module does not import :mod:`evalrx.eval_agent.loop`. +This module does not import :mod:`evalrx.eval_agent.loop.diagnose`. """ from __future__ import annotations diff --git a/evalrx/eval_agent/policy.py b/evalrx/eval_agent/loop/fixed.py similarity index 64% rename from evalrx/eval_agent/policy.py rename to evalrx/eval_agent/loop/fixed.py index 3c529c53..181f7aa1 100644 --- a/evalrx/eval_agent/policy.py +++ b/evalrx/eval_agent/loop/fixed.py @@ -1,19 +1,17 @@ -"""Who picks the next stage of a :class:`~evalrx.eval_agent.loop.VLDiagnoseLoop` run. +"""The default next-step policy: M1→M2→M3(→M4) cycles in a fixed order. -The loop owns the stages (M1 probe, explore, M2 stats, M3 diagnosis, M4 test), -the run log and the confirm split. A policy decides the order: -:class:`FixedOrderPolicy` (the default) runs M1→M2→M3→M4 cycles; -:class:`~evalrx.eval_agent.agentic.policy.JudgePolicy` asks a judge, one tool -call at a time. Both keep their bookkeeping in one :class:`RunState`. +The loop (:class:`~evalrx.eval_agent.loop.diagnose.VLDiagnoseLoop`) owns the +stages, the run log and the confirm split; a policy only decides the order. +The alternative is :class:`~evalrx.eval_agent.loop.judge.policy.JudgePolicy`, +which asks a judge one tool call at a time. """ from __future__ import annotations import logging -from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Protocol +from typing import TYPE_CHECKING -from evalrx.eval_agent.loop_reports import ( +from evalrx.eval_agent.loop.report import ( STOPPED_BY_BUDGET, STOPPED_BY_CRITERIA, STOPPED_BY_DIAG_ERROR, @@ -22,62 +20,15 @@ STOPPED_BY_NO_PROBE, AutoDiagnoseReport, ) +from evalrx.eval_agent.loop.state import RunState, cycle_summary if TYPE_CHECKING: from evalrx.core.case import CaseBatch - from evalrx.eval_agent.loop import VLDiagnoseLoop + from evalrx.eval_agent.loop.diagnose import VLDiagnoseLoop logger = logging.getLogger(__name__) -class Policy(Protocol): - def run(self, loop: "VLDiagnoseLoop", data: "CaseBatch", - timings: dict[str, float]) -> AutoDiagnoseReport: ... - - -@dataclass -class RunState: - """What one run accumulates, whichever policy drives it.""" - - original_data: Any - data: Any - timings: dict[str, float] = field(default_factory=dict) - cycle: int = 0 - all_hypotheses: list[Any] = field(default_factory=list) - all_test_results: list[Any] = field(default_factory=list) - #: Each finished cycle's summary, M3's context for the next one. - prior_cycles: list[dict[str, Any]] = field(default_factory=list) - stats_report: Any = None - diagnosis_failed: bool = False - #: The last M1's analyzers — what the held-out M4 pass re-runs. - analyzer_names: list[str] = field(default_factory=list) - # Judge-decided runs only: the decision judge and the tools' working state. - judge: Any = None - pending_hypotheses: list[Any] = field(default_factory=list) - probe_results: dict[str, Any] = field(default_factory=dict) - artifact_pngs: list[Any] = field(default_factory=list) - failure_modes: Any = None - probe_search_result: Any = None - surgery_outcome: Any = None - fix_outcome: Any = None - - -def cycle_summary(cycle: int, stats_report: Any, hypotheses: list) -> dict[str, Any]: - """One finished cycle as the next M3 call sees it.""" - return { - "cycle": cycle, - "severity": getattr(stats_report, "severity", "none"), - "hypotheses": [ - { - "statement": h.statement, - "failure_mode": h.predicted_failure_mode, - "status": h.status.value if h.status else "pending", - } - for h in hypotheses - ], - } - - class FixedOrderPolicy: """M1→M2→M3(→M4) cycles until a stopping rule fires (the default policy). @@ -106,7 +57,8 @@ def run(self, loop: "VLDiagnoseLoop", data: "CaseBatch", holdout_target = loop._holdout_target(confirm) loop._start_run_log(data, "VLDiagnoseLoop", confirm=confirm, test=test, val=loop.val_data) - state = RunState(original_data=original_data, data=data, timings=timings) + state = RunState(original_data=original_data, data=data, stages=loop.stages(), + timings=timings) stopped_by = STOPPED_BY_MAX cycles = 0 for cycle in range(loop.max_cycles): @@ -121,7 +73,7 @@ def run(self, loop: "VLDiagnoseLoop", data: "CaseBatch", # applies to candidates. Without one, the in-cycle results stand. m4_holdout_status: "str | None" = None if holdout_target is not None and state.all_hypotheses: - state.all_test_results, m4_holdout_status = loop._m4_holdout_pass( + state.all_test_results, m4_holdout_status = state.stages.test_on_holdout( state.all_hypotheses, holdout_target, state.analyzer_names, timings, ) verified = loop.hypothesis_tester.best_hypotheses(state.all_test_results) @@ -150,30 +102,31 @@ def _cycle(loop: "VLDiagnoseLoop", cycle: int, state: RunState, *, holdout: bool """ data, timings = state.data, state.timings state.cycle = cycle - if loop.token_budget > 0 and loop._tokens_used >= loop.token_budget: + stages = state.stages + if loop.token_budget > 0 and stages.memory.tokens_used >= loop.token_budget: logger.warning("Token budget %d exhausted after %d cycles", loop.token_budget, cycle) return STOPPED_BY_BUDGET if loop.run_logger is not None: loop.run_logger.current_cycle = cycle # ── M1: protocol-guided probing (+ signal bridge) ───────── - probe_results, artifact_pngs = loop._do_m1(cycle, data, state.all_hypotheses, timings) + probe_results, artifact_pngs = stages.probe(cycle, data, state.all_hypotheses, timings) if not probe_results: logger.info("M1 produced no probe results — stopping.") return STOPPED_BY_NO_PROBE state.analyzer_names = list(probe_results) # ── explore (optional): free-form EDA on M1's table → M3 notes ── - loop._do_explore(cycle, probe_results, data, timings) + stages.explore(cycle, probe_results, data, timings) # ── M2: protocol-aware stats analysis ──────────────────── - stats_report = loop._do_m2(cycle, probe_results, data, artifact_pngs, timings) + stats_report = stages.analyze(cycle, probe_results, data, artifact_pngs, timings) state.stats_report = stats_report if loop.analysis_only: return STOPPED_BY_NO_HYPS # ── M3: hypothesis generation ("AI scientist") ──────────── - diag = loop._do_m3(cycle, stats_report, state.prior_cycles, timings, cases=data) + diag = stages.diagnose(cycle, stats_report, state.prior_cycles, timings, cases=data) if diag is None: state.diagnosis_failed = True return STOPPED_BY_DIAG_ERROR @@ -186,7 +139,7 @@ def _cycle(loop: "VLDiagnoseLoop", cycle: int, state: RunState, *, holdout: bool # ── M4: hypothesis testing (stats + protocol consistency) ─ if not holdout: - test_results = loop._do_m4(cycle, diag.hypotheses, stats_report, data, timings) + test_results = stages.test_hypotheses(cycle, diag.hypotheses, stats_report, data, timings) state.all_test_results.extend(test_results) if loop.hypothesis_tester.stopping_criteria_met(test_results, loop.protocol): logger.info( diff --git a/evalrx/eval_agent/agentic/__init__.py b/evalrx/eval_agent/loop/judge/__init__.py similarity index 74% rename from evalrx/eval_agent/agentic/__init__.py rename to evalrx/eval_agent/loop/judge/__init__.py index a3002631..c8eb4b27 100644 --- a/evalrx/eval_agent/agentic/__init__.py +++ b/evalrx/eval_agent/loop/judge/__init__.py @@ -9,10 +9,10 @@ from __future__ import annotations -from evalrx.eval_agent.agentic.actions import Action, decide -from evalrx.eval_agent.agentic.board import BudgetState, EvidenceBoard -from evalrx.eval_agent.agentic.policy import JudgePolicy -from evalrx.eval_agent.agentic.tools import ( +from evalrx.eval_agent.loop.judge.actions import Action, decide +from evalrx.eval_agent.loop.judge.board import BudgetState, EvidenceBoard +from evalrx.eval_agent.loop.judge.policy import JudgePolicy +from evalrx.eval_agent.loop.judge.tools import ( ToolOutcome, ToolRegistry, ToolSpec, diff --git a/evalrx/eval_agent/agentic/actions.py b/evalrx/eval_agent/loop/judge/actions.py similarity index 95% rename from evalrx/eval_agent/agentic/actions.py rename to evalrx/eval_agent/loop/judge/actions.py index 340aba7c..3a012051 100644 --- a/evalrx/eval_agent/agentic/actions.py +++ b/evalrx/eval_agent/loop/judge/actions.py @@ -20,9 +20,9 @@ from evalrx.agent_runtime.judge_call import JudgeError, ask_judge if TYPE_CHECKING: - from evalrx.eval_agent.agentic.board import EvidenceBoard - from evalrx.eval_agent.agentic.tools import ToolRegistry - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.loop.judge.board import EvidenceBoard + from evalrx.eval_agent.loop.judge.tools import ToolRegistry + from evalrx.eval_agent.runlog.logger import RunLogger logger = logging.getLogger(__name__) diff --git a/evalrx/eval_agent/agentic/board.py b/evalrx/eval_agent/loop/judge/board.py similarity index 100% rename from evalrx/eval_agent/agentic/board.py rename to evalrx/eval_agent/loop/judge/board.py diff --git a/evalrx/eval_agent/agentic/policy.py b/evalrx/eval_agent/loop/judge/policy.py similarity index 89% rename from evalrx/eval_agent/agentic/policy.py rename to evalrx/eval_agent/loop/judge/policy.py index d8253940..583639b8 100644 --- a/evalrx/eval_agent/agentic/policy.py +++ b/evalrx/eval_agent/loop/judge/policy.py @@ -16,16 +16,16 @@ import logging from typing import TYPE_CHECKING, Any -from evalrx.eval_agent.agentic.actions import decide -from evalrx.eval_agent.agentic.board import BudgetState, EvidenceBoard -from evalrx.eval_agent.agentic.tools import ToolRegistry, build_default_registry -from evalrx.eval_agent.loop_reports import STOPPED_BY_DIAG_ERROR, AutoDiagnoseReport -from evalrx.eval_agent.policy import RunState -from evalrx.eval_agent.run_metadata import _data_provenance +from evalrx.eval_agent.loop.judge.actions import decide +from evalrx.eval_agent.loop.judge.board import BudgetState, EvidenceBoard +from evalrx.eval_agent.loop.judge.tools import ToolRegistry, build_default_registry +from evalrx.eval_agent.loop.metadata import _data_provenance +from evalrx.eval_agent.loop.report import STOPPED_BY_DIAG_ERROR, AutoDiagnoseReport +from evalrx.eval_agent.loop.state import RunState if TYPE_CHECKING: from evalrx.core.case import CaseBatch - from evalrx.eval_agent.loop import VLDiagnoseLoop + from evalrx.eval_agent.loop.diagnose import VLDiagnoseLoop logger = logging.getLogger(__name__) @@ -46,7 +46,7 @@ def _protocol_summary(protocol: "Any | None") -> str: class JudgePolicy: - """Next-step policy for :class:`~evalrx.eval_agent.loop.VLDiagnoseLoop`. + """Next-step policy for :class:`~evalrx.eval_agent.loop.diagnose.VLDiagnoseLoop`. Args: judge: Judge that decides the next action each turn (e.g. @@ -102,8 +102,8 @@ def run(self, loop: "VLDiagnoseLoop", data: "CaseBatch", ) board.budget.start() - state = RunState(original_data=original_data, data=data, timings=timings, - judge=self.judge) + state = RunState(original_data=original_data, data=data, stages=loop.stages(), + timings=timings, judge=self.judge) registry: ToolRegistry = ( self.registry_factory(loop, state) if self.registry_factory is not None diff --git a/evalrx/eval_agent/agentic/tools.py b/evalrx/eval_agent/loop/judge/tools.py similarity index 97% rename from evalrx/eval_agent/agentic/tools.py rename to evalrx/eval_agent/loop/judge/tools.py index 5e472666..ac7b6a39 100644 --- a/evalrx/eval_agent/agentic/tools.py +++ b/evalrx/eval_agent/loop/judge/tools.py @@ -12,12 +12,13 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable -from evalrx.eval_agent.policy import RunState, cycle_summary +from evalrx.eval_agent.loop.stages import finalize_confirmatory_stats +from evalrx.eval_agent.loop.state import RunState, cycle_summary if TYPE_CHECKING: - from evalrx.eval_agent.agentic.actions import Action - from evalrx.eval_agent.agentic.board import EvidenceBoard - from evalrx.eval_agent.loop_reports import AutoDiagnoseReport + from evalrx.eval_agent.loop.judge.actions import Action + from evalrx.eval_agent.loop.judge.board import EvidenceBoard + from evalrx.eval_agent.loop.report import AutoDiagnoseReport @dataclass(frozen=True) @@ -147,7 +148,7 @@ def _summarize_stats(report: Any) -> list[dict[str, Any]]: def _current_report(loop: Any, state: RunState) -> "AutoDiagnoseReport": """Snapshot the run so far into the same report shape run_m5/run_fix expect.""" - from evalrx.eval_agent.loop_reports import AutoDiagnoseReport + from evalrx.eval_agent.loop.report import AutoDiagnoseReport verified = loop.hypothesis_tester.best_hypotheses(state.all_test_results) return AutoDiagnoseReport( @@ -258,7 +259,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: f"({_MAX_UNNAMED_PROBE_RUNS}); name the probes to run (see list_probes)", error="max_calls", ) - probe_results, artifact_pngs = loop._do_m1( + probe_results, artifact_pngs = state.stages.probe( state.cycle, state.data, state.all_hypotheses, state.timings ) if not probe_results: @@ -293,7 +294,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: call_params[name] = args names = list(dict.fromkeys(names)) try: - probe_results, artifact_pngs = loop._do_m1( + probe_results, artifact_pngs = state.stages.probe( state.cycle, state.data, state.all_hypotheses, state.timings, analyzers=names, analyzer_params=call_params or None, ) @@ -319,7 +320,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: def _run_stats(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: confirmatory = bool(params.get("confirmatory", True)) - stats_report = loop._do_m2( + stats_report = state.stages.analyze( state.cycle, state.probe_results, state.data, state.artifact_pngs, state.timings, confirmatory=confirmatory, ) @@ -344,7 +345,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: or "Explore this dataset and surface the patterns that matter." ) # Reuse host adjudication, artifact capture, and M3 context publication. - report = loop._do_explore( + report = state.stages.explore( state.cycle, state.probe_results, state.data, state.timings, question=question, ) if report is None: @@ -422,7 +423,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: def _propose_hypotheses(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: - diag = loop._do_m3( + diag = state.stages.diagnose( state.cycle, state.stats_report, state.prior_cycles, state.timings, failure_modes=state.failure_modes, cases=state.data, ) @@ -456,9 +457,9 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return ToolOutcome( False, "no untested hypotheses — call propose_hypotheses first", error="empty" ) - loop._finalize_confirmatory_stats(state.stats_report) + finalize_confirmatory_stats(state.stats_report) board.stats_confirmatory = True - test_results = loop._do_m4( + test_results = state.stages.test_hypotheses( state.cycle, state.pending_hypotheses, state.stats_report, state.data, state.timings ) for tr in test_results: diff --git a/evalrx/eval_agent/run_metadata.py b/evalrx/eval_agent/loop/metadata.py similarity index 98% rename from evalrx/eval_agent/run_metadata.py rename to evalrx/eval_agent/loop/metadata.py index f9722c55..370c1019 100644 --- a/evalrx/eval_agent/run_metadata.py +++ b/evalrx/eval_agent/loop/metadata.py @@ -1,5 +1,5 @@ """Shared run-provenance and logging-wiring helpers used by both -``VLDiagnoseLoop`` (loop.py) and its ``JudgePolicy`` (agentic/policy.py). +``VLDiagnoseLoop`` (loop/diagnose.py) and its ``JudgePolicy`` (loop/judge/policy.py). """ from __future__ import annotations diff --git a/evalrx/eval_agent/loop/partition.py b/evalrx/eval_agent/loop/partition.py new file mode 100644 index 00000000..f9ffbc62 --- /dev/null +++ b/evalrx/eval_agent/loop/partition.py @@ -0,0 +1,88 @@ +"""How a batch is divided into EXPLORE / CONFIRM / TEST partitions. + +The single source of truth: every stage re-derives the identical partition +from the same input batch, so M1-M3 never see the cases M4 and the fix stage +are measured on. +""" + +from __future__ import annotations + +import random +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from evalrx.core.case import CaseBatch + + +def split_cases( + data: "CaseBatch", *, confirm_split: float, test_split: float = 0.0, seed: int = 0, +) -> "tuple[CaseBatch, CaseBatch | None, CaseBatch | None]": + """Deterministic, stratified (explore, confirm, test) partition. + + The single source of truth for how a batch is divided; every stage + re-derives the identical partition from the same input batch. When + ``confirm_split <= 0`` (or the batch is too small to split), returns + ``(data, None, None)`` — a no-op, so existing runs are byte-for-byte + unchanged. When ``test_split <= 0`` the third element is ``None`` (the + two-way explore/confirm behaviour). With both fractions set, CONFIRM is + drawn first (same seed as the two-way split), then TEST from the + remainder (seed+1); EXPLORE is what is left. + """ + from evalrx.core.case import CaseBatch + from evalrx.stats.subset_sampling import stratified_subset + + cases = list(data) + frac = confirm_split + if frac <= 0.0 or len(cases) < 4: + return data, None, None + n_confirm = round(len(cases) * frac) + if n_confirm <= 0 or n_confirm >= len(cases): + return data, None, None + three_way = test_split > 0.0 + confirm = stratified_subset(cases, _strat_key, n_confirm, + seed=seed) + if three_way: + # ``stratified_subset`` guarantees at MOST n (per-stratum rounding + # can under-allocate by one or two); the train/val/test mode + # promises exact counts, so top the draw up deterministically. + # The two-way path is left untouched — byte-for-byte reproducible. + confirm = _exact_size(confirm, cases, n_confirm, + seed) + confirm_ids = {id(c) for c in confirm} + rest = [c for c in cases if id(c) not in confirm_ids] + if not three_way: + return CaseBatch(rest), CaseBatch(confirm), None + n_test = round(len(cases) * test_split) + if n_test <= 0 or n_test >= len(rest): + return CaseBatch(rest), CaseBatch(confirm), None + test = stratified_subset(rest, _strat_key, n_test, + seed=seed + 1) + test = _exact_size(test, rest, n_test, seed + 1) + test_ids = {id(c) for c in test} + explore = [c for c in rest if id(c) not in test_ids] + return CaseBatch(explore), CaseBatch(confirm), CaseBatch(test) + + +def _strat_key(case: "Any") -> "tuple": + """Stratify the explore/confirm split by label + probe_type when present + (keeps the no-free-lunch control mix, e.g. present-detections, in both + partitions). Falls back to label alone for generic batches.""" + label = getattr(getattr(case, "label", None), "value", "?") + probe = (getattr(case, "metadata", {}) or {}).get("probe_type") + return (label, probe) + + +def _exact_size(picked: "list", pool: "list", n: int, seed: int) -> "list": + """Top a stratified draw up to exactly *n* items, deterministically. + + :func:`~evalrx.stats.subset_sampling.stratified_subset` returns at most + *n* items but per-stratum rounding can under-allocate by one or two; the + train/val/test split promises exact 1:1:1 counts, so the shortfall is + filled from a seeded shuffle of the untaken remainder of *pool*. + """ + if len(picked) >= n: + return picked[:n] + picked_ids = {id(c) for c in picked} + leftover = [c for c in pool if id(c) not in picked_ids] + random.Random(seed + 7919).shuffle(leftover) + return picked + leftover[: n - len(picked)] diff --git a/evalrx/eval_agent/loop_reports.py b/evalrx/eval_agent/loop/report.py similarity index 96% rename from evalrx/eval_agent/loop_reports.py rename to evalrx/eval_agent/loop/report.py index 23716f68..7ce8deb4 100644 --- a/evalrx/eval_agent/loop_reports.py +++ b/evalrx/eval_agent/loop/report.py @@ -30,8 +30,8 @@ @dataclass class AutoDiagnoseReport: """Summary returned by every diagnosis loop: - :class:`~evalrx.eval_agent.loop.VLDiagnoseLoop.run` and - :meth:`~evalrx.eval_agent.agentic.JudgePolicy.run` both return + :class:`~evalrx.eval_agent.loop.diagnose.VLDiagnoseLoop.run` and + :meth:`~evalrx.eval_agent.loop.judge.JudgePolicy.run` both return this one class. Every field below is populated by both loops except where noted "M4-only", which stay at their default (``None`` / empty) when the producing loop has no equivalent concept. diff --git a/evalrx/eval_agent/loop/stages.py b/evalrx/eval_agent/loop/stages.py new file mode 100644 index 00000000..faaa3ecd --- /dev/null +++ b/evalrx/eval_agent/loop/stages.py @@ -0,0 +1,621 @@ +"""The stages of a diagnosis run: M1 probe, explore, M2 stats, M3 diagnosis, M4 test. + +:class:`Stages` runs one stage at a time and records it (run log, contract +payloads, timings). It holds the stage dependencies only — the model, the +protocol, the agents, the store, the logger — never the loop; the loop builds +one per run (:meth:`~evalrx.eval_agent.loop.diagnose.VLDiagnoseLoop.stages`) +and a policy decides which stage runs next. :class:`StageMemory` is what +outlives one run on the same loop (the explorer notes M3 and the fix stage +read, the default M3 agent, the token count). +""" + +from __future__ import annotations + +import logging +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from evalrx.eval_agent.loop.metadata import ( + _log_generated_tools, + _make_intervention_result_from_test, +) + +if TYPE_CHECKING: + from collections.abc import Mapping + + from evalrx.eval_agent.store import Store + +logger = logging.getLogger(__name__) + + +@dataclass +class StageMemory: + """What outlives one run on the same loop.""" + + #: Explorer notes M3 is shown: a Step-1 ``explore_report`` or the latest + #: in-cycle explore step. The fix stage reads it too. + explore_context: Any = None + #: The default DiagnosisAgent, once built (when none was configured). + diagnosis_agent: Any = None + #: Judge tokens spent in the current run (reset at each run's start). + tokens_used: int = 0 + + +@dataclass +class Stages: + """Runs and records one stage at a time. Built by the loop for each run.""" + + model: Any + protocol: Any + probe_agent: Any + stats_agent: Any + hypothesis_tester: Any + store: "Store" + run_logger: Any + emitter: Any + memory: StageMemory + diagnosis_agent: Any = None + diagnosis_retries: int = 0 + explorer: Any = None + explore_dir: "Path | None" = None + explore_question: str = "" + signal_recipes: list[Any] = field(default_factory=list) + bridge_analyzer_name: str = "explored" + + def _emit(self, name: str, build: "Any") -> None: + """Emit one stage payload; never raises into the pipeline.""" + if self.emitter is not None: + self.emitter.emit(name, build) + + def bridge_signals(self, probe_results: "dict[str, Any]", data: "Any | None") -> None: + """Compile pre-registered signal recipes into a synthetic analyzer Result + and inject it into *probe_results* so M2/M3/M4 see the bridged composite + signals through the standard findings["per_case"] contract. No-op when no + recipes are configured. Never raises into the loop.""" + if not self.signal_recipes: + return + # Never silently overwrite a real analyzer that already used this key. + name = self.bridge_analyzer_name + if name in probe_results: + base, n = name, 1 + while name in probe_results: + name, n = f"{base}_bridge{n}", n + 1 + logger.warning( + "bridge analyzer name %r collides with a real analyzer; " + "injecting under %r instead", base, name, + ) + try: + from evalrx.analysis.operationalize import bridge_recipes_to_result + + synth = bridge_recipes_to_result( + self.signal_recipes, probe_results, data, + model_repr=repr(self.model), + analyzer_name=name, + ) + except Exception as exc: # bridging must never sink the loop + logger.warning("signal bridge failed: %s", exc) + return + if synth is None: + return + probe_results[name] = synth + self.store.add_result(synth) + # The bridged signals ARE the discovered candidates — they must be tested, + # not optional. The plan caps at the stats agent's max_signal_tools and + # appends bridged signals LAST, so a low cap silently drops them. Raise the + # cap to cover the expanded family (more multiplicity = more conservative, + # never less — e-BH still controls FDR over whatever is tested). + agent = getattr(self, "stats_agent", None) + if agent is not None and hasattr(agent, "_max_signal_tools"): + try: + from evalrx.analysis.stats_tools import build_stats_input + + n_signals = len(build_stats_input(probe_results, data).per_case) + current = getattr(agent, "_max_signal_tools", None) + if current is not None: + agent._max_signal_tools = max(int(current), n_signals) + except Exception as exc: # never let the cap-bump break the loop + logger.debug("bridge: could not raise stats signal cap: %s", exc) + logger.info( + "bridged %d signal row(s) into M2 as analyzer %r", + len(synth.findings.get("per_case", [])), name, + ) + + def diagnosis_agent_or_default(self) -> "Any": + """M3's agent: the configured one, else a default DiagnosisAgent built once + per loop (built lazily: DiagnosisAgent() raises without its judge's + credentials even when M3 never runs).""" + if self.diagnosis_agent is not None: + return self.diagnosis_agent + if self.memory.diagnosis_agent is None: + from evalrx.eval_agent.stages.diagnosis import DiagnosisAgent + + self.memory.diagnosis_agent = DiagnosisAgent() + return self.memory.diagnosis_agent + + def probe( + self, cycle: int, data: "Any", all_hypotheses: "list[Any]", + timings: "dict[str, float]", *, log: bool = True, + analyzers: "list[str] | None" = None, + analyzer_params: "dict[str, dict[str, Any]] | None" = None, + ) -> "tuple[dict[str, Any], list]": + """M1: protocol-guided probing + signal bridge. + + Returns ``(probe_results, artifact_pngs)``; ``probe_results`` is empty + when M1 produced nothing (caller decides whether to stop). When + ``log`` is False the probe events are not written — used by + :meth:`run_confirm` when it only needs to regenerate the stats the + tester reads (M1/M2 already belong to the analysis phase's log). + + ``analyzers`` / ``analyzer_params`` name the probes and their arguments + explicitly, bypassing selection (see :meth:`ProbeAgent.probe`); the + agentic loop's ``run_probe`` tool passes them through.""" + prior_modes = list(dict.fromkeys( + h.predicted_failure_mode for h in all_hypotheses + if getattr(h, "predicted_failure_mode", None) + )) + # Named calls run exactly what was named (no cap, no backfill). + named: dict[str, Any] = {"analyzers": analyzers, "exact": True} if analyzers is not None else {} + if analyzer_params: + named["analyzer_params"] = analyzer_params + _t0 = time.monotonic() + probe_results = self.probe_agent.probe( + self.model, + data, + protocol=self.protocol, + prior_hypotheses=all_hypotheses or None, + hint_failure_modes=prior_modes or None, + **named, + ) + _dt = time.monotonic() - _t0 + timings["m1"] = timings.get("m1", 0.0) + _dt + artifact_pngs: list = [] + if log and self.run_logger: + artifact_pngs = self.run_logger.log_probe( + cycle, probe_results, schema=self.probe_agent.last_schema, + cases=data, + judge_prompt=getattr(self.probe_agent, "last_selection_prompt", ""), + judge_raw=getattr(self.probe_agent, "last_selection_raw", ""), + duration_sec=_dt, + ) or [] + _log_generated_tools(self.run_logger, cycle, "m1_probe", self.probe_agent) + self._emit_m1(cycle, probe_results, data, _dt) + if not probe_results: + return {}, [] + for r in probe_results.values(): + self.store.add_result(r) + # Operationalization bridge: pre-registered recipes -> synthetic + # "explored" analyzer Result (no-op when none configured). + self.bridge_signals(probe_results, data) + return probe_results, artifact_pngs + + def _emit_m1(self, cycle: int, probe_results: "dict[str, Any]", data: "Any", + duration_sec: float) -> None: + """Emit M1's ProbeOutput, including how analyzer routing was decided. + + The three modality sets are recorded separately because they can differ + and the difference is the diagnosis: an omni model on an audio benchmark + declares four modalities, fills one, and is routed on one. + """ + if self.emitter is None: + return + from evalrx.contract.emit import from_probe_results + from evalrx.core.case import probed_modalities + + selector = self.probe_agent.selector if hasattr(self.probe_agent, "selector") else None + declared = sorted(getattr(self.model, "modalities", frozenset({"text"})) or {"text"}) + probed = sorted(probed_modalities(data)) + routed = sorted( + selector.routed_slots(self.model, data) if selector is not None else probed + ) + # Trajectories in the batch, not declared TOOL_CALLS: the api backend + # reports tool_calls for every chat model, which made a single-turn text + # run record itself as an agent run. + from evalrx.eval_agent.stages.probe import _carries_trajectories + + is_agent = bool(data is not None and _carries_trajectories(data)) + self._emit(f"c{cycle}.m1", lambda: from_probe_results( + probe_results, + trace_id=self.emitter.trace_id, cycle=cycle, model=self.model, + model_modalities=declared, probed_modalities=probed, routed_on=routed, + is_agent=is_agent, + selector="llm_judge" if getattr(self.probe_agent, "judge", None) else "static_strategy", + generated=list(getattr(self.probe_agent, "generated_probes", []) or []), + failed_analyzers=dict(getattr(self.probe_agent, "_failed_analyzers", {}) or {}), + duration_sec=duration_sec, + )) + + def explore_out_dir(self) -> "Path | None": + """Where the explore step persists its report/tables/figures. + + Explicit ``explore_dir`` wins. Otherwise it is derived from the run + logger so the files land INSIDE the run, beside the log, where the + report reader looks (``reporting.run_data``: ``/explore``, else a + sibling ``explore/``): + + - a :class:`~evalrx.eval_agent.runlog.context.RunContext`-backed logger + → ``ctx.explore_dir``, an ephemeral tree under ``ctx.runtime_root`` + (captured into ``M2/log.json`` and deleted at ``finalize()``; + writing straight to ``/explore`` would leak real files + outside the JSON-only run artifact); + - a standalone ``RunLogger("/logs")`` / ``logs_confirm`` … → + ``/explore`` (a sibling of the ``logs*/`` dir, the llm_benchmark + layout — under the log dir it would be two levels down for a + ``logs_confirm/`` carrier log and the report would miss it); + - any other standalone run dir → ``/explore``. + + ``None`` (nothing persisted, context in memory only) without a logger.""" + if self.explore_dir is not None: + return self.explore_dir + if self.run_logger is None: + return None + ctx = getattr(self.run_logger, "_context", None) + if ctx is not None and hasattr(ctx, "explore_dir"): + return ctx.explore_dir + run_dir = getattr(self.run_logger, "run_dir", None) + if run_dir is None: + return None + run_dir = Path(run_dir) + if run_dir.name.startswith("logs"): + return run_dir.parent / "explore" + return run_dir / "explore" + + def explore( + self, cycle: int, probe_results: "dict[str, Any]", data: "Any", + timings: "dict[str, float]", *, log: bool = True, question: str | None = None, + ) -> "Any | None": + """Optional in-cycle explore step: free-form EDA over M1's per-case table. + + Runs between M1 and M2 when an ``explorer`` is configured. The explorer + sees exactly what M2 sees — ``build_stats_input`` → ``per_case_to_records`` + (M1 analyzer per-case signals + PASS/FAIL labels) — writes tables and + chart specs, and the host renders the charts. The result feeds: + + - M3, as an :class:`~evalrx.eval_agent.stages.diagnosis.ExploreContext` + (observations / rendered charts / caveats — descriptive, UNCONFIRMED, + used only to decide WHICH hypotheses to propose); + - the report, via ``exploratory_report.json`` + ``tables/`` + + ``figures/`` under :meth:`explore_out_dir` (one directory, rewritten + each cycle — it always holds what the *latest* M3 was shown; the + per-cycle ``explore`` run-log events keep every cycle's counts and + observations). + + It never touches M2's confirmatory family, M4, or the fix gate: the + explorer's candidate-signal verdicts are host-adjudicated IN-SAMPLE + (labelled so) and dropped from the M3 context by construction. Held-out + confirmation of explorer recipes is the fused pipeline's job, not this + step's. Best-effort: any failure logs a warning and returns ``None`` — + an explorer outage must not cost the M2/M3 that already have their data. + + Returns the explorer report (or ``None``).""" + if self.explorer is None: + return None + from evalrx.analysis.operationalize import per_case_to_records + from evalrx.analysis.stats_tools import build_stats_input + from evalrx.eval_agent.stages.diagnosis import ExploreContext + + _t0 = time.monotonic() + report: Any = None + out_dir = self.explore_out_dir() + try: + inp = build_stats_input(probe_results, data) + records = per_case_to_records(inp.per_case, inp.labels) + if not records: + logger.info("explore: M1 produced no per-case signals — skipping.") + return None + question = question or self.explore_question + if not question: + from evalrx.eval_agent.prompts.explore_step import default_explore_question + + question = default_explore_question(self.protocol) + report = self.explorer.explore_records( + records, question=question, outcome_col="label", + ) + # Host firewall: recompute every candidate verdict from sufficient + # statistics with the M2 core (in-sample here — labelled as such so + # nothing downstream mistakes it for a held-out result). + try: + from evalrx.analysis.adjudicate import adjudicate_report + + adjudicate_report(report, split_label="in_sample") + except Exception as exc: # adjudication is a verdict layer, not the data + logger.warning("explore: host adjudication failed: %s", exc) + if out_dir is not None: + from evalrx.analysis.explore_run import write_report_artifacts + + # Renders chart specs from the copied tables/ CSVs, so the + # persisted report carries each chart's absolute figure_path — + # the PNGs M3 is shown and the report displays. + write_report_artifacts(report, out_dir) + ctx = ExploreContext.from_report( + report.to_dict() if hasattr(report, "to_dict") else None + ) + if ctx is not None: + ctx.source = "loop_explorer" + self.memory.explore_context = ctx + elif getattr(report, "ok", False): + logger.info("explore: report carried no observations/charts — " + "M3 keeps its previous explore context.") + except Exception as exc: # the explorer must never sink the loop + logger.warning( + "explore step failed at cycle %d (%s) — M2/M3 continue without " + "explorer notes.", cycle, exc, + ) + _dt = time.monotonic() - _t0 + timings["explore"] = timings.get("explore", 0.0) + _dt + if log and self.run_logger is not None: + try: + self.run_logger.log_explore( + cycle, report, out_dir=out_dir, duration_sec=_dt, + ) + except Exception as exc: # logging must never break the run + logger.warning("explore: could not log the explore event: %s", exc) + return report + + def analyze( + self, cycle: int, probe_results: "dict[str, Any]", data: "Any", + artifact_pngs: "list", timings: "dict[str, float]", *, log: bool = True, + confirmatory: bool = True, + ) -> "Any": + """M2: protocol-aware rigorous stats analysis (effect sizes + charts). + + ``confirmatory=False`` defers the e-BH validity verdict (the analysis + phase shows distributions only); the confirm phase recomputes it.""" + _t0 = time.monotonic() + stats_report = self.stats_agent.analyze( + probe_results, + model_name=repr(self.model), + protocol=self.protocol, + data=data, + extra_figures=artifact_pngs, + confirmatory=confirmatory, + ) + _dt = time.monotonic() - _t0 + timings["m2"] = timings.get("m2", 0.0) + _dt + if log and self.run_logger: + self.run_logger.log_analysis(cycle, stats_report, duration_sec=_dt) + _log_generated_tools(self.run_logger, cycle, "m2_stats", self.stats_agent) + if self.emitter is not None: + from evalrx.contract.emit import from_stats_report + + self._emit(f"c{cycle}.m2", lambda: from_stats_report( + stats_report, trace_id=self.emitter.trace_id, cycle=cycle, + raw_results_ref=f"contract/c{cycle}.m1.json", duration_sec=_dt, + )) + return stats_report + + def diagnose( + self, cycle: int, stats_report: "Any", prior_cycles: "list[Any]", + timings: "dict[str, float]", *, log: bool = True, + failure_modes: "Any | None" = None, cases: "Any | None" = None, + ) -> "Any | None": + """M3: hypothesis generation. Returns the diagnosis result, or ``None`` + when M3 could not run (judge unavailable / timeout / quota) — the caller + stops gracefully on ``None`` (regression guard: an M3 timeout must not + kill the whole run after M1+M2 succeeded). Also accrues token usage. + + ``failure_modes`` (optional clustered ``FailureModeReport``) is passed + through to the diagnosis agent only when it accepts the parameter — + ``None`` (the default, always the case for ``VLDiagnoseLoop``) adds + nothing to the prompt and costs no extra call.""" + _t0 = time.monotonic() + for attempt in range(self.diagnosis_retries + 1): + try: + diag_agent = self.diagnosis_agent_or_default() + diag = _diagnose_with_optional_context( + diag_agent, stats_report, prior_cycles, self.memory.explore_context, + failure_modes, cases=cases, + ) + break + except Exception as exc: + retrying = attempt < self.diagnosis_retries + error = f"{type(exc).__name__}: {exc}" + logger.warning("M3 attempt %d failed (%s); retrying=%s", + attempt + 1, error, retrying) + if self.run_logger is not None: + # A JudgeError carries what the judge was asked and answered. + for call in (e.record() for e in getattr(exc, "exchanges", ())): + self.run_logger.log_model_exchange( + "M3", cycle=cycle, role=call["role"], operation=call["operation"], + inputs=call["inputs"], output=call["output"], error=call["error"], + duration_sec=call["duration_sec"], metadata=call["metadata"], + ) + self.run_logger.log_model_exchange( + stage="M3", cycle=cycle, role="diagnosis", operation="diagnose", + inputs=None, output=None, error=error, + metadata={"attempt": attempt + 1, "retrying": retrying}, + duration_sec=time.monotonic() - _t0, + ) + if not retrying: + timings["m3"] = timings.get("m3", 0.0) + time.monotonic() - _t0 + return None + _dt = time.monotonic() - _t0 + timings["m3"] = timings.get("m3", 0.0) + _dt + + _tok = getattr(diag, "tokens_used", None) + if _tok is None: + _tok = max(1, len(diag.raw_judge_output) // 4) + self.memory.tokens_used += _tok + + if log and self.run_logger: + # Log only the figures that actually existed (the same existence + # filter M3 applies) so the audit trail reflects what the judge saw. + _explore_figs = None + if self.memory.explore_context is not None: + from pathlib import Path as _P + + _explore_figs = [ + f for f in self.memory.explore_context.figure_paths if _P(f).exists() + ] + self.run_logger.log_diagnosis( + cycle, diag, duration_sec=_dt, explore_figures=_explore_figs or None + ) + if self.emitter is not None: + from evalrx.contract.emit import from_diagnosis + + self._emit(f"c{cycle}.m3", lambda: from_diagnosis( + diag, trace_id=self.emitter.trace_id, cycle=cycle, duration_sec=_dt, + )) + return diag + + def test_hypotheses( + self, cycle: int, hypotheses: "list[Any]", stats_report: "Any", + data: "Any", timings: "dict[str, float]", *, log: bool = True, + split_label: "str | None" = None, + ) -> "list[Any]": + """M4: statistical test + protocol consistency for each hypothesis, + writing the verdict back onto ``hypothesis.status``. + + ``split_label`` tags each result's evidence with which data split the + test read (``"confirm_holdout"`` for the held-out pass) BEFORE the + result is logged, so the marker reaches the run log too.""" + _t0 = time.monotonic() + test_results = self.hypothesis_tester.test( + hypotheses, + stats_report, + data, + protocol=self.protocol, + ) + _dt = time.monotonic() - _t0 + timings["m4"] = timings.get("m4", 0.0) + _dt + for tr in test_results: + tr.hypothesis.status = tr.status + if split_label and isinstance(getattr(tr, "evidence", None), dict): + tr.evidence["split"] = split_label + if log and self.run_logger: + # M4 results are logged through the surgery slot. + for tr in test_results: + _iv = _make_intervention_result_from_test(tr) + self.run_logger.log_surgery( + cycle, tr.hypothesis, _iv, duration_sec=_dt, + validation_cases=data, + judge_prompt=getattr(tr, "judge_prompt", None) or None, + judge_raw=getattr(tr, "judge_raw", None) or None, + ) + if log and self.emitter is not None: + from evalrx.contract.emit import from_test_results + + # M4 has no stage log of its own — it reuses the per-hypothesis + # surgery slot — so this is the first place the whole verdict set + # exists as one object a reader can load. + split = "confirm" if split_label == "confirm_holdout" else "explore" + self._emit(f"c{cycle}.m4", lambda: from_test_results( + test_results, trace_id=self.emitter.trace_id, cycle=cycle, + split=split, duration_sec=_dt, + stopping_criteria_met=bool( + self.hypothesis_tester.stopping_criteria_met(test_results, self.protocol) + ), + )) + return test_results + + def test_on_holdout( + self, + hypotheses: "list[Any]", + confirm: "Any", + analyzer_names: "list[str]", + timings: "dict[str, float]", + ) -> "tuple[list[Any], str]": + """The M4 pass — on the held-out confirm split. + + With a confirm split in play this is the ONLY hypothesis test: M3's + hypotheses are taken straight to data M1/M2/M3 never mined. The same + analyzers as the last explore cycle are re-run on the confirm split + (pinned via ``ProbeAgent.probe(analyzers=)`` — a fresh judge selection + could miss the designated signals); with no names to pin (a reloaded + run without a stats report) the probe agent selects normally. + + Returns ``(test_results, status)`` with status ``"confirmed"`` (the + pass ran) or ``"failed"`` (the confirm re-probe produced nothing — no + hypothesis can be verified this run). + """ + pinned = [n for n in analyzer_names if not n.startswith("generated:")] + logger.info( + "M4 (held-out): testing %d hypothesis(es) on the %d-case confirm " + "split (analyzers: %s)", + len(hypotheses), len(list(confirm)), + ", ".join(pinned) or "", + ) + # Stamped BEFORE probe() (not just before log_probe below): ProbeAgent + # tags every model call it makes with whatever current_cycle reads AT + # CALL TIME, and probe() is where those calls happen. Setting this + # only right before log_probe(-1, ...) tagged this whole confirm-split + # re-probe's model calls with the previous explore cycle's number. + if self.run_logger: + self.run_logger.current_cycle = -1 + _t0 = time.monotonic() + if pinned: + probe_results = self.probe_agent.probe( + self.model, confirm, protocol=self.protocol, + prior_hypotheses=hypotheses or None, analyzers=pinned, + ) + else: + probe_results = self.probe_agent.probe( + self.model, confirm, protocol=self.protocol, + prior_hypotheses=hypotheses or None, + ) + timings["m4_holdout_m1"] = timings.get("m4_holdout_m1", 0.0) + ( + time.monotonic() - _t0) + if not probe_results: + logger.warning( + "M4 (held-out): the confirm-split re-probe produced no results " + "— no hypothesis can be verified this run." + ) + return [], "failed" + self.bridge_signals(probe_results, confirm) + if self.run_logger: + self.run_logger.log_probe( + -1, probe_results, + schema=getattr(self.probe_agent, "last_schema", None), + cases=confirm, + ) + stats_confirm = self.analyze( + -1, probe_results, confirm, [], timings, confirmatory=True + ) + results = self.test_hypotheses(-1, hypotheses, stats_confirm, confirm, timings, + split_label="confirm_holdout") + return results, "confirmed" + + +def finalize_confirmatory_stats(stats_report: "Any") -> None: + """Promote a descriptive (analysis-phase) stats report to confirmatory. + + The analysis phase runs M2 with the e-BH validity verdict DEFERRED + (``descriptive_only=True``). The confirm phase recomputes e-BH FDR + correction over the report's stats results so M4 and the report see + the family-level reject decision. No-op when already confirmatory.""" + if stats_report is None: + return + corr = getattr(stats_report, "corrected_rejections", None) or {} + if getattr(stats_report, "descriptive_only", False) or corr.get("deferred"): + from evalrx.analysis.stats_tools import fdr_correct + + stats_report.corrected_rejections = fdr_correct( + list(getattr(stats_report, "stats_results", None) or []) + ) + stats_report.descriptive_only = False + + +def _diagnose_with_optional_context( + diag_agent: "Any", stats_report: "Any", prior_cycles: "Any", explore_context: "Any | None", + failure_modes: "Any | None" = None, cases: "Any | None" = None, +) -> "Any": + """Call ``diag_agent.diagnose`` passing ``explore_context``/``failure_modes``/ + ``cases`` only when the agent accepts them, so custom/legacy diagnosis + agents keep working unchanged. ``cases`` (the explore-split batch M1/M2 + ran on) only feeds the critic's label summary -- never the proposer.""" + import inspect as _inspect + + kwargs: dict[str, Any] = {"prior_cycles": prior_cycles or None} + optional = {"explore_context": explore_context, "failure_modes": failure_modes, + "cases": cases} + if any(v is not None for v in optional.values()): + params: "Mapping[str, _inspect.Parameter]" + try: + params = _inspect.signature(diag_agent.diagnose).parameters + except (TypeError, ValueError): + params = {} + for name, value in optional.items(): + if value is not None and name in params: + kwargs[name] = value + return diag_agent.diagnose(stats_report, **kwargs) diff --git a/evalrx/eval_agent/loop/state.py b/evalrx/eval_agent/loop/state.py new file mode 100644 index 00000000..7f739c27 --- /dev/null +++ b/evalrx/eval_agent/loop/state.py @@ -0,0 +1,68 @@ +"""What a diagnosis run carries between steps, whichever policy drives it. + +:class:`Policy` is the contract every next-step policy meets +(:class:`~evalrx.eval_agent.loop.fixed.FixedOrderPolicy`, +:class:`~evalrx.eval_agent.loop.judge.policy.JudgePolicy`); :class:`RunState` +is the bookkeeping they share. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Protocol + +if TYPE_CHECKING: + from evalrx.core.case import CaseBatch + from evalrx.eval_agent.loop.diagnose import VLDiagnoseLoop + from evalrx.eval_agent.loop.report import AutoDiagnoseReport + from evalrx.eval_agent.loop.stages import Stages + + +class Policy(Protocol): + def run(self, loop: "VLDiagnoseLoop", data: "CaseBatch", + timings: dict[str, float]) -> "AutoDiagnoseReport": ... + + +@dataclass +class RunState: + """What one run accumulates, whichever policy drives it.""" + + original_data: Any + data: Any + #: The stages this run calls (:meth:`VLDiagnoseLoop.stages`). + stages: "Stages" + timings: dict[str, float] = field(default_factory=dict) + cycle: int = 0 + all_hypotheses: list[Any] = field(default_factory=list) + all_test_results: list[Any] = field(default_factory=list) + #: Each finished cycle's summary, M3's context for the next one. + prior_cycles: list[dict[str, Any]] = field(default_factory=list) + stats_report: Any = None + diagnosis_failed: bool = False + #: The last M1's analyzers — what the held-out M4 pass re-runs. + analyzer_names: list[str] = field(default_factory=list) + # Judge-decided runs only: the decision judge and the tools' working state. + judge: Any = None + pending_hypotheses: list[Any] = field(default_factory=list) + probe_results: dict[str, Any] = field(default_factory=dict) + artifact_pngs: list[Any] = field(default_factory=list) + failure_modes: Any = None + probe_search_result: Any = None + surgery_outcome: Any = None + fix_outcome: Any = None + + +def cycle_summary(cycle: int, stats_report: Any, hypotheses: list) -> dict[str, Any]: + """One finished cycle as the next M3 call sees it.""" + return { + "cycle": cycle, + "severity": getattr(stats_report, "severity", "none"), + "hypotheses": [ + { + "statement": h.statement, + "failure_mode": h.predicted_failure_mode, + "status": h.status.value if h.status else "pending", + } + for h in hypotheses + ], + } diff --git a/evalrx/eval_agent/prompts/fix_agent.py b/evalrx/eval_agent/prompts/fix_agent.py index 40d8ce6d..2dd6fdb9 100644 --- a/evalrx/eval_agent/prompts/fix_agent.py +++ b/evalrx/eval_agent/prompts/fix_agent.py @@ -122,10 +122,12 @@ baseline_output, costs nothing and does not count. Branch on outputs within that budget — e.g. describe first, then decide; vote over independent variants. -- model_generate is thread-safe and concurrent calls are serviced in - parallel: fan out over CASES with concurrent.futures.ThreadPoolExecutor - (max_workers=8) — a serial loop over every case x several calls is slow and - risks the wall-clock limit. +- model_generate is thread-safe, and the host answers the calls that are + waiting at the same moment as ONE batch. Fan out over CASES with + concurrent.futures.ThreadPoolExecutor(max_workers=len(cases)) — one worker + per case, each making its own calls in order. A serial loop over every + case x several calls gets a batch of one each time: many times slower, and + it risks the wall-clock limit. - SELECTION RULE (enforced by the host, without labels): for each case the host anchors on baseline_output (or on your plain direct call when a case has no record). Your final "output" may differ from that anchor only when diff --git a/evalrx/eval_agent/prompts/probe_generator.py b/evalrx/eval_agent/prompts/probe_generator.py index 5bd82ca5..c6da7473 100644 --- a/evalrx/eval_agent/prompts/probe_generator.py +++ b/evalrx/eval_agent/prompts/probe_generator.py @@ -23,6 +23,9 @@ REQUIREMENTS: - Read "{input_filename}" from the current directory; do NOT hardcode the data. + The file is already there and holds the real cases: look at it to see what + the outputs are like, and never overwrite, move or delete it. To try the + script on cases you make up, put them in a file with another name. - Compute, per case, a numeric or boolean signal for the failure pattern above (e.g. 1 if the output refuses / drifts language / breaks format, else 0). - Standard library + `import numpy` only. No network, no file writes, no model calls. diff --git a/evalrx/eval_agent/prompts/whitebox_probe_generator.py b/evalrx/eval_agent/prompts/whitebox_probe_generator.py index 12ad7bb4..234cb0a1 100644 --- a/evalrx/eval_agent/prompts/whitebox_probe_generator.py +++ b/evalrx/eval_agent/prompts/whitebox_probe_generator.py @@ -25,6 +25,8 @@ contains "im_start", "image_pad", "vision"). REQUIREMENTS: +- The files above are already there and hold the real captures: never + overwrite, move or delete them. - numpy only (`import numpy as np`); no network, no other file writes. - Compute ONE per-case numeric signal for the mechanism above (e.g. attention mass on structural tokens, image-vs-text attention ratio at a layer, diff --git a/evalrx/eval_agent/RUN_LOGGER.md b/evalrx/eval_agent/runlog/README.md similarity index 99% rename from evalrx/eval_agent/RUN_LOGGER.md rename to evalrx/eval_agent/runlog/README.md index 8c03735f..59432dd4 100644 --- a/evalrx/eval_agent/RUN_LOGGER.md +++ b/evalrx/eval_agent/runlog/README.md @@ -136,7 +136,7 @@ Most events know their stage (`log_probe` is M1, `log_analysis` is M2). `log_surgery` is not tag-based: an intervention result whose evidence carries `m4_test_name` is a hypothesis verification (M4), anything else an intervention -(M5). `run_metadata.py` is where `m4_test_name` is set. +(M5). `loop/metadata.py` is where `m4_test_name` is set. ## Durability: why every event rewrites its document diff --git a/evalrx/eval_agent/runlog/__init__.py b/evalrx/eval_agent/runlog/__init__.py new file mode 100644 index 00000000..0887ee18 --- /dev/null +++ b/evalrx/eval_agent/runlog/__init__.py @@ -0,0 +1,11 @@ +"""A run's output directory and event log (see README.md in this folder). + + context.py RunContext, Trial — the one owner of a run's directory + logger.py RunLogger — run.json + per-stage M/log.json + entries.py what each logged event records + files.py atomic writes, inlined workspaces, saved .npy artifacts + tracing.py the run log mirrored into Langfuse + schema.py the published run_log JSON Schema (run_log.schema.json) + narration.py the live terminal narration of a run + instrumentation.py InstrumentedModel — logs each call an analyzer makes to the model +""" diff --git a/evalrx/eval_agent/run_context.py b/evalrx/eval_agent/runlog/context.py similarity index 97% rename from evalrx/eval_agent/run_context.py rename to evalrx/eval_agent/runlog/context.py index ccdbad41..b54fab95 100755 --- a/evalrx/eval_agent/run_context.py +++ b/evalrx/eval_agent/runlog/context.py @@ -8,8 +8,8 @@ gluing with one library-owned object that owns the whole run directory and hands every producer its subdirectory. -The logger is :class:`~evalrx.eval_agent.run_logger.RunLogger` (see -``evalrx/eval_agent/RUN_LOGGER.md``): one ``run.json`` plus one +The logger is :class:`~evalrx.eval_agent.runlog.logger.RunLogger` (see +``evalrx/eval_agent/runlog/README.md``): one ``run.json`` plus one ``M1/log.json``..``M5/log.json`` per stage, no flat event file, no persisted ``prompts/``/``experiments/``/``tools/``/``workspace/``/``fixes/`` — generated text/code is captured inline into the relevant stage's JSON via an ephemeral @@ -57,7 +57,7 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger class Trial: @@ -113,7 +113,7 @@ class RunContext: verbose: Forwarded to the logger (human-readable stdout). narrate: Forwarded to the logger — live, aligned M1-M5 terminal narration instead of `verbose`'s raw one-liner (see - :class:`evalrx.eval_agent.narration.LoopNarrator`). + :class:`evalrx.eval_agent.runlog.narration.LoopNarrator`). Supersedes *verbose* rather than stacking with it. config: Optional run-configuration dict recorded verbatim in the manifest (model, judge, protocol, …). @@ -200,7 +200,7 @@ def artifacts_dir(self) -> Path: def logger(self) -> "RunLogger": """The logger bound to this context (created on first use).""" if self._logger is None: - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger self._logger = RunLogger( run_dir=self.root, verbose=self._verbose, narrate=self._narrate, @@ -275,7 +275,7 @@ def write_diagnose_report( *discovery* (optional) is a list of already-serialised case rows — examples that compute task-specific columns (e.g. parsed yes/no) build the rows themselves. Delegates to - :meth:`~evalrx.eval_agent.run_logger.RunLogger.log_diagnose_report`. + :meth:`~evalrx.eval_agent.runlog.logger.RunLogger.log_diagnose_report`. """ self.logger.log_diagnose_report(report, cases, discovery=discovery) diff --git a/evalrx/eval_agent/run_log_entries.py b/evalrx/eval_agent/runlog/entries.py similarity index 100% rename from evalrx/eval_agent/run_log_entries.py rename to evalrx/eval_agent/runlog/entries.py diff --git a/evalrx/eval_agent/run_log_files.py b/evalrx/eval_agent/runlog/files.py similarity index 100% rename from evalrx/eval_agent/run_log_files.py rename to evalrx/eval_agent/runlog/files.py diff --git a/evalrx/eval_agent/model_instrumentation.py b/evalrx/eval_agent/runlog/instrumentation.py similarity index 83% rename from evalrx/eval_agent/model_instrumentation.py rename to evalrx/eval_agent/runlog/instrumentation.py index b36b6086..729bb205 100644 --- a/evalrx/eval_agent/model_instrumentation.py +++ b/evalrx/eval_agent/runlog/instrumentation.py @@ -61,9 +61,11 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: + from collections.abc import Sequence + from evalrx.core.capability import Capability from evalrx.core.model import CaptureSpec, Judge, Model, Trace - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger # The proxy stands in for the Model it wraps. It is not a subclass at run # time: Model's class-level defaults (capabilities, modalities) would @@ -192,6 +194,7 @@ def _next_call_index(self) -> int: def _record( self, method: str, inputs: Any, kwargs: "dict[str, Any] | None", output: Any, duration_sec: float, error: "str | None", + batch_size: int = 1, ) -> None: prompt = inputs if isinstance(inputs, str) else getattr(inputs, "prompt", None) case_id = self._case_prompts.get(str(prompt)) if prompt is not None else None @@ -205,6 +208,7 @@ def _record( "batch_case_ids": self._batch_case_ids_inline, "n_batch_cases": self._n_batch_cases, "kwargs": {k: str(v) for k, v in (kwargs or {}).items()}, + "batch_size": batch_size, }, ) return @@ -221,8 +225,37 @@ def _record( output=output, duration_sec=duration_sec, error=error, + batch_size=batch_size, ) + def generate_batch(self, inputs: "Sequence[Any]", **kwargs: Any) -> list[str]: + inputs = list(inputs) + t0 = time.monotonic() + try: + outs = self._model.generate_batch(inputs, **kwargs) + except Exception as exc: # noqa: BLE001 - record the failure, then re-raise it + self._record_batch(inputs, kwargs, [exc] * len(inputs), time.monotonic() - t0) + raise + self._record_batch(inputs, kwargs, outs, time.monotonic() - t0) + return outs + + def try_generate_batch(self, inputs: "Sequence[Any]", **kwargs: Any) -> "list[str | Exception]": + inputs = list(inputs) + t0 = time.monotonic() + outs = self._model.try_generate_batch(inputs, **kwargs) + self._record_batch(inputs, kwargs, outs, time.monotonic() - t0) + return outs + + def _record_batch(self, inputs: list, kwargs: "dict[str, Any]", outs: "Sequence[Any]", + duration_sec: float) -> None: + """One record per input. ``duration_sec`` is the input's share of the + batch's wall time, so the records still sum to the time spent.""" + share = duration_sec / max(1, len(inputs)) + for item, out in zip(inputs, outs): + failed = isinstance(out, Exception) + self._record("generate", item, kwargs, None if failed else str(out), share, + repr(out) if failed else None, batch_size=len(inputs)) + def generate(self, inputs: Any, **kwargs: Any) -> str: t0 = time.monotonic() try: @@ -257,6 +290,23 @@ def logprobs(self, inputs: Any, **kwargs: Any) -> "list[Any]": self._record("logprobs", inputs, kwargs, summary, time.monotonic() - t0, None) return toks + def logprobs_batch(self, inputs: "Sequence[Any]", **kwargs: Any) -> "list[list[Any]]": + inputs = list(inputs) + t0 = time.monotonic() + try: + rows = self._model.logprobs_batch(inputs, **kwargs) + except Exception as exc: # noqa: BLE001 + share = (time.monotonic() - t0) / max(1, len(inputs)) + for item in inputs: + self._record("logprobs", item, kwargs, None, share, repr(exc), + batch_size=len(inputs)) + raise + share = (time.monotonic() - t0) / max(1, len(inputs)) + for item, toks in zip(inputs, rows): + summary = [{"token": t.token, "logprob": round(t.logprob, 4)} for t in toks] + self._record("logprobs", item, kwargs, summary, share, None, batch_size=len(inputs)) + return rows + def chat(self, messages: list, tools: "list | None" = None) -> Any: t0 = time.monotonic() try: diff --git a/evalrx/eval_agent/run_logger.py b/evalrx/eval_agent/runlog/logger.py similarity index 97% rename from evalrx/eval_agent/run_logger.py rename to evalrx/eval_agent/runlog/logger.py index 046857aa..01278ca0 100644 --- a/evalrx/eval_agent/run_logger.py +++ b/evalrx/eval_agent/runlog/logger.py @@ -4,7 +4,7 @@ ``run.json`` for what is not stage content; every event of one kind is one array in one file; everything text-shaped is a string value in the JSON, and only binary media (figures, tensors, audio) is a separate file. See -``RUN_LOGGER.md`` beside this file for the layout and the reasoning. +``README.md`` beside this file for the layout and the reasoning. This module is the class and what only it can do: route an event to its document, stamp it, and write the document atomically. What an event records @@ -28,8 +28,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any -from evalrx.eval_agent.log_schema import RUN_LOG_SCHEMA_VERSION -from evalrx.eval_agent.run_log_entries import ( +from evalrx.eval_agent.runlog.entries import ( analysis_entry, diagnose_report_entry, diagnosis_entry, @@ -40,13 +39,14 @@ probe_entry, surgery_entry, ) -from evalrx.eval_agent.run_log_files import ( +from evalrx.eval_agent.runlog.files import ( artifact_to_numpy, atomic_write_json, inline_workspace, save_artifact_figure, ) -from evalrx.eval_agent.run_log_tracing import ( +from evalrx.eval_agent.runlog.schema import RUN_LOG_SCHEMA_VERSION +from evalrx.eval_agent.runlog.tracing import ( trace_agent_decision, trace_analysis, trace_diagnosis, @@ -64,7 +64,7 @@ from evalrx.analysis.analysis_module import AnalysisReport from evalrx.core.result import Result from evalrx.eval_agent.hypothesis import Hypothesis - from evalrx.eval_agent.loop_reports import AutoDiagnoseReport + from evalrx.eval_agent.loop.report import AutoDiagnoseReport from evalrx.eval_agent.stages.diagnosis import DiagnosisResult from evalrx.eval_agent.stages.surgery import InterventionResult @@ -76,7 +76,7 @@ #: Tags used somewhere in the codebase that carry no "m" substring at all #: (checked against every literal `module=`/`stage=` value passed to a -#: log_* method as of this writing — see RUN_LOGGER.md's "routing" table). +#: log_* method as of this writing — see README.md's "routing" table). _STAGE_ALIASES: dict[str, str] = { "fix_pipeline": "M5", "fix": "M5", @@ -138,7 +138,7 @@ class RunLogger: (``[M1] probe cycle=0``). Ignored when *narrate* is set. narrate: Print live, aligned M1-M5 narration instead — the same visual style as ``evalrx explore``'s terminal output (see - :mod:`evalrx.eval_agent.narration.LoopNarrator`), built + :mod:`evalrx.eval_agent.runlog.narration.LoopNarrator`), built from real per-stage counts instead of a raw event dump. trace_id: Ties every event to one Langfuse trace; auto-generated if omitted. @@ -179,12 +179,12 @@ def __init__( self.trace_id: str = trace_id or str(uuid.uuid4()) self.current_cycle: int = -1 - # Live M1-M5 terminal narration (see evalrx.eval_agent.narration) -- + # Live M1-M5 terminal narration (see evalrx.eval_agent.runlog.narration) -- # opt-in, takes over from the plain `verbose` one-liner below rather # than stacking with it, so a run never prints each event twice. self._narrator = None if narrate: - from evalrx.eval_agent.narration import LoopNarrator + from evalrx.eval_agent.runlog.narration import LoopNarrator self._narrator = LoopNarrator() self.verbose = verbose @@ -279,7 +279,7 @@ def _stamp_event(self, key: str, record: dict[str, Any], stage: str) -> None: record.setdefault("ts", self._ts()) if self._validate_events: try: - from evalrx.eval_agent.log_schema import _validator, build_schema + from evalrx.eval_agent.runlog.schema import _validator, build_schema if self._event_validator is None: self._event_validator = _validator(build_schema()) @@ -313,6 +313,17 @@ def _append_stage(self, tag: "str | None", key: str, record: "dict[str, Any]") - print(_EventLine.line(stage, key, record)) return stage + def progress(self, stage: str, text: str) -> None: + """Print one line about work still running inside *stage*. + + Console only: a stage that takes minutes says what it is on, and the + event log keeps its one record per finished step. + """ + if self._narrator is not None: + self._narrator.progress(stage, text) + elif self.verbose: + print(f"[{stage}] {text}") + def _append_run(self, key: str, record: "dict[str, Any]") -> None: """Append *record* to the (always list-valued) run.json bucket *key*. @@ -578,6 +589,7 @@ def log_model_call( case_id: "str | None" = None, batch_case_ids: "list[str] | None" = None, n_batch_cases: "int | None" = None, + batch_size: int = 1, ) -> None: record: dict[str, Any] = { "ts": self._ts(), "cycle": cycle, "analyzer": analyzer, @@ -587,6 +599,8 @@ def log_model_call( "inputs": inputs, "kwargs": kwargs, "output": output, "duration_sec": round(duration_sec, 4), } + if batch_size > 1: + record["batch_size"] = batch_size if error is not None: record["error"] = error with self._lock: diff --git a/evalrx/eval_agent/narration.py b/evalrx/eval_agent/runlog/narration.py similarity index 97% rename from evalrx/eval_agent/narration.py rename to evalrx/eval_agent/runlog/narration.py index eff3a718..14ce46d8 100644 --- a/evalrx/eval_agent/narration.py +++ b/evalrx/eval_agent/runlog/narration.py @@ -1,5 +1,5 @@ """Live per-stage terminal narration for the M1-M5 diagnosis loop -(:class:`~evalrx.eval_agent.run_logger.RunLogger`). +(:class:`~evalrx.eval_agent.runlog.logger.RunLogger`). Sibling of :class:`evalrx.analysis.narration.TerminalNarrator` (built for the `evalrx explore`/`run-codebase` CLI pipeline) — same visual grammar @@ -87,6 +87,10 @@ def _row(self, key: str, detail: str) -> str: def _print(self, key: str, detail: str) -> None: print(self._row(key, detail), file=self.stream, flush=True) + def progress(self, stage: str, text: str) -> None: + """One line about work still running inside *stage*.""" + self._print(stage, self._c(_DIM, text)) + # -- stage events (M1-M5), from RunLogger._append_stage ------------- def on_event(self, stage: str, key: str, record: dict[str, Any]) -> None: diff --git a/evalrx/eval_agent/run_log.schema.json b/evalrx/eval_agent/runlog/run_log.schema.json similarity index 99% rename from evalrx/eval_agent/run_log.schema.json rename to evalrx/eval_agent/runlog/run_log.schema.json index 6b9eefc8..607ef556 100644 --- a/evalrx/eval_agent/run_log.schema.json +++ b/evalrx/eval_agent/runlog/run_log.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://evalrx.dev/schemas/run_log.schema.json", "title": "EvalRX run event", - "description": "One logged event, wherever a run stores it (run.json / M/log.json). Discriminated on `event`; matches schema_version 8. Permissive: extra (additive) fields are allowed.", + "description": "One logged event, wherever a run stores it (run.json / M/log.json). Discriminated on `event`; matches schema_version 9. Permissive: extra (additive) fields are allowed.", "$defs": { "envelope": { "type": "object", @@ -42,7 +42,7 @@ ] }, "schema_version": { - "const": 8 + "const": 9 }, "ts": { "type": "string", @@ -973,6 +973,10 @@ "string", "null" ] + }, + "batch_size": { + "type": "integer", + "minimum": 2 } }, "required": [ diff --git a/evalrx/eval_agent/log_schema.py b/evalrx/eval_agent/runlog/schema.py similarity index 98% rename from evalrx/eval_agent/log_schema.py rename to evalrx/eval_agent/runlog/schema.py index cdc97e37..9977bb59 100644 --- a/evalrx/eval_agent/log_schema.py +++ b/evalrx/eval_agent/runlog/schema.py @@ -65,7 +65,10 @@ # v8: `analysis` no longer carries `stats_tool_results` / `visualizations` # (summaries from a retired tool layer); `stats_results` and `figures` # hold the same information. -RUN_LOG_SCHEMA_VERSION = 8 +# v9: `model_call.batch_size`, on a call that was one input of a +# `generate_batch`; its `duration_sec` is then that input's share of the +# batch's wall time. +RUN_LOG_SCHEMA_VERSION = 9 #: The event types a run logs. EVENT_TYPES: tuple[str, ...] = ( @@ -344,6 +347,7 @@ "properties": { "duration_sec": {"type": "number"}, "error": {"type": ["string", "null"]}, + "batch_size": {"type": "integer", "minimum": 2}, }, "anyOf": [{"required": ["analyzer", "method", "call_index"]}, {"required": ["role", "operation"]}], diff --git a/evalrx/eval_agent/run_log_tracing.py b/evalrx/eval_agent/runlog/tracing.py similarity index 100% rename from evalrx/eval_agent/run_log_tracing.py rename to evalrx/eval_agent/runlog/tracing.py diff --git a/evalrx/eval_agent/stages/case_discovery.py b/evalrx/eval_agent/stages/case_discovery.py index 61616c26..272b4cd2 100755 --- a/evalrx/eval_agent/stages/case_discovery.py +++ b/evalrx/eval_agent/stages/case_discovery.py @@ -50,19 +50,10 @@ class CaseDiscoveryAgent: judge: Optional LLM judge used when no scorer is supplied. generation_kwargs: Extra kwargs forwarded to ``model.generate``. include_unknown: Keep UNKNOWN cases in the returned batch. - concurrency: How many cases may be generated at once. Only the - ``model.generate`` calls fan out; scoring and - labelling stay sequential and in input order, so the - report is identical whatever this is set to. - - Values above 1 are honoured ONLY for an API-backed - handle, following the same rule as - :func:`evalrx.models.agent.run_batch`: HTTP is - reentrant, a local backend sharing one GPU is not. - Against a local ``vllm serve`` this is the - difference between one request in flight and a - batch -- the server can only batch what it has been - given. + n_samples: Answers drawn per case; the label is their majority. + One is right for a deterministic model. A sampling + model can answer the same case both ways, so one + answer labels it by chance; use an odd number. """ def __init__( @@ -71,13 +62,15 @@ def __init__( judge: "Judge | None" = None, generation_kwargs: dict[str, Any] | None = None, include_unknown: bool = True, - concurrency: int = 1, + n_samples: int = 1, ) -> None: + if n_samples < 1: + raise ValueError(f"n_samples must be at least 1, got {n_samples}") self.scorer = scorer self.judge = judge self.generation_kwargs = generation_kwargs or {} self.include_unknown = include_unknown - self.concurrency = max(1, int(concurrency)) + self.n_samples = n_samples def discover( self, @@ -92,23 +85,30 @@ def discover( counts = {Label.PASS: 0, Label.FAIL: 0, Label.UNKNOWN: 0} cases = list(candidates) - for case, observed, gen_error in self._generate(model, cases): - try: - if gen_error is not None: - raise gen_error - case.observed = observed - label, reason = self._score_with_reason(case, str(observed), protocol) - except Exception as exc: # noqa: BLE001 - discovery should continue - observed = "" - label = Label.UNKNOWN - reason = "model generation or scoring raised an exception" - errors.append(f"{case.id}: {exc}") - case.metadata["discovery_error"] = str(exc) - + for case, answers in zip(cases, self._generate(model, cases)): + samples = [self._sample(case, answer, protocol) for answer in answers] + n_pass = sum(1 for s in samples if s.label is Label.PASS) + n_fail = sum(1 for s in samples if s.label is Label.FAIL) + label = (Label.PASS if n_pass > n_fail + else Label.FAIL if n_fail > n_pass else Label.UNKNOWN) + # The recorded answer is one that earned the label: analyzers score + # ``observed`` and must reach the label the case carries. + shown = next((s for s in samples if s.label is label), samples[0]) + failed = [s.error for s in samples if s.error] + errors.extend(f"{case.id}: {error}" for error in failed) + + if shown.observed is not None: + case.observed = shown.observed case.label = label - case.metadata["discovery_observed"] = str(observed) + case.metadata["discovery_observed"] = "" if shown.error else str(shown.observed) case.metadata["discovery_label"] = label.value - case.metadata["discovery_reason"] = reason + case.metadata["discovery_reason"] = shown.reason + if label is Label.UNKNOWN and failed: + case.metadata["discovery_error"] = failed[0] + if self.n_samples > 1: + case.metadata["discovery_votes"] = {"pass": n_pass, "fail": n_fail} + case.metadata["discovery_reason"] = ( + f"{n_pass} of {len(samples)} sampled answers passed; {shown.reason}") counts[label] += 1 if label != Label.UNKNOWN or self.include_unknown: @@ -122,59 +122,30 @@ def discover( errors=errors, ) - def _generate( - self, model: "Model", cases: list[FailureCase] - ) -> "list[tuple[FailureCase, Any, Exception | None]]": - """``(case, observed, error)`` per case, in input order. + def _generate(self, model: "Model", cases: list[FailureCase]) -> "list[list[Any]]": + """Each case's ``n_samples`` answers, in case order. - The exception is carried rather than raised so the caller keeps its one - place that turns any failure into an UNKNOWN label -- a case whose - generation failed and a case whose scoring failed are the same - observation, and both must leave the batch intact. - """ - workers = self._workers(model, len(cases)) - if workers <= 1: - out: "list[tuple[FailureCase, Any, Exception | None]]" = [] - for case in cases: - try: - out.append((case, model.generate(case.inputs, **self.generation_kwargs), None)) - except Exception as exc: # noqa: BLE001 - out.append((case, None, exc)) - return out - - from concurrent.futures import ThreadPoolExecutor - - def _one(case: FailureCase): - try: - return case, model.generate(case.inputs, **self.generation_kwargs), None - except Exception as exc: # noqa: BLE001 - return case, None, exc - - with ThreadPoolExecutor(max_workers=workers) as pool: - return list(pool.map(_one, cases)) - - def _workers(self, model: "Model", n_cases: int) -> int: - """Concurrency actually allowed for this handle. - - A local backend is silently forced back to 1 rather than warned about: - unlike ``run_batch``, nothing here asked for parallelism per case -- - the caller set one number for a whole run that may mix handles, and a - warning per discovery pass would be noise about a setting that is - behaving correctly. + A failed generation is carried as its exception rather than raised, so + one bad case leaves the batch intact. """ - if self.concurrency <= 1: - return 1 - from evalrx.models.backends.api import APIModel - - # A deployed-pipeline wrapper (fix_tools.SpecPipelineModel) is exactly - # as reentrant as the handle it drives — judge it by its inner model. - model = getattr(model, "inner_model", model) - # InstrumentedModel is also a transparent proxy; preserve the API - # handle's configured discovery concurrency while recording each call. - model = getattr(model, "_model", model) - if not isinstance(model, APIModel): - return 1 - return min(self.concurrency, max(1, n_cases)) + # One batch call. The backend decides how many run at once: padded + # batches on a local model, ``runtime.concurrency`` requests over an API. + k = self.n_samples + answers = model.try_generate_batch( + [case.inputs for case in cases for _ in range(k)], **self.generation_kwargs) + return [answers[i * k:(i + 1) * k] for i in range(len(cases))] + + def _sample( + self, case: FailureCase, answer: Any, protocol: "ExperimentProtocol | None" + ) -> "_Sample": + """One answer and its label; a failed generation or scoring is UNKNOWN.""" + if isinstance(answer, Exception): + return _Sample(None, Label.UNKNOWN, _FAILED, str(answer)) + try: + label, reason = self._score_with_reason(case, str(answer), protocol) + except Exception as exc: # noqa: BLE001 - discovery should continue + return _Sample(answer, Label.UNKNOWN, _FAILED, str(exc)) + return _Sample(answer, label, reason) def _score_with_reason( self, @@ -216,6 +187,19 @@ def _judge_score( return _coerce_label(graded.label), graded.reason +_FAILED = "model generation or scoring raised an exception" + + +@dataclass +class _Sample: + """One sampled answer of a case and what it scored.""" + + observed: Any + label: Label + reason: str + error: str = "" + + class _CaseLabel(BaseModel): label: Literal["PASS", "FAIL", "UNKNOWN"] reason: str = "judge returned a structured label" diff --git a/evalrx/eval_agent/stages/diagnosis.py b/evalrx/eval_agent/stages/diagnosis.py index ea13a0ee..9da07cc8 100755 --- a/evalrx/eval_agent/stages/diagnosis.py +++ b/evalrx/eval_agent/stages/diagnosis.py @@ -277,6 +277,37 @@ def _plain_language_problems(proposal: Proposal) -> str | None: ) +def _unmeasured_test_problems(proposal: Proposal, stats_results: list[Any]) -> str | None: + """Feedback for tests that name only evidence M2 did not measure, or ``None``. + + M4 does not judge such a hypothesis: its test is unmet until a later cycle + measures what it names. Asking once here keeps a run from spending a + hypothesis on a signal name the judge made up or on a case id. + """ + from evalrx.eval_agent.stages.hypothesis_tester import ( + testable_signals, + unmeasured_identifiers, + ) + + problems = [ + f"- hypothesis {i}'s test names {', '.join(sorted(missing)[:6])}" + for i, d in enumerate(proposal.hypotheses, start=1) + for missing in [unmeasured_identifiers(d.test, stats_results)] + if missing + ] + if not problems: + return None + usable = testable_signals(stats_results) + return ( + "Some tests name identifiers that have no result to check them against " + "this cycle. Rewrite only those tests: name one of the signals below " + "exactly as written, or, when none of them tests the claim, describe the " + "evidence in plain words without identifiers or case ids. Keep every " + "other field as it was.\n" + "\n".join(problems) + + "\nSignals with a result: " + (", ".join(usable[:30]) or "none") + ) + + def _to_hypothesis(draft: HypothesisDraft, model_name: str) -> Hypothesis: return Hypothesis( statement=draft.hypothesis, @@ -595,9 +626,16 @@ def diagnose( # A failed or unreadable proposal raises JudgeError with every exchange; # the loop logs them and retries M3 or stops, instead of this stage # standing in a guess for the judge's answer. + def _problems(proposal: Proposal) -> str | None: + found = [text for text in ( + _plain_language_problems(proposal), + _unmeasured_test_problems(proposal, stats_results) if signals else None, + ) if text] + return "\n\n".join(found) or None + reply = ask_judge( self.judge, prompt, Proposal, role="diagnosis_judge", - images=_figs, check=_plain_language_problems, + images=_figs, check=_problems, ) self._model_calls.extend(e.record() for e in reply.exchanges) raw = reply.raw diff --git a/evalrx/eval_agent/stages/experiment_writer.py b/evalrx/eval_agent/stages/experiment_writer.py index 125c6d75..af1e001e 100755 --- a/evalrx/eval_agent/stages/experiment_writer.py +++ b/evalrx/eval_agent/stages/experiment_writer.py @@ -1132,7 +1132,7 @@ def _cli_write_and_run( workdir = getattr(sandbox, "workdir", Path(tempfile.mkdtemp(prefix="evalrx_cli_"))) import json as _json - (workdir / "cases.json").write_text(cases_json, encoding="utf-8") + sandbox.put("cases.json", cases_json) # Summarise which cases have images so the agent prompt is accurate try: _cases = _json.loads(cases_json) @@ -1140,12 +1140,12 @@ def _cli_write_and_run( except Exception: _n_images = 0 - (workdir / "hypothesis.md").write_text( + sandbox.put( + "hypothesis.md", f"# Hypothesis\n\n" f"**Statement:** {hypothesis.statement}\n\n" f"**Failure mode:** {hypothesis.predicted_failure_mode}\n\n" f"**Target model:** {hypothesis.target_model}\n", - encoding="utf-8", ) prompt = build_cli_prompt( diff --git a/evalrx/eval_agent/stages/fix/agent.py b/evalrx/eval_agent/stages/fix/agent.py index 213c25b4..4a21b6c3 100755 --- a/evalrx/eval_agent/stages/fix/agent.py +++ b/evalrx/eval_agent/stages/fix/agent.py @@ -133,9 +133,10 @@ class FixAgent: unbounded batch makes coded pipelines time out. baseline_repeats: Samples per case for the unmodified baseline (default 1 = the frozen ``observed`` output). With - ``k > 1`` the frozen sample counts as one and ``k-1`` - fresh samples are drawn, giving each case a baseline - PASS RATE; the paired test then runs on per-case rate + ``k > 1`` it draws ``k`` fresh samples, giving each + case a baseline PASS RATE (the frozen output labelled + the case, so it is not an independent draw and is + left out); the paired test then runs on per-case rate differences (``noise_model="paired_rates"``, betting e-value) instead of one-sample McNemar. A case whose baseline flips across samples is *unstable* — it is @@ -152,7 +153,7 @@ class FixAgent: alpha: Significance level for the e-value gate (default 0.05; rejects when e >= 1/alpha). Also sets the power ceiling used to flag underpowered-by-design runs. - run_context: Optional :class:`~evalrx.eval_agent.run_context.RunContext`. + run_context: Optional :class:`~evalrx.eval_agent.runlog.context.RunContext`. When set (directly, or inherited from ``run_logger``), coded-pipeline sandbox workdirs are allocated durably under ``workspace/`` instead of an ephemeral temp dir. @@ -207,10 +208,6 @@ class FixAgent: cases' ``metadata["generation_config"]``, else no floor is enforced. Both values are also shown to the proposer. - concurrency: Threads used to run a declarative candidate over - the validation batch, and how many bridged model - calls the coded-pipeline host services at once - (default 1 = serial, unchanged behaviour). scoring_note: Free-text description of how outputs are scored / the expected final-answer format, shown to the proposer (a per-call ``FixContext.scoring_note`` @@ -251,7 +248,6 @@ def __init__( weight_edit: "bool | dict[str, Any] | None" = None, verbose: bool = False, baseline_generation_kwargs: "dict[str, Any] | None" = None, - concurrency: int = 1, scoring_note: str = "", floor_candidates: "Iterable[str] | None" = ("self_consistency_5",), prewritten_code: str = "", @@ -295,7 +291,6 @@ def __init__( self._max_tokens_floor: "int | None" = None score = score_fn or _default_score - concurrency = max(1, int(concurrency)) self.recorder = FixRecorder(run_logger) self.coder = PipelineCoder( judge=judge, @@ -306,7 +301,6 @@ def __init__( run_context=self._run_context, sandbox=sandbox, exec_timeout_sec=exec_timeout_sec, - concurrency=concurrency, max_repair_rounds=max(1, int(max_repair_rounds)), prewritten_code=prewritten_code, ) @@ -329,7 +323,6 @@ def __init__( recorder=self.recorder, coder=self.coder, progress=self._progress, - concurrency=concurrency, baseline_repeats=max(1, int(baseline_repeats)), candidate_repeats=max(1, int(candidate_repeats)), finetune_pool=finetune_pool, @@ -392,8 +385,9 @@ def propose_and_validate( remains untouched confirmation data and permits only one round. ``max_tier`` / ``min_tier`` narrow the tier window for this call only - (default: the agent's own). ``record=False`` writes nothing to the - run logger, for a caller that records one combined outcome itself. + (default: the agent's own). ``record=False`` leaves out the ``fix`` + outcome event, for a caller that records one combined outcome itself; + the model and judge exchanges of the search are logged either way. """ window = ( parse_tier(max_tier) if max_tier is not None else self.max_tier, @@ -402,7 +396,7 @@ def propose_and_validate( if record: return self._search(model, data, hypotheses, prior_attempts, context, proposal_data, *window) - with self.recorder.muted(): + with self.recorder.without_outcome(): return self._search(model, data, hypotheses, prior_attempts, context, proposal_data, *window) diff --git a/evalrx/eval_agent/stages/fix/codegen.py b/evalrx/eval_agent/stages/fix/codegen.py index 7bf2ccd3..502d5fb7 100644 --- a/evalrx/eval_agent/stages/fix/codegen.py +++ b/evalrx/eval_agent/stages/fix/codegen.py @@ -31,7 +31,7 @@ from evalrx.agent_runtime.cli_types import CliAgentConfig from evalrx.core.case import CaseBatch, FailureCase from evalrx.core.model import Judge, Model - from evalrx.eval_agent.run_context import Trial + from evalrx.eval_agent.runlog.context import Trial logger = logging.getLogger(__name__) @@ -112,7 +112,6 @@ def __init__( run_context: "Any | None" = None, sandbox: "Any | None" = None, exec_timeout_sec: int = 600, - concurrency: int = 1, max_repair_rounds: int = 1, prewritten_code: str = "", ) -> None: @@ -124,7 +123,6 @@ def __init__( self.run_context = run_context self.sandbox = sandbox self.exec_timeout_sec = exec_timeout_sec - self.concurrency = concurrency self.max_repair_rounds = max_repair_rounds self._prewritten_code = str(prewritten_code or "") self._last_repair_prompt = "" @@ -333,7 +331,6 @@ def run( timeout_sec=self.exec_timeout_sec, enable_attend=bool(candidate.payload.get("enable_attend")), max_tokens_floor=max_tokens_floor, - concurrency=self.concurrency, consensus_min_support=int(candidate.payload.get("consensus_min_support", 0)), max_calls_per_case=int(candidate.payload.get("max_calls_per_case", 0)), call_logger=self.recorder.bridge_exchange, @@ -362,7 +359,6 @@ def run( timeout_sec=self.exec_timeout_sec, enable_attend=bool(candidate.payload.get("enable_attend")), max_tokens_floor=max_tokens_floor, - concurrency=self.concurrency, consensus_min_support=int( candidate.payload.get("consensus_min_support", 0) ), diff --git a/evalrx/eval_agent/stages/fix/pipeline.py b/evalrx/eval_agent/stages/fix/pipeline.py index 971c070b..99308089 100755 --- a/evalrx/eval_agent/stages/fix/pipeline.py +++ b/evalrx/eval_agent/stages/fix/pipeline.py @@ -15,9 +15,11 @@ reply on stdin; the host services each call (applies catalog image tools to the case's image, runs ``model.generate``) under a per-session call budget and wall-clock deadline. Requests carry a ``rid`` echoed by the reply, so - the sandbox helper is thread-safe and the host can service several calls at - once (``concurrency=``) — a pipeline that fans out over cases with a thread - pool really runs in parallel. + the sandbox helper is thread-safe. One host thread answers the calls: those + that arrive together go to the model as one batch + (``Model.try_generate_batch``), which a local model pads into one forward + pass and an API model sends as concurrent requests — a pipeline that fans + out over cases with a thread pool is answered a round at a time. * The script's final ``FIX_PIPELINE_RESULT_JSON=`` line carries per-case final answers; **scoring stays host-side** — the case payload shipped to the sandbox contains only ``id``, ``prompt`` and the model's own @@ -43,12 +45,12 @@ import json import logging +import queue import re import subprocess import sys import threading import time -from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Optional, cast @@ -64,6 +66,10 @@ CASES_FILENAME = "fix_cases.json" CALL_MARKER = "@@MODEL_CALL@@" RESULT_MARKER = "FIX_PIPELINE_RESULT_JSON=" +#: How long the host keeps collecting after a call arrives before it answers +#: what it has. Sandbox threads that fan out over cases send their calls within +#: milliseconds of each other; one model call takes seconds. +GATHER_SEC = 0.05 # Injected ahead of the generated code: the only channel to the model. _PRELUDE = '''\ @@ -123,8 +129,8 @@ def _bridge_call(payload): def model_generate(case_id, prompt=None, image_ops=None, generation_kwargs=None): """Call the original model on one case (host-mediated bridge). - Thread-safe: concurrent calls (e.g. from a ThreadPoolExecutor over cases) - are serviced in parallel by the host. + Thread-safe: calls made at the same time (e.g. from a ThreadPoolExecutor + with one worker per case) are answered by the host as one batch. generation_kwargs: optional bounded decoding controls ({{"max_tokens", "temperature", "top_p", "stop"}}); anything else is @@ -203,7 +209,6 @@ def run_coded_pipeline( enable_attend: bool = False, reply_fn: "Callable[[Any, str], str] | None" = None, max_tokens_floor: "int | None" = None, - concurrency: int = 1, consensus_min_support: int = 0, max_calls_per_case: int = 0, call_logger: "Callable[[dict[str, Any]], None] | None" = None, @@ -215,13 +220,14 @@ def run_coded_pipeline( invoked host-side). Returns the per-case final answers for host-side scoring. - ``concurrency``: how many bridged calls the host services at once. Every - request carries a ``rid`` and the reply echoes it, so the sandbox side is - thread-safe — generated code that fans out over cases with a thread pool - really runs in parallel (with ``concurrency=1`` calls are serviced strictly - in arrival order, the old behaviour). Without the ids a threaded pipeline - silently read each other's replies: the reply to case A's prompt could - land in case B's vote. + Every request carries a ``rid`` and the reply echoes it, so the sandbox + side is thread-safe: without the ids a threaded pipeline silently read each + other's replies (the reply to case A's prompt could land in case B's + vote). One host thread owns the model. It answers the calls that arrived + within ``GATHER_SEC`` of each other as one ``try_generate_batch`` per + distinct decoding setting, so how many run at once is the model's own + business (``RuntimeConfig.batch_size`` locally, ``concurrency`` for an + API), and a white-box model is never entered from two threads. ``reply_fn(case, prompt) -> str``, when given, answers every bridged call instead of the model (which is then never touched) — the hook @@ -248,8 +254,6 @@ def run_coded_pipeline( from the record (``n_replayed``) and is free under the cap — there is nothing to select from in re-reading the baseline. """ - from evalrx.core.case import Inputs - res = CodedPipelineResult() case_by_id = {c.id: c for c in cases} budget = max_calls if max_calls is not None else 6 * len(case_by_id) + 10 @@ -300,76 +304,94 @@ def _kill_on_timeout() -> None: call_records: "dict[str, list[tuple[bool, str, str]]]" = {} calls_per_case: "dict[str, int]" = {} unmarked_tail: "list[str]" = [] # fallback: last non-marker stdout lines - stdin_lock = threading.Lock() - records_lock = threading.Lock() - pool = (ThreadPoolExecutor(max_workers=max(1, int(concurrency))) - if int(concurrency) > 1 else None) - - def _rid_of(raw: str) -> "Any": - try: - return json.loads(raw).get("rid") - except Exception: - return None + calls: "queue.Queue[tuple[dict[str, Any], str] | None]" = queue.Queue() - def _send(reply: "dict[str, Any]") -> bool: - with stdin_lock: - try: - proc.stdin.write(json.dumps(reply) + "\n") # type: ignore[union-attr] - proc.stdin.flush() # type: ignore[union-attr] - return True - except (BrokenPipeError, OSError, ValueError): - return False - - def _serve(raw: str, request: "dict[str, Any]", case_id: str) -> bool: - call_started = time.perf_counter() - case = case_by_id.get(case_id) - replayed = reply_fn is None and _replayable_direct(request, case) - if replayed: - # The direct baseline is already on record: answer from it. Under - # greedy decoding a fresh call would return the same text; under - # sampling the record is the frozen baseline arm the paired test - # compares against, so replaying it keeps anchor and baseline - # identical (a resample could drift from both). - # _replayable_direct is False for a missing case. - reply: "dict[str, Any]" = {"output": str(cast("FailureCase", case).observed)} - with records_lock: - res.n_replayed += 1 - else: - reply = _service_call(raw, case_by_id, model, Inputs, enable_attend, - reply_fn, max_tokens_floor=max_tokens_floor) - reply["rid"] = _rid_of(raw) - if call_logger is not None: - try: - call_logger({ - "case_id": case_id, - "request": request, - "response": {k: v for k, v in reply.items() if k != "rid"}, - "replayed_from_recorded_baseline": replayed, - "duration_sec": time.perf_counter() - call_started, - }) - except Exception as exc: # logging must never break the bridge - logger.debug("fix_pipeline: call logger failed: %s", exc) - # Record the call for the gold-free consensus guard: was it the direct - # baseline (untouched prompt, no ops), and what did it answer? + def _send(reply: "dict[str, Any]") -> None: try: + proc.stdin.write(json.dumps(reply) + "\n") # type: ignore[union-attr] + proc.stdin.flush() # type: ignore[union-attr] + except (BrokenPipeError, OSError, ValueError): + pass # the script is gone; its result line (or the lack of one) says why + + def _answer(batch: "list[tuple[dict[str, Any], str]]") -> None: + """Reply to every call in *batch*; the ones that need the model share it.""" + started = time.perf_counter() + replies: "list[dict[str, Any]]" = [] + replayed: "set[int]" = set() + asks: "dict[str, tuple[dict[str, Any], list[tuple[int, Any]]]]" = {} + for index, (request, case_id) in enumerate(batch): + case = case_by_id.get(case_id) + if reply_fn is None and _replayable_direct(request, case): + # The direct baseline is already on record: answer from it. + # Under greedy decoding a fresh call would return the same + # text; under sampling the record is the frozen baseline arm + # the paired test compares against, so replaying it keeps + # anchor and baseline identical (a resample could drift from + # both). _replayable_direct is False for a missing case. + replies.append({"output": str(cast("FailureCase", case).observed)}) + replayed.add(index) + continue + prepared = _prepare_call(request, case, model, enable_attend, reply_fn, + max_tokens_floor=max_tokens_floor) + if isinstance(prepared, dict): + replies.append(prepared) + continue + new_inputs, gen_kwargs = prepared + replies.append({}) + asks.setdefault(repr(sorted(gen_kwargs.items())), (gen_kwargs, []))[1].append( + (index, new_inputs)) + for gen_kwargs, members in asks.values(): + answers = cast("Model", model).try_generate_batch( + [new_inputs for _, new_inputs in members], **gen_kwargs) + for (index, _), answer in zip(members, answers): + replies[index] = ( + {"error": f"{type(answer).__name__}: {answer}"} + if isinstance(answer, Exception) else {"output": str(answer)} + ) + res.n_replayed += len(replayed) + share = (time.perf_counter() - started) / max(1, len(batch) - len(replayed)) + for index, ((request, case_id), reply) in enumerate(zip(batch, replies)): + if call_logger is not None: + try: + call_logger({ + "case_id": case_id, + "request": request, + "response": dict(reply), + "replayed_from_recorded_baseline": index in replayed, + "duration_sec": 0.0 if index in replayed else share, + }) + except Exception as exc: # logging must never break the bridge + logger.debug("fix_pipeline: call logger failed: %s", exc) + # Record the call for the gold-free consensus guard: was it the + # direct baseline (untouched prompt, no ops), and what did it answer? + case = case_by_id.get(case_id) if "output" in reply and case is not None: - supplied_prompt = request.get("prompt") - is_direct = _is_direct_request(request, case) signature = json.dumps( - { - "prompt": supplied_prompt, - "image_ops": request.get("image_ops") or [], - }, - sort_keys=True, + {"prompt": request.get("prompt"), + "image_ops": request.get("image_ops") or []}, + sort_keys=True, default=str, ) - with records_lock: - call_records.setdefault(case_id, []).append( - (is_direct, signature, str(reply.get("output", ""))) - ) - except (TypeError, ValueError, json.JSONDecodeError): - pass - return _send(reply) + call_records.setdefault(case_id, []).append( + (_is_direct_request(request, case), signature, str(reply["output"])) + ) + _send({**reply, "rid": request.get("rid")}) + + def _serve() -> None: + """Answer queued calls until the ``None`` that closes the session.""" + while True: + batch = [calls.get()] + while batch[-1] is not None: + try: + batch.append(calls.get(timeout=GATHER_SEC)) + except queue.Empty: + break + closing = batch[-1] is None + _answer([call for call in batch if call is not None]) + if closing: + return + server = threading.Thread(target=_serve, daemon=True) + server.start() try: for line in proc.stdout: # type: ignore[union-attr] stripped = line.strip() @@ -385,37 +407,31 @@ def _serve(raw: str, request: "dict[str, Any]", case_id: str) -> bool: res.error = f"model-call budget exhausted ({budget} calls)" proc.kill() break - raw = stripped[len(CALL_MARKER):] - # Selection-safety accounting runs on THIS (serial) reader - # thread before dispatch, so the per-case cap is deterministic - # under concurrency too; the reply itself may be serviced by - # the pool. + # Selection-safety accounting runs here, in arrival order, + # before the call is queued, so the per-case cap does not + # depend on how the calls are batched. try: - request = json.loads(raw) + request = json.loads(stripped[len(CALL_MARKER):]) case_id = str(request.get("case_id", "")) - # A plain direct call on a recorded case is answered from - # the record and never touches the model: free under the - # cap (in the live run AND the frozen control, so the - # same code is accounted identically in both). - if not _replayable_direct(request, case_by_id.get(case_id)): - calls_per_case[case_id] = calls_per_case.get(case_id, 0) + 1 - if ( - max_calls_per_case > 0 - and calls_per_case.get(case_id, 0) > max_calls_per_case - ): - res.error = ( - "selection-safety contract violated: more than " - f"{max_calls_per_case} model calls for case {case_id!r}" - ) - proc.kill() - break - except (TypeError, ValueError, json.JSONDecodeError): - request, case_id = {}, "" - if pool is not None: - pool.submit(_serve, raw, request, case_id) - else: - if not _serve(raw, request, case_id): - break + except (AttributeError, TypeError, ValueError): + continue # not a request: nothing to answer, nobody to route to + # A plain direct call on a recorded case is answered from the + # record and never touches the model: free under the cap (in + # the live run AND the frozen control, so the same code is + # accounted identically in both). + if not _replayable_direct(request, case_by_id.get(case_id)): + calls_per_case[case_id] = calls_per_case.get(case_id, 0) + 1 + if ( + max_calls_per_case > 0 + and calls_per_case.get(case_id, 0) > max_calls_per_case + ): + res.error = ( + "selection-safety contract violated: more than " + f"{max_calls_per_case} model calls for case {case_id!r}" + ) + proc.kill() + break + calls.put((request, case_id)) elif stripped.startswith(RESULT_MARKER): result_line = stripped[len(RESULT_MARKER):] elif stripped: @@ -427,10 +443,10 @@ def _serve(raw: str, request: "dict[str, Any]", case_id: str) -> bool: proc.kill() finally: watchdog.cancel() - if pool is not None: - # In-flight model calls finish on their own (the reply is dropped - # on a closed pipe); queued ones are cancelled. - pool.shutdown(wait=False, cancel_futures=True) + # The batch in flight finishes before this returns: the next candidate + # must not find the model still generating for this one. + calls.put(None) + server.join() if result_line is None and not timed_out.is_set(): # A judge-written pipeline sometimes gets the JSON payload right but @@ -587,23 +603,26 @@ def _answers_match(left: str, right: str) -> bool: return left_key == right_key -def _service_call( - raw: str, - case_by_id: "dict[str, Any]", +def _prepare_call( + req: "dict[str, Any]", + case: "Any", model: "Model | None", - inputs_cls: "type", enable_attend: bool = False, reply_fn: "Callable[[Any, str], str] | None" = None, max_tokens_floor: "int | None" = None, -) -> "dict[str, Any]": - """Handle one bridged model call; never raises (errors travel as JSON).""" +) -> "dict[str, Any] | tuple[Any, dict[str, Any]]": + """Turn one bridged call into its reply, or into what to ask the model. + + Returns the reply itself when the call needs no generation (an error, an + attention read, a ``reply_fn`` answer); otherwise ``(inputs, kwargs)`` for + the caller to batch. Never raises (errors travel as JSON). + """ import dataclasses + from evalrx.core.case import Inputs from evalrx.eval_agent.stages.fix.tools import _safe_generation_kwargs try: - req = json.loads(raw) - case = case_by_id.get(str(req.get("case_id", ""))) if case is None: return {"error": f"unknown case_id {req.get('case_id')!r}"} if req.get("op") == "attend": @@ -658,12 +677,10 @@ def _service_call( ): gen_kwargs["max_tokens"] = int(max_tokens_floor) # dataclasses.replace keeps .video/.audio (a bare Inputs(prompt=, - # image=) dropped them — the same modality bug run_pipeline had). + # image=) dropped them — the same modality bug run_pipelines had). if dataclasses.is_dataclass(inp) and not isinstance(inp, type): - new_inputs = dataclasses.replace(inp, prompt=str(prompt), image=image) - else: - new_inputs = inputs_cls(prompt=str(prompt), image=image) - return {"output": str(model.generate(new_inputs, **gen_kwargs))} + return dataclasses.replace(inp, prompt=str(prompt), image=image), gen_kwargs + return Inputs(prompt=str(prompt), image=image), gen_kwargs except Exception as exc: return {"error": f"{type(exc).__name__}: {exc}"} diff --git a/evalrx/eval_agent/stages/fix/proposal.py b/evalrx/eval_agent/stages/fix/proposal.py index 24bfa0ee..9e88fc3a 100644 --- a/evalrx/eval_agent/stages/fix/proposal.py +++ b/evalrx/eval_agent/stages/fix/proposal.py @@ -1153,7 +1153,7 @@ def _l2_candidates( # structural no-op. defaults = image_defaults if has_images else text_defaults # self_refine/least_to_most were only ever offered for text-only - # cases, even though run_pipeline already threads the case image + # cases, even though run_pipelines already threads the case image # through every call of a multi-call strategy (tools.py) -- # nothing about them is text-specific. On a binary/grounding task # (yes_no) the image transforms above are the right first lever; @@ -1177,7 +1177,7 @@ def _l2_candidates( # look would catch; self_consistency helps when greedy decoding # is stuck on one answer but the model's distribution actually # has support elsewhere. Majority-vote aggregation already - # exists in run_pipeline (tools.py, n_samples > 1) but had + # exists in run_pipelines (tools.py, n_samples > 1) but had # never been registered as a default candidate for any task. reasoning_defaults = [] if "self_refine" not in prior_names: diff --git a/evalrx/eval_agent/stages/fix/recorder.py b/evalrx/eval_agent/stages/fix/recorder.py index e88bc8ae..2ce92a60 100644 --- a/evalrx/eval_agent/stages/fix/recorder.py +++ b/evalrx/eval_agent/stages/fix/recorder.py @@ -16,7 +16,7 @@ from evalrx.agent_runtime.judge_call import Exchange from evalrx.core.case import CaseBatch from evalrx.core.model import Model - from evalrx.eval_agent.run_context import Trial + from evalrx.eval_agent.runlog.context import Trial from evalrx.eval_agent.stages.fix.types import FixOutcome logger = logging.getLogger(__name__) @@ -27,19 +27,25 @@ class FixRecorder: def __init__(self, run_logger: "Any | None" = None) -> None: self.run_logger = run_logger + self._outcomes = True @contextmanager - def muted(self) -> "Iterator[None]": - """Write nothing inside the block (the caller records a combined outcome).""" - run_logger, self.run_logger = self.run_logger, None + def without_outcome(self) -> "Iterator[None]": + """Record no ``fix`` outcome inside the block; the caller records one + that combines several searches. + + Every model and judge exchange is still logged: they are the only + record of what a candidate asked and what it got back. + """ + self._outcomes = False try: yield finally: - self.run_logger = run_logger + self._outcomes = True def outcome(self, outcome: "FixOutcome") -> None: """Record the stage outcome as a ``fix`` event.""" - if self.run_logger is None: + if self.run_logger is None or not self._outcomes: return try: self.run_logger.log_fix(outcome) @@ -146,7 +152,7 @@ def instrument(self, model: "Model", data: "CaseBatch", analyzer: str) -> "Model """Wrap *model* so every call is logged, when the run has a log.""" if self.run_logger is None: return model - from evalrx.eval_agent.model_instrumentation import InstrumentedModel + from evalrx.eval_agent.runlog.instrumentation import InstrumentedModel return InstrumentedModel( model, self.run_logger, stage="M5", diff --git a/evalrx/eval_agent/stages/fix/tools.py b/evalrx/eval_agent/stages/fix/tools.py index 2fdacfda..8909dd36 100755 --- a/evalrx/eval_agent/stages/fix/tools.py +++ b/evalrx/eval_agent/stages/fix/tools.py @@ -18,9 +18,12 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Callable, Optional +from evalrx.core.analyzer import Ask, run_probes from evalrx.core.model import Model if TYPE_CHECKING: + from collections.abc import Generator, Sequence + from evalrx.core.case import FailureCase logger = logging.getLogger(__name__) @@ -654,7 +657,7 @@ def to_dict(self) -> "dict[str, Any]": #: ``(step label, instruction prepended for that call)``. An empty instruction #: means the call sends the task prompt with nothing added. #: -#: Hoisted out of ``run_pipeline`` (which now formats from these) so that the +#: Hoisted out of the executor (which formats from these) so that the #: text a strategy actually sends can be shown rather than paraphrased. STRATEGY_CALLS: "dict[str, tuple[tuple[str, str], ...]]" = { "self_refine": ( @@ -785,40 +788,32 @@ def spec_changes_input(spec: PipelineSpec, case: "FailureCase") -> bool: return True # cannot prove it is a no-op — treat as applicable -def _run_strategy_once( - generate: "Callable[[str], str]", strategy: str, base_prompt: str -) -> str: - """One pass of a reviewed multi-call strategy; returns its final output.""" +def _strategy_steps(strategy: str, base_prompt: str) -> "Generator[str, str, str]": + """One pass of a reviewed multi-call strategy. + + Yields each prompt, is sent the model's answer to it, and returns the + pass's final output. + """ if strategy == "least_to_most": calls = STRATEGY_CALLS["least_to_most"] - decomposition = generate(calls[0][1] + "\n\n" + base_prompt) - return generate( + decomposition = yield calls[0][1] + "\n\n" + base_prompt + return (yield ( f"{calls[1][1]}\n\nOriginal task:\n" f"{base_prompt}\n\nDecomposition:\n{decomposition}" - ) - if strategy == "self_refine": - calls = STRATEGY_CALLS["self_refine"] - draft = generate(base_prompt) - feedback = generate( + )) + if strategy in ("self_refine", "chain_of_verification"): + calls = STRATEGY_CALLS[strategy] + review = "Feedback" if strategy == "self_refine" else "Checks" + draft = yield base_prompt + notes = yield ( f"{calls[1][1]}\n\n" f"Original task:\n{base_prompt}\n\nAttempt:\n{draft}" ) - return generate( + return (yield ( f"{calls[2][1]}\n\n" - f"Original task:\n{base_prompt}\n\nAttempt:\n{draft}\n\nFeedback:\n{feedback}" - ) - if strategy == "chain_of_verification": - calls = STRATEGY_CALLS["chain_of_verification"] - draft = generate(base_prompt) - checks = generate( - f"{calls[1][1]}\n\n" - f"Original task:\n{base_prompt}\n\nAttempt:\n{draft}" - ) - return generate( - f"{calls[2][1]}\n\n" - f"Original task:\n{base_prompt}\n\nAttempt:\n{draft}\n\nChecks:\n{checks}" - ) - return generate(base_prompt) + f"Original task:\n{base_prompt}\n\nAttempt:\n{draft}\n\n{review}:\n{notes}" + )) + return (yield base_prompt) def answer_key(output: str, pattern: str = "") -> str: @@ -857,107 +852,114 @@ def answer_key(output: str, pattern: str = "") -> str: return re.sub(r"\s+", " ", text.strip().lower()) -def run_pipeline( - model: "Model", - case: "FailureCase", - spec: PipelineSpec, - score_fn: "Callable[[FailureCase, str], Optional[bool]]", - capture: "dict[str, Any] | None" = None, - call_logger: "Callable[[dict[str, Any]], None] | None" = None, -) -> "Optional[bool]": - """Execute *spec* on one case; aggregate outputs before host-side scoring. +@dataclass +class PipelineRun: + """What a spec produced on one case, before scoring. + + ``winner`` is the aggregated answer (``None`` when every call failed or the + case could not be prepared); ``calls`` lists every model call as + ``{"inputs", "output", "error", "generation_kwargs"}``, in the order asked. + """ + + prompt: str = "" + outputs: "list[str]" = field(default_factory=list) + winner: "str | None" = None + calls: "list[dict[str, Any]]" = field(default_factory=list) + + +def run_pipelines( + model: "Model", cases: "Sequence[FailureCase]", spec: PipelineSpec +) -> "list[PipelineRun]": + """Execute *spec* on every case; one :class:`PipelineRun` per case, in order. ``n_samples`` applies to EVERY strategy: a multi-call strategy is run - ``n_samples`` times end-to-end and its final outputs vote (previously only - ``direct`` honoured ``n_samples`` — a judge's ``least_to_most, n_samples=3`` - silently ran once). Samples vote on an evaluator-declared final-answer key - when one is available, otherwise on the extracted final answer - (:func:`answer_key`). The scoring rubric is applied *after* aggregation, so - a pipeline cannot use the hidden gold answer to select its preferred - sample. Reviewed multi-call strategies are prompt-only and keep the - underlying model unchanged. Returns ``None`` when the case cannot be scored - (no rubric / all calls failed). - - *capture*, when a dict, receives ``{"prompt", "outputs", "winner", - "n_calls"}`` so the caller can persist WHAT the candidate produced (the - only way to tell a truncated answer from a wrong one after the fact). + ``n_samples`` times end-to-end and its final outputs vote. Each pass is a + probe, so one round of generation covers every case and every sample + (:func:`~evalrx.core.analyzer.run_probes`). Samples vote on an + evaluator-declared final-answer key when one is available, otherwise on the + extracted final answer (:func:`answer_key`). Nothing here sees a scoring + rubric: the caller scores ``winner`` after aggregation, so a pipeline + cannot use the hidden gold answer to select its preferred sample. Reviewed + multi-call strategies are prompt-only and keep the underlying model + unchanged. + + A case that cannot be prepared (an image op that raises) or whose calls all + fail keeps ``winner=None``; it never takes the other cases down with it. + """ + runs = [PipelineRun() for _ in cases] + probes: "list[Generator[Ask, list[Any], str]]" = [] + owners: "list[PipelineRun]" = [] + for run, case in zip(runs, cases): + try: + inp = case.inputs + image = getattr(inp, "image", None) + if spec.image_ops: + image = apply_image_ops(image, spec.image_ops, case=case) + # safe_format, not str.format: a judge-written template legitimately + # contains braces (LaTeX, sets like "{1,2,3}", JSON). + # {original_prompt} lets an EDIT candidate (recursive rounds) REPLACE + # the previously deployed template instead of wrapping its rendered + # output. + context = {"prompt": str(getattr(inp, "prompt", ""))} + original = (getattr(case, "metadata", {}) or {}).get("original_prompt") + if original: + context["original_prompt"] = str(original) + run.prompt = safe_format(spec.prompt_template, context) + except Exception as exc: + logger.debug("run_pipelines: could not prepare %s: %s", case.id, exc) + continue + for _ in range(max(1, spec.n_samples)): + probes.append(_one_pass(run, inp, image, spec)) + owners.append(run) + for run, output in zip(owners, run_probes(model, probes, tolerant=True)): + if output: + run.outputs.append(output) + for run, case in zip(runs, cases): + if run.outputs: + run.winner = _winner(case, spec, run.outputs) + return runs + + +def _one_pass( + run: PipelineRun, inp: Any, image: Any, spec: PipelineSpec +) -> "Generator[Ask, list[Any], str]": + """One sample of *spec*'s strategy on one case; returns its final output. + + A failed call reaches the strategy as an empty answer and is recorded on + the run; the pass carries on, as a strategy's later step may still answer. """ import dataclasses from evalrx.core.case import Inputs - inp = getattr(case, "inputs", None) - prompt = str(getattr(inp, "prompt", "")) if inp is not None else "" - image = getattr(inp, "image", None) if inp is not None else None - if spec.image_ops: - image = apply_image_ops(image, spec.image_ops, case=case) - # safe_format, not str.format: a judge-written template legitimately - # contains braces (LaTeX, sets like "{1,2,3}", JSON) — str.format raised - # KeyError OUTSIDE the per-case try and took down a whole fix stage - # (qwen3.5-2b/bbh_tracking7 run8: template with "{1,2,3,4,5,6,7}"). - # {original_prompt} lets an EDIT candidate (recursive rounds) REPLACE the - # previously deployed template instead of wrapping its rendered output. - template_context = {"prompt": prompt} - original = (getattr(case, "metadata", {}) or {}).get("original_prompt") - if original: - template_context["original_prompt"] = str(original) - base_prompt = safe_format(spec.prompt_template, template_context) - n_calls = 0 - - def generate(text: str) -> str: - nonlocal n_calls - import time - - n_calls += 1 - started = time.perf_counter() - new_inputs = None + steps = _strategy_steps(spec.strategy, run.prompt) + text = next(steps) + while True: + # dataclasses.replace keeps .video/.audio (a bare Inputs(prompt=, + # image=) dropped them, so every strategy was inapplicable on any + # non-image case). Only `image` is overridden: spec.image_ops may have + # rewritten it. + new_inputs = ( + dataclasses.replace(inp, prompt=text, image=image) + if dataclasses.is_dataclass(inp) and not isinstance(inp, type) + else Inputs(prompt=text, image=image) + ) + (answer,) = yield Ask([new_inputs], spec.generation_kwargs) + failed = isinstance(answer, Exception) + run.calls.append({ + "inputs": new_inputs, + "output": None if failed else str(answer), + "error": str(answer) if failed else None, + "generation_kwargs": dict(spec.generation_kwargs), + }) try: - # dataclasses.replace(inp, ...), not a bare Inputs(prompt=..., - # image=...): the bare form silently dropped .video/.audio, so - # every strategy (least_to_most/self_refine/chain_of_verification) - # was unconditionally inapplicable on any non-image FailureCase -- - # generate() raising on the missing required modality field, - # caught below, every call returning "" (all outputs empty -> - # run_pipeline returns None -> unscoreable for every case). Only - # `image` is deliberately overridden (it may have been rewritten - # by spec.image_ops just above); no fallback needed for inp is - # None since FailureCase.inputs is never optional in practice. - new_inputs = ( - dataclasses.replace(inp, prompt=text, image=image) - if inp is not None - else Inputs(prompt=text, image=image) - ) - output = str(model.generate(new_inputs, **spec.generation_kwargs)) - if call_logger is not None: - call_logger({ - "inputs": new_inputs, "output": output, "error": None, - "duration_sec": time.perf_counter() - started, - "generation_kwargs": dict(spec.generation_kwargs), - }) - return output - except Exception as exc: - logger.debug("run_pipeline: generate failed on %s: %s", case.id, exc) - if call_logger is not None: - try: - call_logger({ - "inputs": new_inputs or {"prompt": text}, "output": None, - "error": str(exc), "duration_sec": time.perf_counter() - started, - "generation_kwargs": dict(spec.generation_kwargs), - }) - except Exception as log_exc: - logger.debug("run_pipeline: call logger failed: %s", log_exc) - return "" - - outputs = [ - _run_strategy_once(generate, spec.strategy, base_prompt) - for _ in range(max(1, spec.n_samples)) - ] - outputs = [output for output in outputs if output] - if capture is not None: - capture.update({"prompt": base_prompt, "outputs": list(outputs), - "winner": None, "n_calls": n_calls}) - if not outputs: - return None + text = steps.send("" if failed else str(answer)) + except StopIteration as done: + return str(done.value) + + +def _winner(case: "FailureCase", spec: PipelineSpec, outputs: "list[str]") -> str: + """The answer most samples agree on, subject to the baseline-override gate.""" # Keep the first original response for the winning normalized key; stable # tie-breaking avoids injecting a score-dependent preference. pattern = spec.output_key_pattern or str( @@ -966,23 +968,19 @@ def generate(text: str) -> str: grouped: "dict[str, list[str]]" = {} for output in outputs: grouped.setdefault(answer_key(output, pattern), []).append(output) - winner = max(grouped.values(), key=len)[0] min_support = max(0, int(spec.baseline_override_min_support)) - if min_support: - baseline = str(getattr(case, "observed", "") or "") - baseline_key = answer_key(baseline, pattern) - alternatives = [group for key, group in grouped.items() if key != baseline_key] - best_alternative = max(alternatives, key=len) if alternatives else [] - # Any enhanced support for the baseline is evidence against a safe - # override. The fallback is the exact recorded output, not a host-side - # rewrite, so this gate never solves the benchmark task itself. - if baseline_key in grouped or len(best_alternative) < min_support: - winner = baseline - else: - winner = best_alternative[0] - if capture is not None: - capture["winner"] = winner - return score_to_bool(score_fn(case, winner)) + if not min_support: + return max(grouped.values(), key=len)[0] + baseline = str(getattr(case, "observed", "") or "") + baseline_key = answer_key(baseline, pattern) + alternatives = [group for key, group in grouped.items() if key != baseline_key] + best_alternative = max(alternatives, key=len) if alternatives else [] + # Any enhanced support for the baseline is evidence against a safe + # override. The fallback is the exact recorded output, not a host-side + # rewrite, so this gate never solves the benchmark task itself. + if baseline_key in grouped or len(best_alternative) < min_support: + return baseline + return best_alternative[0] class SpecPipelineModel(Model): @@ -1020,18 +1018,17 @@ def __init__(self, model: "Model", spec: "PipelineSpec | dict[str, Any]") -> Non self.modalities = getattr(model, "modalities", frozenset({"text"})) def generate(self, inputs: Any, **kwargs: Any) -> str: + return self.generate_batch([inputs])[0] + + def generate_batch(self, inputs: "Sequence[Any]", **kwargs: Any) -> "list[str]": from evalrx.core.case import FailureCase, Inputs - if not hasattr(inputs, "prompt"): - inputs = Inputs(prompt=str(inputs)) - case = FailureCase(id="spec_baseline", inputs=inputs) - capture: "dict[str, Any]" = {} - run_pipeline(self.inner_model, case, self.spec, lambda _case, _out: None, capture) - winner = capture.get("winner") - if winner is None: - outputs = capture.get("outputs") or [] - winner = outputs[0] if outputs else "" - return str(winner) + cases = [ + FailureCase(id="spec_baseline", + inputs=item if hasattr(item, "prompt") else Inputs(prompt=str(item))) + for item in inputs + ] + return [str(run.winner or "") for run in run_pipelines(self.inner_model, cases, self.spec)] def forward(self, inputs: Any, capture: Any, spec: Any = None): raise NotImplementedError("SpecPipelineModel is a generate-only deployed pipeline") diff --git a/evalrx/eval_agent/stages/fix/types.py b/evalrx/eval_agent/stages/fix/types.py index b574b63d..0cd823c7 100644 --- a/evalrx/eval_agent/stages/fix/types.py +++ b/evalrx/eval_agent/stages/fix/types.py @@ -9,7 +9,7 @@ if TYPE_CHECKING: from evalrx.core.case import FailureCase - from evalrx.eval_agent.run_context import Trial + from evalrx.eval_agent.runlog.context import Trial @dataclass @@ -41,7 +41,7 @@ class FixCandidate: cases it returns True for — a *conditional* fix. When ``None``, applicability is inferred structurally (a spec that does not change a case's input is a no-op there). - trial: Optional :class:`~evalrx.eval_agent.run_context.Trial` + trial: Optional :class:`~evalrx.eval_agent.runlog.context.Trial` — when set (a ``RunContext`` is in play), this candidate's code, the sandbox it ran in, and its record/result all live under ``trial.root`` instead of being scattered diff --git a/evalrx/eval_agent/stages/fix/validation.py b/evalrx/eval_agent/stages/fix/validation.py index 4c698838..784c5b9a 100644 --- a/evalrx/eval_agent/stages/fix/validation.py +++ b/evalrx/eval_agent/stages/fix/validation.py @@ -20,7 +20,7 @@ from evalrx.eval_agent.stages.fix.tools import ( PipelineSpec, _safe_generation_kwargs, - run_pipeline, + run_pipelines, safe_format, score_to_bool, spec_changes_input, @@ -101,7 +101,6 @@ def __init__( recorder: FixRecorder, coder: PipelineCoder, progress: "Callable[..., None]", - concurrency: int = 1, baseline_repeats: int = 1, candidate_repeats: int = 1, finetune_pool: "Any | None" = None, @@ -110,13 +109,14 @@ def __init__( self.recorder = recorder self.coder = coder self._progress = progress - self.concurrency = concurrency self.baseline_repeats = baseline_repeats self.candidate_repeats = candidate_repeats self.finetune_pool = finetune_pool # case id -> the final output that was scored, filled while a # candidate runs and moved onto its FixValidation. self._captured: "dict[str, str]" = {} + # (model, what was asked, baseline) for every baseline measured so far. + self._baselines: "list[tuple[Model, tuple[Any, ...], Baseline]]" = [] @property def rates_mode(self) -> bool: @@ -124,7 +124,30 @@ def rates_mode(self) -> bool: return self.baseline_repeats > 1 or self.candidate_repeats > 1 def baseline(self, model: "Model", data: "CaseBatch") -> Baseline: - """Measure the unmodified baseline as a per-case PASS RATE. + """The unmodified model's per-case PASS RATE on *data*, measured once. + + A search climbs one tier at a time over the same cases, and its + candidates are one family that e-BH corrects together, so they all pair + against the same baseline samples; re-drawing them per tier cost 64 + generations each time and gave each tier a different baseline. + """ + # What the samples depend on besides the model: the prompt asked and the + # recorded answer that counts as sample one. A deployed template keeps + # the case ids and changes the prompts, so ids alone would not do. + asked = tuple( + (case.id, str(getattr(case.inputs, "prompt", "")), + None if case.observed is None else str(case.observed)) + for case in data + ) + for seen_model, seen_asked, measured in self._baselines: + if seen_model is model and seen_asked == asked: + return measured + measured = self._measure_baseline(model, data) + self._baselines.append((model, asked, measured)) + return measured + + def _measure_baseline(self, model: "Model", data: "CaseBatch") -> Baseline: + """Draw the baseline samples and summarise them per case. Returns the modal per-case scores, the per-case rates and sample counts (for the paired-rates test) and the unstable case ids. @@ -134,21 +157,23 @@ def baseline(self, model: "Model", data: "CaseBatch") -> Baseline: supposedly paired comparison depend on endpoint non-determinism and waste a call per case. Cases without an ``observed`` are generated once. - * ``baseline_repeats == k > 1`` — the frozen sample counts as sample 1 - and ``k-1`` fresh samples are drawn (all ``k`` fresh when there is no - frozen one), so each case gets a rate in ``{0, 1/k, ..., 1}``. A case - with ``0 < rate < 1`` is *unstable* (its baseline answer is a coin); - it is REPORTED, not dropped: the paired-rates test weighs it by how - much a candidate moves its rate, which is the honest accounting for - a stochastic model — dropping it removed exactly the cases a - variance-reduction scaffold repairs. + * ``baseline_repeats == k > 1`` — ``k`` fresh samples, so each case gets + a rate in ``{0, 1/k, ..., 1}``. The recorded answer is not one of + them: it is the answer the case was labelled by (and, under a + majority label, picked to agree with it), so counting it pulls the + rate toward the label wherever cases were chosen by label. + A case with ``0 < rate < 1`` is *unstable* (its baseline answer is a + coin); it is REPORTED, not dropped: the paired-rates test weighs it + by how much a candidate moves its rate, which is the honest + accounting for a stochastic model — dropping it removed exactly the + cases a variance-reduction scaffold repairs. """ k = max(1, int(self.baseline_repeats)) samples: "dict[str, list[bool]]" = {c.id: [] for c in data} need: "list[tuple[Any, int]]" = [] for case in data: observed = getattr(case, "observed", None) - if observed is not None: + if k == 1 and observed is not None: s0 = score_to_bool(self.score(case, str(observed))) if s0 is not None: samples[case.id].append(bool(s0)) @@ -180,36 +205,32 @@ def _sample_baseline( need: "list[tuple[Any, int]]", samples: "dict[str, list[bool]]", ) -> None: - """Draw the missing fresh baseline samples (threaded like candidates).""" + """Draw the missing fresh baseline samples, all in one batch.""" jobs = [case for case, n in need for _ in range(n)] - - def one(case: Any) -> "tuple[str, Optional[bool]]": - started = time.perf_counter() - try: - output = str(model.generate(case.inputs)) - except Exception as exc: - logger.debug("FixAgent: baseline generate failed on %s: %s", case.id, exc) - self.recorder.target_exchange( - "fresh_baseline", case.inputs, None, case_id=case.id, - error=str(exc), duration_sec=time.perf_counter() - started, - ) - return case.id, None + answers, share = self._generate(model, [case.inputs for case in jobs]) + for case, answer in zip(jobs, answers): + failed = isinstance(answer, Exception) self.recorder.target_exchange( - "fresh_baseline", case.inputs, output, case_id=case.id, - duration_sec=time.perf_counter() - started, + "fresh_baseline", case.inputs, None if failed else str(answer), + case_id=case.id, error=str(answer) if failed else None, duration_sec=share, ) - return case.id, score_to_bool(self.score(case, output)) - - if self.concurrency > 1 and len(jobs) > 1: - from concurrent.futures import ThreadPoolExecutor - - with ThreadPoolExecutor(max_workers=self.concurrency) as pool: - results = list(pool.map(one, jobs)) - else: - results = [one(case) for case in jobs] - for cid, s in results: + if failed: + logger.debug("FixAgent: baseline generate failed on %s: %s", case.id, answer) + continue + s = score_to_bool(self.score(case, str(answer))) if s is not None: - samples[cid].append(bool(s)) + samples[case.id].append(bool(s)) + + @staticmethod + def _generate( + model: "Model", inputs: "list[Any]", **kwargs: Any + ) -> "tuple[list[str | Exception], float]": + """One batch of answers and each call's share of the time it took.""" + if not inputs: + return [], 0.0 + started = time.perf_counter() + answers = model.try_generate_batch(inputs, **kwargs) + return answers, (time.perf_counter() - started) / len(inputs) def matched_baseline( self, candidate: FixCandidate, model: "Model", data: "CaseBatch" @@ -228,45 +249,25 @@ def matched_baseline( executor = getattr(model, executor_name, None) if not callable(executor): return {case.id: None for case in data} - - def guarded(case: "FailureCase") -> "tuple[str, Optional[bool]]": + scores: "dict[str, Optional[bool]]" = {} + for case in data: try: - output = executor(case.inputs) - return case.id, score_to_bool(self.score(case, str(output))) + scores[case.id] = score_to_bool(self.score(case, str(executor(case.inputs)))) except Exception as exc: - logger.warning( - "FixAgent: matched baseline %s failed on case %s: %s", - executor_name, - case.id, - exc, - ) - return case.id, None - - cases = list(data) - if self.concurrency > 1 and len(cases) > 1: - from concurrent.futures import ThreadPoolExecutor - - with ThreadPoolExecutor(max_workers=self.concurrency) as pool: - return dict(pool.map(guarded, cases)) - return dict(guarded(case) for case in cases) + logger.warning("FixAgent: matched baseline %s failed on case %s: %s", + executor_name, case.id, exc) + scores[case.id] = None + return scores # -- per-candidate-kind execution ---------------------------------------- # - # A candidate kind either runs per case (a strategy: one model call chain - # per case, threaded by scores()) or as a batch (its own executor over the - # whole batch). Adding a kind is one method plus one entry below. - - def strategy( - self, candidate: FixCandidate - ) -> "Callable[[Model, FailureCase], Optional[bool]]": - """Compile a candidate to a per-case success function.""" - build = { - "registered_repair": self._registered_repair_strategy, - "visual_search": self._visual_search_strategy, - "detector_visual_search": self._visual_search_strategy, - "template": self._template_strategy, - }.get(candidate.kind, self._spec_strategy) - return build(candidate) + # A candidate kind runs one of three ways. Adding a kind is one method plus + # one entry in scores(): + # * whole batch, own executor — coded pipelines, internals, fine-tunes; + # * prompts to the model — templates and specs: every case's calls + # go to the model as batches, which the backend runs its own way; + # * a model method per case — registered repairs and visual search. + # These hook the model while they generate, so they run one at a time. def scores( self, @@ -286,43 +287,45 @@ def scores( batch = runners.get(candidate.kind) if batch is not None: return batch(candidate, model, data, max_tokens_floor=max_tokens_floor) - strategy = self.strategy(candidate) cases = list(data) - from threading import Lock - - progress_lock = Lock() - completed = 0 + scores: "dict[str, Optional[bool]]" = {case.id: None for case in cases} + # Do not execute a conditional repair outside its registered + # population. Validation already excludes those cases, but generating + # for them wastes compute and can advance a stochastic model before + # the applicable cases are sampled. + applicable = [case for case in cases if applies(candidate, case)] + per_case = self._PER_CASE.get(candidate.kind) + if per_case is not None: + scores.update(self._run_per_case(candidate, per_case, model, applicable)) + elif candidate.kind == "template": + scores.update(self._run_template(candidate, model, applicable)) + else: + scores.update(self._run_spec(candidate, model, applicable)) + self._progress("candidate_cases", candidate=candidate.name, + completed=len(cases), total=len(cases)) + return scores - def guarded(case: "FailureCase") -> "tuple[str, Optional[bool]]": - nonlocal completed - # One case's failure (a template that cannot render, an adapter - # error) scores None for THAT case; it must never abort the whole - # candidate — let alone the fix stage. + def _run_per_case( + self, + candidate: FixCandidate, + method: str, + model: "Model", + cases: "list[FailureCase]", + ) -> "dict[str, Optional[bool]]": + """One model-method call per case, in order.""" + strategy = getattr(self, method)(candidate) + scores: "dict[str, Optional[bool]]" = {} + for done, case in enumerate(cases, 1): + # One case's failure (an adapter error) scores None for THAT case; + # it must never abort the whole candidate — let alone the fix stage. try: - # Do not execute a conditional repair outside its registered - # population. Validation already excludes those cases, but - # generating for them wastes compute and can advance a - # stochastic model before the applicable cases are sampled. - if not applies(candidate, case): - return case.id, None - return case.id, strategy(model, case) + scores[case.id] = strategy(model, case) except Exception as exc: logger.warning("FixAgent: %s failed on case %s: %s", candidate.name, case.id, exc) - return case.id, None - finally: - with progress_lock: - completed += 1 - if completed == 1 or completed % 10 == 0 or completed == len(cases): - self._progress("candidate_cases", candidate=candidate.name, - completed=completed, total=len(cases)) - - if self.concurrency > 1 and len(cases) > 1: - from concurrent.futures import ThreadPoolExecutor - - with ThreadPoolExecutor(max_workers=self.concurrency) as pool: - results = list(pool.map(guarded, cases)) - return dict(results) - return dict(guarded(case) for case in cases) + if done == 1 or done % 10 == 0: + self._progress("candidate_cases", candidate=candidate.name, + completed=done, total=len(cases)) + return scores def _registered_repair_strategy( self, candidate: FixCandidate @@ -390,78 +393,85 @@ def visual_search(model: "Model", case: "FailureCase") -> "Optional[bool]": return visual_search - def _template_strategy( - self, candidate: FixCandidate - ) -> "Callable[[Model, FailureCase], Optional[bool]]": + #: kind -> the method that compiles it to a per-case model-method call + _PER_CASE = { + "registered_repair": "_registered_repair_strategy", + "visual_search": "_visual_search_strategy", + "detector_visual_search": "_visual_search_strategy", + } + + def _run_template( + self, candidate: FixCandidate, model: "Model", cases: "list[FailureCase]" + ) -> "dict[str, Optional[bool]]": + """An L1 prompt template: one rewritten prompt per case, asked as one batch.""" template = candidate.payload["prompt_template"] gen_kwargs = _safe_generation_kwargs(candidate.payload.get("generation_kwargs")) - - def l1(model: "Model", case: "FailureCase") -> "Optional[bool]": - inp = case.inputs - metadata = getattr(case, "metadata", {}) or {} - template_context = {str(key): value for key, value in metadata.items()} - template_context["prompt"] = str(getattr(inp, "prompt", "")) - template_context.setdefault("failure_axis", "the relevant visual evidence") - # Inside the try, not before it: rendering the template is as - # capable of failing as generating from it, and a single bad - # case must score None rather than abort the whole validation. - started = time.perf_counter() + metadata = {"generation_kwargs": gen_kwargs, "candidate": candidate.name} + asked: "list[tuple[FailureCase, Any]]" = [] + for case in cases: + context = {str(k): v for k, v in (getattr(case, "metadata", {}) or {}).items()} + context["prompt"] = str(getattr(case.inputs, "prompt", "")) + context.setdefault("failure_axis", "the relevant visual evidence") + # Rendering the template is as capable of failing as generating + # from it: a single bad case scores None, the rest still run. try: - # dataclasses.replace, not a bare Inputs(prompt=..., image=...): - # that silently dropped .video/.audio, so every L1 candidate was - # unconditionally inapplicable (generate() raising on the - # missing required modality field, caught below, scored as - # None for every case) on any non-image FailureCase. - new_inputs = dataclasses.replace( - inp, prompt=safe_format(template, template_context) - ) - output = str(model.generate(new_inputs, **gen_kwargs)) - self.recorder.target_exchange( - "template_candidate", new_inputs, output, case_id=case.id, - duration_sec=time.perf_counter() - started, - metadata={"generation_kwargs": gen_kwargs, "candidate": candidate.name}, - ) - self._record_output(case.id, output) - return score_to_bool(self.score(case, output)) + # dataclasses.replace keeps .video/.audio; a bare + # Inputs(prompt=..., image=...) dropped them. + rendered = dataclasses.replace(case.inputs, prompt=safe_format(template, context)) except Exception as exc: self.recorder.target_exchange( - "template_candidate", locals().get("new_inputs", inp), None, - case_id=case.id, error=str(exc), - duration_sec=time.perf_counter() - started, - metadata={"generation_kwargs": gen_kwargs, "candidate": candidate.name}, + "template_candidate", case.inputs, None, case_id=case.id, + error=str(exc), metadata=metadata, ) - return None - - return l1 + continue + asked.append((case, rendered)) + answers, share = self._generate(model, [inputs for _, inputs in asked], **gen_kwargs) + scores: "dict[str, Optional[bool]]" = {} + for (case, rendered), answer in zip(asked, answers): + failed = isinstance(answer, Exception) + self.recorder.target_exchange( + "template_candidate", rendered, None if failed else str(answer), + case_id=case.id, error=str(answer) if failed else None, + duration_sec=share, metadata=metadata, + ) + if not failed: + self._record_output(case.id, answer) + scores[case.id] = self._score(candidate, case, str(answer)) + return scores - def _spec_strategy( - self, candidate: FixCandidate - ) -> "Callable[[Model, FailureCase], Optional[bool]]": + def _run_spec( + self, candidate: FixCandidate, model: "Model", cases: "list[FailureCase]" + ) -> "dict[str, Optional[bool]]": + """A declarative pipeline: every case's passes advance together.""" spec = PipelineSpec.from_dict(candidate.payload) if spec is None: # already validated at proposal time; belt and braces - return lambda model, case: None - - def declarative(model: "Model", case: "FailureCase") -> "Optional[bool]": - capture: "dict[str, Any]" = {} - result = run_pipeline( - model, case, spec, self.score, capture=capture, - call_logger=lambda record: self.recorder.target_exchange( - "declarative_pipeline", record.get("inputs"), record.get("output"), - case_id=case.id, error=record.get("error"), - duration_sec=record.get("duration_sec"), - metadata={ - "candidate": candidate.name, - "generation_kwargs": record.get("generation_kwargs") or {}, - }, - ), - ) - winner = capture.get("winner") - if winner is None and capture.get("outputs"): - winner = capture["outputs"][0] - self._record_output(case.id, winner) - return result + return {} + started = time.perf_counter() + runs = run_pipelines(model, cases, spec) + n_calls = sum(len(run.calls) for run in runs) + share = (time.perf_counter() - started) / max(1, n_calls) + scores: "dict[str, Optional[bool]]" = {} + for case, run in zip(cases, runs): + for call in run.calls: + self.recorder.target_exchange( + "declarative_pipeline", call["inputs"], call["output"], + case_id=case.id, error=call["error"], duration_sec=share, + metadata={"candidate": candidate.name, + "generation_kwargs": call["generation_kwargs"]}, + ) + if run.winner is not None: + self._record_output(case.id, run.winner) + scores[case.id] = self._score(candidate, case, run.winner) + return scores - return declarative + def _score(self, candidate: FixCandidate, case: "FailureCase", output: str) -> "Optional[bool]": + """Score one answer; a rubric that raises scores None for that case.""" + try: + return score_to_bool(self.score(case, output)) + except Exception as exc: + logger.warning("FixAgent: %s could not be scored on case %s: %s", + candidate.name, case.id, exc) + return None def _run_primitive( self, candidate: FixCandidate, model: "Model", data: "CaseBatch", **_: Any @@ -582,7 +592,7 @@ def validate( self._captured = {} if isinstance(candidate.payload, dict): v.exec_error = str(candidate.payload.get("exec_error", "") or "") - # Baseline rates: measured by baseline() (frozen sample + k-1 fresh); + # Baseline rates: measured by baseline() (k fresh samples per case); # a Baseline built from bare booleans carries 0/1 rates. matched_baseline = self.matched_baseline(candidate, model, data) base_rates: "dict[str, Optional[float]]" = {} diff --git a/evalrx/eval_agent/stages/hypothesis_tester.py b/evalrx/eval_agent/stages/hypothesis_tester.py index f86f2c3f..9a3b48f7 100755 --- a/evalrx/eval_agent/stages/hypothesis_tester.py +++ b/evalrx/eval_agent/stages/hypothesis_tester.py @@ -529,10 +529,7 @@ def _select_results( 3. **shared** — all signal tools as shared evidence (historical aggregated-signal behaviour). """ - signal_res = [ - r for r in stats_results - if r.ok and r.tool in _SIGNAL_TOOLS and r.effect is not None - ] + signal_res = _signal_results(stats_results) global_res = [r for r in stats_results if r.ok and r.tool in _GLOBAL_TOOLS] def _tool_text(r: "StatsToolResult") -> str: @@ -855,6 +852,31 @@ def _identifiers(text: str) -> set[str]: return {m.group(0) for m in _IDENT_RE.finditer(str(text or "").lower())} +def _signal_results(stats_results: "list[StatsToolResult]") -> "list[StatsToolResult]": + """The M2 results a hypothesis can be judged on: one signal, with an effect.""" + return [r for r in stats_results + if r.ok and r.tool in _SIGNAL_TOOLS and r.effect is not None] + + +def testable_signals(stats_results: "list[StatsToolResult]") -> list[str]: + """The ``analyzer.signal`` keys M4 has a result to judge a hypothesis on.""" + return list(dict.fromkeys(filter(None, map(_tool_signal, _signal_results(stats_results))))) + + +def unmeasured_identifiers(test_design: str, stats_results: "list[StatsToolResult]") -> set[str]: + """The identifiers *test_design* names when M2 measured none of them. + + Empty when the design names no identifier, or when at least one is a + measured signal or its analyzer: the same reading :meth:`_route` uses to + decide the design is unmet, available to M3 before the hypothesis is filed. + """ + named = _identifiers(test_design) + measured: set[str] = set() + for result in _signal_results(stats_results): + measured |= _tool_ids(result, level="signal") | _tool_ids(result, level="analyzer") + return set() if named & measured else named + + def _signal_keywords(text: str) -> set[str]: """Non-generic 4+ letter words of *text* (for word-level routing).""" return _keywords(text) - _GENERIC_KW diff --git a/evalrx/eval_agent/stages/probe_agent.py b/evalrx/eval_agent/stages/probe_agent.py index 06bb0afc..c8bd3cab 100755 --- a/evalrx/eval_agent/stages/probe_agent.py +++ b/evalrx/eval_agent/stages/probe_agent.py @@ -45,6 +45,7 @@ import logging import re import subprocess +import time import warnings from concurrent.futures import ThreadPoolExecutor, as_completed from typing import TYPE_CHECKING, Any @@ -85,7 +86,8 @@ class ProbeAgent: catalog to select analyzers dynamically. runner: Executes direct (non-Docker) runs. Defaults to a fresh ``ExperimentRunner()``. - max_analyzers: Cap on analyzers per cycle. + max_analyzers: Cap on analyzers per cycle (default 6; ``None`` for + no cap). analyzer_overrides: Pre-instantiated analyzers for those requiring mandatory constructor arguments. use_docker: When ``True``, black-box-compatible analyzers are @@ -94,9 +96,13 @@ class ProbeAgent: docker_timeout: Seconds before a Docker run is killed. model_env_var: Name of the env var inside Docker that carries the API key for the containerised model. - max_workers: Maximum parallel black-box analyzers. Use 1 to run - all analyzers on the calling thread for a shared - local model. + max_workers: Maximum Docker-mode analyzers running at once + (*use_docker*). In-process analyzers always run one + at a time; the model's backend batches their calls. + time_budget_sec: Wall-clock budget for one :meth:`probe` call + (default 1800; 0 for no limit). An analyzer that has + not started when it is spent is skipped and named in + the selection rationale. """ def __init__( @@ -104,7 +110,7 @@ def __init__( probe: StrategyProbe | None = None, judge: "Judge | None" = None, runner: ExperimentRunner | None = None, - max_analyzers: int | None = None, + max_analyzers: int | None = 6, analyzer_overrides: dict[str, "Analyzer"] | None = None, use_docker: bool = False, docker_image: str = "evalrx:latest", @@ -118,10 +124,15 @@ def __init__( run_logger: "Any | None" = None, max_cases_per_analyzer: int = 0, max_workers: int = 8, + time_budget_sec: float = 1800.0, ) -> None: if max_workers < 1: raise ValueError("max_workers must be positive") self.max_workers = max_workers + #: Wall-clock budget for one probe() call; 0 = no limit. An analyzer + #: that has not started when it runs out is skipped and named in the + #: selection rationale, so a slow model costs evidence, not hours. + self.time_budget_sec = float(time_budget_sec or 0.0) self.selector = probe or StrategyProbe() self.judge = judge self.runner = runner or ExperimentRunner() @@ -217,9 +228,9 @@ def probe( :class:`~evalrx.eval_agent.probe.StrategyProbe` with the optional *hint_failure_modes* list for priority-boosting. - Black-box analyzers use a ``ThreadPoolExecutor`` when ``max_workers`` - exceeds 1. White-box analyzers, and all probes with ``max_workers=1``, - run sequentially on the calling thread. + Analyzers run one at a time on the calling thread; each sends its + questions to the model in batches. With ``use_docker``, black-box + analyzers run in containers, up to ``max_workers`` at once. Sets :attr:`last_schema` with the selection rationale so callers can inspect which analyzers ran and why without changing the return type. @@ -281,7 +292,8 @@ def probe( ] names = [n for n in names if n not in filtered] else: - names, filtered = self._filter_applicable_names(names, model, data) + names, filtered = self._filter_applicable_names( + names, model, data, named=analyzers is not None) if filtered: rationale += f" Filtered inapplicable analyzer(s): {', '.join(filtered)}." @@ -301,24 +313,36 @@ def probe( tasks.append((name, analyzer)) results: dict[str, "Result"] = {} + started = time.monotonic() + out_of_time: list[str] = [] + self._progress(f"{len(tasks)} analyzer(s) on {len(data)} case(s): " + + ", ".join(name for name, _ in tasks)) def _run_one(name: str, analyzer: "Analyzer") -> tuple[str, "Result | None"]: + if self.time_budget_sec and time.monotonic() - started > self.time_budget_sec: + out_of_time.append(name) + self._progress(f"{name}: skipped, the {self.time_budget_sec:.0f}s budget is spent") + return name, None cls = type(analyzer) subset = self._cap_cases(name, analyzer, data) + began = time.monotonic() if self.use_docker and _is_blackbox_compatible(cls): - return name, self._run_in_docker(name, analyzer, subset) - return name, self._run_direct(analyzer, model, subset) - - # White-box analyzers do GPU forward passes on the SHARED local model; - # running them in threads races on the model (accelerate device_map - # hooks are not thread-safe → meta-tensor/dtype errors) and stacks - # transient activations until the GPU OOMs. Only black-box analyzers - # (GENERATE/LOGPROBS, possibly Dockerised) may parallelise when the - # caller's backend supports concurrent requests. - parallel = [(n, a) for n, a in tasks if _is_blackbox_compatible(type(a))] - serial = [(n, a) for n, a in tasks if not _is_blackbox_compatible(type(a))] - if self.max_workers == 1: - parallel, serial = [], tasks + result = self._run_in_docker(name, analyzer, subset) + else: + result = self._run_direct(analyzer, model, subset) + self._progress(f"{name}: {'done' if result is not None else 'no result'} " + f"({time.monotonic() - began:.1f}s)") + return name, result + + # In-process analyzers run one at a time on the calling thread: they + # share the model, whose backend already answers each analyzer's + # questions as a batch (padded batches locally, concurrent requests + # over an API). Running analyzers in threads on top of that would + # multiply the requests in flight, and races a local model's hooks. + # Only Docker-mode analyzers, each in its own container, run in parallel. + in_docker = self.use_docker and self.max_workers > 1 + parallel = [(n, a) for n, a in tasks if in_docker and _is_blackbox_compatible(type(a))] + serial = [(n, a) for n, a in tasks if (n, a) not in parallel] def _record(name: str, result, exc=None) -> None: if exc is not None: @@ -336,7 +360,7 @@ def _record(name: str, result, exc=None) -> None: _record(name, result) except Exception as exc: _record(futures[future], None, exc) - for name, analyzer in serial: # shared local model: one probe at a time + for name, analyzer in serial: try: _, result = _run_one(name, analyzer) _record(name, result) @@ -344,7 +368,12 @@ def _record(name: str, result, exc=None) -> None: _record(name, None, exc) selected = [t[0] for t in tasks] - failed_selected = [n for n in selected if n not in results] + for n in out_of_time: + self._failed_analyzers[n] = f"not run: the {self.time_budget_sec:.0f}s M1 time budget was spent" + if out_of_time: + rationale += (f" Not run, the {self.time_budget_sec:.0f}s time budget was spent: " + f"{', '.join(out_of_time)}.") + failed_selected = [n for n in selected if n not in results and n not in out_of_time] for n in failed_selected: self._failed_analyzers.setdefault(n, "produced no result") if failed_selected: @@ -559,14 +588,25 @@ def _filter_applicable_names( names: list[str], model: "Model", data: "CaseBatch", + *, + named: bool = False, ) -> tuple[list[str], list[str]]: """Drop analyzers whose data preconditions are not met. LLM selection can choose semantically plausible tools that require a specific case shape. Filtering here prevents invalid runs such as POPE on open-ended VQA prompts without yes/no gold labels. + + The result is never longer than *names* (or than ``max_analyzers`` when + *names* is empty): the static selector replaces a dropped choice, it + does not pad the selection up to the cap. With *named*, the caller + chose these analyzers itself: the cap does not shorten its list and a + ``single_case`` one stays. """ - max_n = self.max_analyzers if self.max_analyzers is not None else len(names) + wanted = len(names) or (self.max_analyzers or 0) + capped = self.max_analyzers is not None and not named + max_n = min(wanted, self.max_analyzers or 0) if capped else wanted + chosen = set(names) if named else set() selected: list[str] = [] filtered: list[str] = [] filtered_seen: set[str] = set() @@ -580,7 +620,8 @@ def _consider(candidate: str) -> None: # that could not be built was selected anyway and then dropped at # instantiation with a warning, having already cost a slot. if not _analyzer_data_preconditions_met(candidate, data, model) \ - or self._needs_injection(candidate): + or self._needs_injection(candidate) \ + or (candidate not in chosen and _reads_one_of_many(candidate, data)): if candidate not in filtered_seen: filtered.append(candidate) filtered_seen.add(candidate) @@ -796,7 +837,7 @@ def _run_direct( # in-process (non-Docker) analyzers — Docker-mode calls happen inside # a subprocess and are out of reach of this wrapper. if self.run_logger is not None: - from evalrx.eval_agent.model_instrumentation import InstrumentedModel + from evalrx.eval_agent.runlog.instrumentation import InstrumentedModel # Best-effort (prompt -> case_id) for THIS analyzer's batch, so a # call that reuses the case's own prompt unmodified can be tied @@ -944,9 +985,19 @@ def _offerable(self, catalog: "dict[str, str]", data: "Any" = None, "via analyzer_overrides", name, needs, ) continue + if _reads_one_of_many(name, data): + logger.debug( + "not offering analyzer '%s': it explains one input and this " + "batch has several", name, + ) + continue keep[name] = desc return keep + def _progress(self, text: str) -> None: + if self.run_logger is not None and hasattr(self.run_logger, "progress"): + self.run_logger.progress("M1", text) + def _needs_injection(self, name: str) -> "list[str]": """Constructor arguments the caller must supply; empty when buildable. @@ -1102,6 +1153,16 @@ def _serialize_cases(data: "CaseBatch") -> list[dict[str, Any]]: return out +def _reads_one_of_many(name: str, data: "Any") -> bool: + """True for a ``single_case`` analyzer on a batch of several cases. + + It would read the first case and give M2 one row. A caller that names it + (``analyzers=[...], exact=True``) still gets it. + """ + cls = registry.analyzers.get(name) if registry.analyzers.has(name) else None + return bool(getattr(cls, "single_case", False)) and data is not None and len(data) > 1 + + def _analyzer_data_preconditions_met(name: str, data: "CaseBatch", model: "Model | None" = None) -> bool: cls = registry.analyzers.get(name) if registry.analyzers.has(name) else None diff --git a/evalrx/eval_agent/stages/probe_generator.py b/evalrx/eval_agent/stages/probe_generator.py index b014f64b..fdec2ec6 100755 --- a/evalrx/eval_agent/stages/probe_generator.py +++ b/evalrx/eval_agent/stages/probe_generator.py @@ -31,7 +31,7 @@ import re from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Callable from evalrx.agent_runtime.sandbox import ExperimentSandbox from evalrx.core.result import Result @@ -140,11 +140,8 @@ def generate( self._emit_codegen(name, need, source, "", ok=False, error="empty code produced") return None, None - result = self._run_code(code, name, model, cases) - self._emit_codegen( - name, need, source, code, ok=result is not None, - error="" if result is not None else "sandbox produced no parseable result", - ) + result, error = self._run_code(code, name, model, cases) + self._emit_codegen(name, need, source, code, ok=result is not None, error=error) if result is None: return None, None probe = GeneratedProbe(name=name, code=code, need=need, source=source) @@ -176,7 +173,7 @@ def run_cached( ) -> "Result | None": """Re-run an already-generated probe on fresh cases (no LLM call).""" self._collect_outputs(model, cases) - return self._run_code(probe.code, probe.name, model, cases) + return self._run_code(probe.code, probe.name, model, cases)[0] # ------------------------------------------------------------------ # Internals @@ -189,7 +186,7 @@ def _collect_outputs(self, model: "Model", cases: "CaseBatch") -> None: if self._max_cases > 0: # 0 = every case selected = selected[: self._max_cases] if self.run_logger is not None: - from evalrx.eval_agent.model_instrumentation import InstrumentedModel + from evalrx.eval_agent.runlog.instrumentation import InstrumentedModel model = InstrumentedModel( model, self.run_logger, @@ -198,13 +195,19 @@ def _collect_outputs(self, model: "Model", cases: "CaseBatch") -> None: case_prompts={c.inputs.prompt: c.id for c in selected}, batch_case_ids=[c.id for c in selected], ) - for case in selected: + # The answer each case was labelled on; only cases that carry none are asked. + outputs = ["" if getattr(case, "observed", None) is None else str(case.observed) + for case in selected] + missing = [i for i, text in enumerate(outputs) + if not text and getattr(selected[i], "inputs", None) is not None] + fresh = model.try_generate_batch([selected[i].inputs for i in missing]) if missing else [] + for i, answer in zip(missing, fresh): + if isinstance(answer, Exception): # a probe over partial outputs is still useful + logger.debug("ProbeGenerator: generate failed for %s: %s", selected[i].id, answer) + else: + outputs[i] = str(answer) + for case, output in zip(selected, outputs): inp = getattr(case, "inputs", None) - try: - output = str(model.generate(inp)) if inp is not None else "" - except Exception as exc: # a probe over partial outputs is still useful - logger.debug("ProbeGenerator: generate failed for %s: %s", case.id, exc) - output = "" label = getattr(case, "label", None) records.append({ "id": case.id, @@ -213,8 +216,7 @@ def _collect_outputs(self, model: "Model", cases: "CaseBatch") -> None: "label": getattr(label, "value", None), "output": output[:_MAX_OUTPUT_CHARS], }) - path = Path(self._sandbox.workdir) / _INPUT_FILENAME - path.write_text(json.dumps({"cases": records}, default=str), encoding="utf-8") + self._sandbox.put(_INPUT_FILENAME, json.dumps({"cases": records}, default=str)) def _write_code(self, need: str) -> tuple[str, str]: if self._cli_config is not None and self._cli_config.provider != "llm": @@ -265,21 +267,42 @@ def _run_code( name: str, model: "Model", cases: "CaseBatch", - ) -> "Result | None": - sandbox_result = self._sandbox.run(code, timeout_sec=self._timeout_sec) - if not sandbox_result.ok: - logger.warning( - "ProbeGenerator: sandbox run failed (rc=%s): %s", - sandbox_result.returncode, (sandbox_result.stderr or "").strip()[:200], - ) - return None - return _parse_result(sandbox_result.stdout, name, model, cases) + ) -> "tuple[Result | None, str]": + """The probe's Result, or ``None`` and why the run produced none.""" + return run_probe_code(self._sandbox, code, self._timeout_sec, + lambda stdout: _parse_result(stdout, name, model, cases)) # --------------------------------------------------------------------------- # Module helpers # --------------------------------------------------------------------------- +def run_probe_code( + sandbox: "ExperimentSandbox", + code: str, + timeout_sec: int, + parse: "Callable[[str], Result | None]", +) -> "tuple[Result | None, str]": + """Run a generated probe; its Result, or ``None`` and the reason in words. + + The reason goes into the run log, so it names what happened: a timeout, the + script's own traceback, or a missing result line. + """ + run = sandbox.run(code, timeout_sec=timeout_sec) + if run.timed_out: + error = f"the probe script was killed after {timeout_sec}s" + elif not run.ok: + tail = (run.stderr or "").strip().splitlines()[-1:] or ["no error output"] + error = f"the probe script exited with code {run.returncode}: {tail[0][:300]}" + else: + result = parse(run.stdout) + if result is not None: + return result, "" + error = f"the probe script printed no readable {_RESULT_MARKER} line" + logger.warning("Generated probe failed: %s", error) + return None, error + + def _extract_code(raw: str) -> str: cleaned = re.sub(r".*?", "", raw, flags=re.DOTALL) fence = re.search(r"```(?:python)?\s*\n(.*?)```", cleaned, flags=re.DOTALL) diff --git a/evalrx/eval_agent/stages/probe_search_agent.py b/evalrx/eval_agent/stages/probe_search_agent.py index 60db8a90..ba950f9b 100644 --- a/evalrx/eval_agent/stages/probe_search_agent.py +++ b/evalrx/eval_agent/stages/probe_search_agent.py @@ -68,7 +68,7 @@ def __post_init__(self) -> None: def run(self, model: "Model", seed_pool: "CaseBatch") -> ProbeSearchResult: judge = self.judge if self.run_logger is not None: - from evalrx.eval_agent.model_instrumentation import InstrumentedModel + from evalrx.eval_agent.runlog.instrumentation import InstrumentedModel run_logger = self.run_logger cycle = int(getattr(run_logger, "current_cycle", -1)) diff --git a/evalrx/eval_agent/stages/surgery.py b/evalrx/eval_agent/stages/surgery.py index 86395ecd..b60636c9 100755 --- a/evalrx/eval_agent/stages/surgery.py +++ b/evalrx/eval_agent/stages/surgery.py @@ -230,7 +230,7 @@ class SurgeryAgent: sandbox even when a ``RunContext`` is given. writer_config: :class:`~evalrx.eval_agent.experiment_writer.ExperimentWriterConfig` controlling phases and limits. - run_context: Optional :class:`~evalrx.eval_agent.run_context.RunContext`. + run_context: Optional :class:`~evalrx.eval_agent.runlog.context.RunContext`. When set (and *sandbox_dir* is not), each ``operate()`` call allocates its own self-contained *trial* under ``experiments/`` (code + sandbox, see diff --git a/evalrx/eval_agent/stages/whitebox_probe_generator.py b/evalrx/eval_agent/stages/whitebox_probe_generator.py index a9aae5cc..c5bf0784 100755 --- a/evalrx/eval_agent/stages/whitebox_probe_generator.py +++ b/evalrx/eval_agent/stages/whitebox_probe_generator.py @@ -31,6 +31,7 @@ from __future__ import annotations +import io import json import logging import re @@ -49,6 +50,7 @@ _MANIFEST, _RESULT_MARKER, ) +from evalrx.eval_agent.stages.probe_generator import run_probe_code if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig @@ -145,11 +147,8 @@ def generate( self._emit_codegen(name, need, source, "", ok=False, error="empty code produced") return None, None - result = self._run_code(code, name, model, cases) - self._emit_codegen( - name, need, source, code, ok=result is not None, - error="" if result is not None else "sandbox produced no parseable result", - ) + result, error = self._run_code(code, name, model, cases) + self._emit_codegen(name, need, source, code, ok=result is not None, error=error) if result is None: return None, None probe = GeneratedWhiteboxProbe(name=name, code=code, need=need, source=source) @@ -182,7 +181,7 @@ def run_cached( """Re-capture and re-run an already-generated probe (no LLM call).""" if self._capture(model, cases) == 0: return None - return self._run_code(probe.code, probe.name, model, cases) + return self._run_code(probe.code, probe.name, model, cases)[0] # ------------------------------------------------------------------ # Host capture (trusted) @@ -190,16 +189,12 @@ def run_cached( def _capture(self, model: "Model", cases: "CaseBatch") -> int: """Forward each case, reduce, and dump the attention bundle. Returns n captured.""" - workdir = Path(self._sandbox.workdir) - dump_dir = workdir / _DUMP_DIR - dump_dir.mkdir(parents=True, exist_ok=True) - manifest: list[dict[str, Any]] = [] selected = list(cases) if self._max_cases > 0: # 0 = every case selected = selected[: self._max_cases] if self.run_logger is not None: - from evalrx.eval_agent.model_instrumentation import InstrumentedModel + from evalrx.eval_agent.runlog.instrumentation import InstrumentedModel model = InstrumentedModel( model, self.run_logger, @@ -228,10 +223,9 @@ def _capture(self, model: "Model", cases: "CaseBatch") -> int: finally: trace = None # free the heavy attention tensors promptly - np.savez_compressed( - dump_dir / f"{case.id}.npz", - attn_last=rows, image_token_mask=mask_np, - ) + dump = io.BytesIO() + np.savez_compressed(dump, attn_last=rows, image_token_mask=mask_np) + self._sandbox.put(f"{_DUMP_DIR}/{case.id}.npz", dump.getvalue()) label = getattr(case, "label", None) manifest.append({ "id": case.id, @@ -241,9 +235,7 @@ def _capture(self, model: "Model", cases: "CaseBatch") -> int: "tokens": tokens, }) - (workdir / _MANIFEST).write_text( - json.dumps({"cases": manifest}), encoding="utf-8" - ) + self._sandbox.put(_MANIFEST, json.dumps({"cases": manifest})) return len(manifest) # ------------------------------------------------------------------ @@ -296,15 +288,10 @@ def _build_prompt(self, need: str, *, fenced: bool) -> str: def _run_code( self, code: str, name: str, model: "Model", cases: "CaseBatch", - ) -> "Result | None": - sandbox_result = self._sandbox.run(code, timeout_sec=self._timeout_sec) - if not sandbox_result.ok: - logger.warning( - "WhiteboxProbeGenerator: sandbox run failed (rc=%s): %s", - sandbox_result.returncode, (sandbox_result.stderr or "").strip()[:200], - ) - return None - return _parse_result(sandbox_result.stdout, name, model, cases) + ) -> "tuple[Result | None, str]": + """The probe's Result, or ``None`` and why the run produced none.""" + return run_probe_code(self._sandbox, code, self._timeout_sec, + lambda stdout: _parse_result(stdout, name, model, cases)) # --------------------------------------------------------------------------- diff --git a/evalrx/logging_utils.py b/evalrx/logging_utils.py index c6b1a363..62505ebd 100644 --- a/evalrx/logging_utils.py +++ b/evalrx/logging_utils.py @@ -40,7 +40,7 @@ import sys from typing import IO, Optional -# Every module's `logging.getLogger(__name__)` (e.g. "evalrx.eval_agent.loop") +# Every module's `logging.getLogger(__name__)` (e.g. "evalrx.eval_agent.loop.diagnose") # is a child of this in the dot-hierarchy, so one handler here reaches all of # them via normal propagation -- except RunLogger's own "evalrx.run." # tree, which sets propagate=False by design to keep its structured JSONL diff --git a/evalrx/models/backends/api/backend.py b/evalrx/models/backends/api/backend.py index cc194bd8..6f5badfa 100755 --- a/evalrx/models/backends/api/backend.py +++ b/evalrx/models/backends/api/backend.py @@ -96,6 +96,7 @@ class APIModel(Model): def __init__(self, spec, runtime: RuntimeConfig) -> None: self.spec = spec self.runtime = runtime + self.concurrency = runtime.concurrency self._generate_fn = runtime.generate_fn self._chat_fn = runtime.chat_fn self._logprobs_fn = runtime.logprobs_fn diff --git a/evalrx/models/backends/base.py b/evalrx/models/backends/base.py index 6d87712a..2ce36553 100755 --- a/evalrx/models/backends/base.py +++ b/evalrx/models/backends/base.py @@ -29,6 +29,19 @@ class RuntimeConfig: dtype: str = "bfloat16" attn_impl: Optional[str] = None # hf_local forces "eager" when attention is wanted max_new_tokens: int = 512 + #: The decoding the model is deployed with (``do_sample``, ``temperature``, + #: ``top_p``, ``top_k``). ``hf_local`` and ``jax_local`` apply it to every + #: generate call that does not pass its own, so a probe run with no + #: arguments answers the way the labelled run did. The api backends carry + #: their sampling in ``generate_fn``. + sampling: dict[str, Any] = field(default_factory=dict) + #: hf_local: prompts per padded batch in ``generate_batch`` (halved on a + #: CUDA out-of-memory error). A batch runs until its longest answer ends, + #: so throughput grows almost linearly with it: Qwen3.5-2B at a 2048-token + #: cap took 4.3 s per prompt at 16, 2.8 s at 32 and 1.6 s at 64 (8.4 GB). + batch_size: int = 32 + #: api: requests in flight at once in ``generate_batch``. + concurrency: int = 8 #: hf_local, TEXT-ONLY specs: render ``inputs.prompt`` as one user turn through #: the tokenizer's chat template (with ``spec.chat_template_kwargs``, e.g. #: ``enable_thinking=False``) before generate()/logprobs(). Off by default: a diff --git a/evalrx/models/backends/hf/_util.py b/evalrx/models/backends/hf/_util.py index c8e8a46c..75619963 100644 --- a/evalrx/models/backends/hf/_util.py +++ b/evalrx/models/backends/hf/_util.py @@ -166,3 +166,39 @@ def _collect_message_images(messages: list) -> list: if img is not None: images.append(_resolve_image(img)) return images + + +def collate_encodings(encodings: "list[Any]", pad_token_id: int) -> "dict[str, Any] | None": + """One left-padded batch from single-input encodings, or ``None``. + + Each encoding is what a tokenizer or processor returned for one input. + Tensors that run along the token sequence (``input_ids`` and everything of + its shape) are padded on the left to the longest; every other tensor is + concatenated on its first axis, which is how the processors themselves + batch images and audio: a per-input tensor ``(1, ...)`` becomes + ``(batch, ...)`` and a flat per-image or per-patch tensor stays flat, in + input order. ``None`` when the encodings do not line up that way (different + keys, or media tensors of different shapes); the caller then runs them one + at a time. + """ + import torch + import torch.nn.functional as F + + keys = set(encodings[0]) | {"attention_mask"} + if any(set(enc) | {"attention_mask"} != keys for enc in encodings): + return None + width = max(enc["input_ids"].shape[1] for enc in encodings) + batch: "dict[str, Any]" = {} + for key in encodings[0] if "attention_mask" in encodings[0] else [*encodings[0], "attention_mask"]: + tensors = [ + enc[key] if key in enc else torch.ones_like(enc["input_ids"]) + for enc in encodings + ] + if all(t.shape == enc["input_ids"].shape for t, enc in zip(tensors, encodings)): + fill = pad_token_id if key == "input_ids" else 0 + tensors = [F.pad(t, (width - t.shape[1], 0), value=fill) for t in tensors] + try: + batch[key] = torch.cat(tensors, dim=0) + except (RuntimeError, TypeError): + return None + return batch diff --git a/evalrx/models/backends/hf/model.py b/evalrx/models/backends/hf/model.py index 9727c273..675941f7 100755 --- a/evalrx/models/backends/hf/model.py +++ b/evalrx/models/backends/hf/model.py @@ -19,7 +19,8 @@ from __future__ import annotations import logging -from typing import Any +from collections.abc import Sequence +from typing import Any, Callable, TypeVar from evalrx.core.capability import Capability, CapabilityError from evalrx.core.case import Inputs @@ -35,12 +36,24 @@ _populate_audio_extras, _populate_vision_extras, _read_nested_attr, + collate_encodings, ) from evalrx.models.backends.hf.decoding import ContrastiveDecodingMixin from evalrx.models.backends.hf.specialists import SpecialistRepairsMixin logger = logging.getLogger(__name__) +_R = TypeVar("_R") + +#: Multimodal families whose batched answers were checked against one input at +#: a time on a real checkpoint (float32, greedy, images or clips of different +#: sizes: identical text on every input, logprobs within 1e-3). A stacked batch +#: that a family's ``generate`` reads wrongly would give plausible wrong +#: answers rather than an error, so any other multimodal family runs one input +#: at a time until it is checked and added here. +BATCHED_MULTIMODAL_FAMILIES = frozenset( + {"qwen2_vl", "qwen2_5_vl", "qwen3_vl", "qwen3_5", "qwen2_audio"}) + # capability -> HF forward flag _CAPTURE_FLAGS = { Capability.ATTENTION: "output_attentions", @@ -348,16 +361,102 @@ def _encode(self, prompt: str): # -- interface ----------------------------------------------------- def generate(self, inputs: Any, **kwargs) -> str: + return self.generate_batch([inputs], **kwargs)[0] + + def generate_batch(self, inputs: Sequence[Any], **kwargs) -> list[str]: + """Answers in padded batches of ``runtime.batch_size`` inputs.""" import torch model, processor = self._loaded tok = getattr(processor, "tokenizer", processor) + decoding = self._decoding(tok, kwargs) + + def run(enc: Any) -> list[str]: + with torch.no_grad(): + out = model.generate(**enc, **decoding) + return [tok.decode(_new_tokens(row, prompt), skip_special_tokens=True) + for row, prompt in zip(out, enc["input_ids"])] + + return self._in_batches(list(inputs), run) + + def _in_batches(self, inputs: list[Any], run: "Callable[[Any], list[_R]]") -> "list[_R]": + """*run* on left-padded batches of *inputs*; results in input order. + + Every input is encoded on its own, the way a single call encodes it, + and the encodings are stacked (:func:`collate_encodings`), so text and + multimodal specs take the same path. Inputs are taken a window of four + batches at a time, so the encodings alive at once stay bounded however + long the list is (one ``vl_shap`` case asks for hundreds of masked + images). Within a window, inputs that carry the same tensors (with an + image, without one) batch together, longest first so a batch pads + little. On a CUDA out-of-memory error the batch is halved and the run + continues. Encodings that cannot be stacked (media tensors of different + shapes) run one input at a time, and so does a multimodal family + outside :data:`BATCHED_MULTIMODAL_FAMILIES`. + """ + import torch + + model, processor = self._loaded + tok = getattr(processor, "tokenizer", processor) + stacks = (not self.spec.needs_multimodal_encode + or self.spec.model_type in BATCHED_MULTIMODAL_FAMILIES) + size = max(1, int(self.runtime.batch_size)) if stacks else 1 + window = 4 * size + results: "list[Any]" = [None] * len(inputs) + for offset in range(0, len(inputs), window): + encodings = {offset + i: self._encode_any(item) + for i, item in enumerate(inputs[offset:offset + window])} + alike: "dict[frozenset[str], list[int]]" = {} + for index, enc in encodings.items(): + alike.setdefault(frozenset(enc), []).append(index) + for group in alike.values(): + group.sort(key=lambda i: -encodings[i]["input_ids"].shape[1]) + stackable, start = True, 0 + while start < len(group): + rows = group[start:start + (size if stackable else 1)] + batch = encodings[rows[0]] + if len(rows) > 1: + if tok.pad_token_id is None: + tok.pad_token = tok.eos_token + batch = collate_encodings([encodings[i] for i in rows], tok.pad_token_id) + if batch is None: + logger.info("%s: these inputs do not stack into one batch; " + "running them one at a time", self.spec.key) + stackable = False + continue + try: + outputs = run(batch) + except torch.cuda.OutOfMemoryError: + if len(rows) == 1: + raise + del batch + torch.cuda.empty_cache() + size = len(rows) // 2 + logger.warning("%s: out of memory at this batch size; continuing " + "with %d", self.spec.key, size) + continue + for i, output in zip(rows, outputs): + results[i] = output + start += len(rows) + return results + + def _encode_any(self, inputs: Any) -> Any: + """One input's encoding (a batch of one) on the model's device.""" + model, processor = self._loaded if self.spec.needs_multimodal_encode: enc, _, _, _ = self._encode_vlm(inputs, model, processor) else: - prompt = self._as_prompt(inputs) - enc = self._encode(prompt) + enc = self._encode(self._as_prompt(inputs)) enc.pop("token_type_ids", None) # some VLM processors emit this; generate() rejects it + return enc + + def _decoding(self, tok: Any, kwargs: dict[str, Any]) -> dict[str, Any]: + """``model.generate`` keyword arguments for one call. + + The call's own *kwargs* win over ``runtime.sampling``, the decoding the + model is deployed with. + """ + kwargs = {**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 @@ -375,53 +474,64 @@ def generate(self, inputs: Any, **kwargs) -> str: # two controls that Hugging Face does not accept verbatim instead of # letting run_pipeline swallow a ValueError and report 0 coverage. temperature = kwargs.get("temperature") - if temperature is not None: - if float(temperature) <= 0.0: - kwargs.pop("temperature", None) - kwargs["do_sample"] = False - kwargs.pop("top_p", None) - kwargs.pop("top_k", None) - else: - kwargs.setdefault("do_sample", True) + if kwargs.get("do_sample") is False or (temperature is not None and float(temperature) <= 0.0): + kwargs["do_sample"] = False + for name in ("temperature", "top_p", "top_k"): + kwargs.pop(name, None) + elif temperature is not None: + kwargs.setdefault("do_sample", True) stop = kwargs.pop("stop", None) if stop: kwargs["stop_strings"] = stop kwargs["tokenizer"] = tok - with torch.no_grad(): - out = model.generate(**enc, max_new_tokens=max_new, **kwargs) - new = _new_tokens(out[0], enc["input_ids"][0]) - return tok.decode(new, skip_special_tokens=True) + return {"max_new_tokens": max_new, **kwargs} def logprobs( self, inputs: Any, max_new_tokens: int = 64, top_k: int = 5, **kwargs ) -> list[TokenLogprob]: """Per-output-token logprobs via greedy generate with output_scores.""" + return self.logprobs_batch([inputs], max_new_tokens=max_new_tokens, top_k=top_k)[0] + + def logprobs_batch( + self, inputs: Sequence[Any], max_new_tokens: int = 64, top_k: int = 5, **kwargs + ) -> list[list[TokenLogprob]]: + """:meth:`logprobs` in padded batches of ``runtime.batch_size`` inputs.""" import torch model, processor = self._loaded tok = getattr(processor, "tokenizer", processor) - if self.spec.needs_multimodal_encode: - enc, _, _, _ = self._encode_vlm(inputs, model, processor) - else: - enc = self._encode(self._as_prompt(inputs)) - enc.pop("token_type_ids", None) - with torch.no_grad(): - out = model.generate( - **enc, - max_new_tokens=max_new_tokens, - do_sample=False, - output_scores=True, - return_dict_in_generate=True, - ) - gen_ids = _new_tokens(out.sequences[0], enc["input_ids"][0]).tolist() - result: list[TokenLogprob] = [] - for i, score in enumerate(out.scores): - lp = torch.log_softmax(score[0].float(), dim=-1) - tid = gen_ids[i] - topk = torch.topk(lp, min(top_k, lp.shape[-1])) - top = {tok.decode([int(j)]): float(v) for v, j in zip(topk.values, topk.indices)} - result.append(TokenLogprob(token=tok.decode([tid]), logprob=float(lp[tid]), top=top)) - return result + stop = getattr(getattr(model, "generation_config", None), "eos_token_id", None) + stop_ids = set(stop) if isinstance(stop, (list, tuple)) else {stop} + + def run(enc: Any) -> list[list[TokenLogprob]]: + with torch.no_grad(): + out = model.generate( + **enc, + max_new_tokens=max_new_tokens, + do_sample=False, + output_scores=True, + return_dict_in_generate=True, + ) + rows: list[list[TokenLogprob]] = [] + for row, prompt in enumerate(enc["input_ids"]): + gen_ids = _new_tokens(out.sequences[row], prompt).tolist() + # A row that stopped before the others is padded after its + # end-of-sequence token; its answer ends with that token. + ended = next((i + 1 for i, tid in enumerate(gen_ids) if tid in stop_ids), + len(gen_ids)) + result: list[TokenLogprob] = [] + for i, score in enumerate(out.scores[:ended]): + lp = torch.log_softmax(score[row].float(), dim=-1) + tid = gen_ids[i] + topk = torch.topk(lp, min(top_k, lp.shape[-1])) + top = {tok.decode([int(j)]): float(v) + for v, j in zip(topk.values, topk.indices)} + result.append( + TokenLogprob(token=tok.decode([tid]), logprob=float(lp[tid]), top=top)) + rows.append(result) + return rows + + return self._in_batches(list(inputs), run) def chat(self, messages: list, tools=None) -> ChatTurn: """Tool-aware turn via the model's chat template. diff --git a/evalrx/models/backends/jax/backend.py b/evalrx/models/backends/jax/backend.py index 404c2064..792e3a62 100644 --- a/evalrx/models/backends/jax/backend.py +++ b/evalrx/models/backends/jax/backend.py @@ -170,8 +170,9 @@ def _encode(self, inputs: Any) -> Encoding: def _sampling(self, kwargs: dict) -> SamplingParams: """hf_local's kwarg contract: ``max_new_tokens`` wins over the OpenAI-style ``max_tokens``; ``temperature <= 0`` (or ``do_sample=False``) is greedy; - ``do_sample=True`` without a temperature samples at 1.0.""" - kwargs = dict(kwargs) + ``do_sample=True`` without a temperature samples at 1.0. The call's own + kwargs win over ``runtime.sampling``.""" + kwargs = {**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 fa27ffcc..236307c0 100755 --- a/evalrx/models/backends/vllm_offline.py +++ b/evalrx/models/backends/vllm_offline.py @@ -15,6 +15,7 @@ from __future__ import annotations +from collections.abc import Sequence from typing import Any from evalrx.core.capability import Capability, CapabilityError @@ -58,19 +59,31 @@ def _engine(self): def _as_prompt(inputs: Any) -> str: return inputs.prompt if isinstance(inputs, Inputs) else str(inputs) - def _sampling(self, *, max_tokens: int | None = None, temperature: float = 0.0, logprobs: int | None = None, **_): + def _sampling(self, *, logprobs: int | None = None, **kwargs: Any): + """vLLM sampling for one call: its own kwargs over ``runtime.sampling``, + under hf_local's names (``max_new_tokens`` or ``max_tokens``; greedy + when ``do_sample`` is False or the temperature is not positive).""" from vllm import SamplingParams - return SamplingParams( - max_tokens=max_tokens or self.runtime.max_new_tokens, - temperature=temperature, - logprobs=logprobs, - ) + kwargs = {**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: + temperature = 0.0 + elif kwargs.get("do_sample") and "temperature" not in kwargs: + temperature = 1.0 + extra = {name: kwargs[name] for name in ("top_p", "top_k") if temperature > 0 and name in kwargs} + return SamplingParams(max_tokens=int(max_tokens), temperature=temperature, logprobs=logprobs, **extra) # -- interface ----------------------------------------------------- def generate(self, inputs: Any, **kwargs) -> str: - out = self._engine.generate([self._as_prompt(inputs)], self._sampling(**kwargs)) - return out[0].outputs[0].text + return self.generate_batch([inputs], **kwargs)[0] + + def generate_batch(self, inputs: Sequence[Any], **kwargs) -> list[str]: + """One engine call for all *inputs*; vLLM batches them continuously.""" + prompts = [self._as_prompt(item) for item in inputs] + outs = self._engine.generate(prompts, self._sampling(**kwargs)) if prompts else [] + return [out.outputs[0].text for out in outs] def chat(self, messages: list, tools=None) -> ChatTurn: if Capability.TOOL_CALLS not in self.capabilities: @@ -83,20 +96,32 @@ def chat(self, messages: list, tools=None) -> ChatTurn: return ChatTurn(text=out[0].outputs[0].text, raw_tool_calls=None) # codec parses the text def logprobs(self, inputs: Any, top_k: int = 5, **kwargs) -> list[TokenLogprob]: - out = self._engine.generate([self._as_prompt(inputs)], self._sampling(logprobs=top_k, **kwargs)) - comp = out[0].outputs[0] + return self.logprobs_batch([inputs], top_k=top_k, **kwargs)[0] + + def logprobs_batch( + self, inputs: Sequence[Any], top_k: int = 5, **kwargs + ) -> list[list[TokenLogprob]]: + """One engine call for all *inputs*, each answer with its token logprobs.""" + prompts = [self._as_prompt(item) for item in inputs] + if not prompts: + return [] + outs = self._engine.generate(prompts, self._sampling(logprobs=top_k, **kwargs)) tok = self._engine.get_tokenizer() - result: list[TokenLogprob] = [] - for tid, lp_dict in zip(comp.token_ids, comp.logprobs or []): - entry = lp_dict.get(tid) - chosen = float(getattr(entry, "logprob", entry)) if entry is not None else 0.0 - chosen_tok = getattr(entry, "decoded_token", None) or tok.decode([tid]) - top = { - (getattr(v, "decoded_token", None) or tok.decode([k])): float(getattr(v, "logprob", v)) - for k, v in lp_dict.items() - } - result.append(TokenLogprob(token=chosen_tok, logprob=chosen, top=top)) - return result + rows: list[list[TokenLogprob]] = [] + for out in outs: + comp = out.outputs[0] + result: list[TokenLogprob] = [] + for tid, lp_dict in zip(comp.token_ids, comp.logprobs or []): + entry = lp_dict.get(tid) + chosen = float(getattr(entry, "logprob", entry)) if entry is not None else 0.0 + chosen_tok = getattr(entry, "decoded_token", None) or tok.decode([tid]) + top = { + (getattr(v, "decoded_token", None) or tok.decode([k])): float(getattr(v, "logprob", v)) + for k, v in lp_dict.items() + } + result.append(TokenLogprob(token=chosen_tok, logprob=chosen, top=top)) + rows.append(result) + return rows def forward(self, inputs: Any, capture: set[Capability], spec=None) -> Trace: raise CapabilityError( # vLLM exposes no internals — use hf_local for white-box diff --git a/evalrx/reporting/langfuse_source.py b/evalrx/reporting/langfuse_source.py index f2965b77..e3a7c9ac 100644 --- a/evalrx/reporting/langfuse_source.py +++ b/evalrx/reporting/langfuse_source.py @@ -7,7 +7,7 @@ types, then re-buckets it into a run-log-shaped cache (:func:`materialize`) so the normal ``run.json``/``M/log.json`` read path can render it. -Caveat: :class:`~evalrx.eval_agent.run_logger.RunLogger` does not +Caveat: :class:`~evalrx.eval_agent.runlog.logger.RunLogger` does not currently push structured events through that outbox (it relies on live spans/generations instead), so a run's recovered events presently carry no ``stage`` tag and land in ``run.json``'s ``unrouted`` bucket rather than diff --git a/evalrx/reporting/server.py b/evalrx/reporting/server.py index 95e8aa83..2d8a3ed6 100644 --- a/evalrx/reporting/server.py +++ b/evalrx/reporting/server.py @@ -115,7 +115,7 @@ def _run_label(root: Path) -> str: return f"{root.parent.name}/{root.name}" if root.name == "logs" else root.name -#: RunLogger's per-stage documents (evalrx/eval_agent/run_logger.py). +#: RunLogger's per-stage documents (evalrx/eval_agent/runlog/logger.py). #: A run.json + at least one of these is its on-disk signature, matching #: find_run_root's marker and reporting/run_events.py's resolve_run_root. _STAGES = ("M1", "M2", "M3", "M4", "M5") diff --git a/examples/benchmark/README.md b/examples/benchmark/README.md index 7ef47ab8..f591dd11 100644 --- a/examples/benchmark/README.md +++ b/examples/benchmark/README.md @@ -185,7 +185,7 @@ the final significance gate, and the validation data costs no confirm power. vLLM endpoint (~29 tok/s on the 2B; ~25 s per causal-judgement item), so the llm default is 256 rows, not a census; `--backend endpoint` is the fast path when a vLLM server is up. -* **Judge/coder defaults to Claude `claude-opus-5` at high effort** (CLI +* **Judge/coder defaults to Claude `sonnet` at medium effort** (CLI defaults; the compose commands no longer pin a judge, so `EXTRA_ARGS` can still override). `--judge-provider codex` restores Codex `gpt-5.6-terra`; the Codex npm package, Node runtime, and authenticated `CODEX_HOME` are diff --git a/examples/benchmark/alm/gemini/docker-compose.yml b/examples/benchmark/alm/gemini/docker-compose.yml index b933e4f9..be9d547d 100644 --- a/examples/benchmark/alm/gemini/docker-compose.yml +++ b/examples/benchmark/alm/gemini/docker-compose.yml @@ -4,7 +4,7 @@ # GEMINI_API_KEY comes from examples/benchmark/.env (this leaf links to it); CONCURRENCY sets the # parallel discovery requests (default 4). EXTRA_ARGS passes more run.py flags (e.g. # EXTRA_ARGS='--baseline-only --limit 8', '--thinking-level low', '--request-retries 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). --backend gemini is forced for +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). --backend gemini is forced for # the family; the fix ladder is clamped to L2 (no internals, no logprobs). name: bench-alm-gemini x-gemini: &gemini diff --git a/examples/benchmark/alm/gemma/docker-compose.yml b/examples/benchmark/alm/gemma/docker-compose.yml index 5d361a3e..23870713 100644 --- a/examples/benchmark/alm/gemma/docker-compose.yml +++ b/examples/benchmark/alm/gemma/docker-compose.yml @@ -2,7 +2,7 @@ # DATASET=mmau LIMIT=256 CUDA_VISIBLE_DEVICES=0 docker compose run -d --name alm-gemma-4-e2b-mmau gemma-4-e2b # Datasets for this modality: mmau, mmsu, audiocaps_hallu, af_reasoning_mcq. # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-alm-gemma x-gemma: &gemma extends: diff --git a/examples/benchmark/alm/gemma_jax/docker-compose.yml b/examples/benchmark/alm/gemma_jax/docker-compose.yml index 66146c14..85128ccf 100644 --- a/examples/benchmark/alm/gemma_jax/docker-compose.yml +++ b/examples/benchmark/alm/gemma_jax/docker-compose.yml @@ -6,7 +6,7 @@ # Weights: EVALRX_JAX_CKPT (examples/benchmark/.env) is a host directory holding gemma4--it/ # and tokenizer_gemma4.model, mounted at /ckpt; a size without a mirror there is read from the # public gs://gemma-data bucket on every load. -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-alm-gemma-jax x-gemma-jax: &gemma_jax extends: diff --git a/examples/benchmark/alm/nemotron/docker-compose.yml b/examples/benchmark/alm/nemotron/docker-compose.yml index 377d4c18..d12375f5 100644 --- a/examples/benchmark/alm/nemotron/docker-compose.yml +++ b/examples/benchmark/alm/nemotron/docker-compose.yml @@ -2,7 +2,7 @@ # DATASET=mmau LIMIT=256 CUDA_VISIBLE_DEVICES=0 docker compose run -d --name alm-nemotron-3-nano-omni-30b-a3b-mmau nemotron-3-nano-omni-30b-a3b # Datasets for this modality: mmau, mmsu, audiocaps_hallu, af_reasoning_mcq. # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-alm-nemotron x-nemotron: &nemotron extends: diff --git a/examples/benchmark/alm/qwen/docker-compose.yml b/examples/benchmark/alm/qwen/docker-compose.yml index 08fb4826..4b91ec99 100644 --- a/examples/benchmark/alm/qwen/docker-compose.yml +++ b/examples/benchmark/alm/qwen/docker-compose.yml @@ -2,7 +2,7 @@ # DATASET=mmau LIMIT=256 CUDA_VISIBLE_DEVICES=0 docker compose run -d --name alm-qwen3-omni-30b-a3b-mmau qwen3-omni-30b-a3b # Datasets for this modality: mmau, mmsu, audiocaps_hallu, af_reasoning_mcq. # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-alm-qwen x-qwen: &qwen extends: diff --git a/examples/benchmark/llm/gemini/docker-compose.yml b/examples/benchmark/llm/gemini/docker-compose.yml index 531b8d8a..76574c0e 100644 --- a/examples/benchmark/llm/gemini/docker-compose.yml +++ b/examples/benchmark/llm/gemini/docker-compose.yml @@ -4,7 +4,7 @@ # GEMINI_API_KEY comes from examples/benchmark/.env (this leaf links to it); CONCURRENCY sets the # parallel discovery requests (default 4). EXTRA_ARGS passes more run.py flags (e.g. # EXTRA_ARGS='--baseline-only --limit 8', '--thinking-level low', '--request-retries 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). --backend gemini is forced for +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). --backend gemini is forced for # the family; the fix ladder is clamped to L2 (no internals, no logprobs). name: bench-llm-gemini x-gemini: &gemini diff --git a/examples/benchmark/llm/gemma/docker-compose.yml b/examples/benchmark/llm/gemma/docker-compose.yml index bdfa2313..6d28e78b 100644 --- a/examples/benchmark/llm/gemma/docker-compose.yml +++ b/examples/benchmark/llm/gemma/docker-compose.yml @@ -4,7 +4,7 @@ # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). # Backend: llm cells default to --backend endpoint (OpenAI-compatible server at --base-url, # default http://host.docker.internal:8020/v1 = a vLLM server on the host); EXTRA_ARGS='--backend hf_local' runs in-process. -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-llm-gemma x-gemma: &gemma extends: diff --git a/examples/benchmark/llm/gemma_jax/docker-compose.yml b/examples/benchmark/llm/gemma_jax/docker-compose.yml index 840c3ad1..e95fbc35 100644 --- a/examples/benchmark/llm/gemma_jax/docker-compose.yml +++ b/examples/benchmark/llm/gemma_jax/docker-compose.yml @@ -6,7 +6,7 @@ # Weights: EVALRX_JAX_CKPT (examples/benchmark/.env) is a host directory holding gemma4--it/ # and tokenizer_gemma4.model, mounted at /ckpt; a size without a mirror there is read from the # public gs://gemma-data bucket on every load. -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-llm-gemma-jax x-gemma-jax: &gemma_jax extends: diff --git a/examples/benchmark/llm/nemotron/docker-compose.yml b/examples/benchmark/llm/nemotron/docker-compose.yml index 6a767c0a..594f1f7c 100644 --- a/examples/benchmark/llm/nemotron/docker-compose.yml +++ b/examples/benchmark/llm/nemotron/docker-compose.yml @@ -4,7 +4,7 @@ # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). # Backend: llm cells default to --backend endpoint (OpenAI-compatible server at --base-url, # default http://host.docker.internal:8020/v1 = a vLLM server on the host); EXTRA_ARGS='--backend hf_local' runs in-process. -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-llm-nemotron x-nemotron: &nemotron extends: diff --git a/examples/benchmark/llm/qwen/docker-compose.yml b/examples/benchmark/llm/qwen/docker-compose.yml index a0335d44..0b6f01fc 100644 --- a/examples/benchmark/llm/qwen/docker-compose.yml +++ b/examples/benchmark/llm/qwen/docker-compose.yml @@ -4,7 +4,7 @@ # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). # Backend: llm cells default to --backend endpoint (OpenAI-compatible server at --base-url, # default http://host.docker.internal:8020/v1 = a vLLM server on the host); EXTRA_ARGS='--backend hf_local' runs in-process. -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-llm-qwen x-qwen: &qwen extends: diff --git a/examples/benchmark/readme_jax.md b/examples/benchmark/readme_jax.md index 5530db59..d446b293 100644 --- a/examples/benchmark/readme_jax.md +++ b/examples/benchmark/readme_jax.md @@ -28,7 +28,7 @@ to end on 2026-10-02 (256 rows, 2 h 10 min on one shared A100, FIXED +0.211). | Docker with the NVIDIA container toolkit, your user in the `docker` group | the cell runs in `evalrx-bench-gemma-jax` | `docker run --rm --gpus all nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi` | | one GPU with about 20 GB free, 35 GB of host RAM | the E2B vlm cell took about 17 GB of the card and peaked at 32.6 GB RSS while loading (the checkpoint is stored float32 and cast after the read); the image sets `XLA_PYTHON_CLIENT_PREALLOCATE=false`, so the run shares a card | `nvidia-smi`, `free -g` | | `gsutil` | the checkpoints are public objects in `gs://gemma-data` (no account needed) | `gsutil ls gs://gemma-data/checkpoints/` | -| the `claude` CLI, logged in | judge and repair coder default to Claude (`claude-opus-5`); Part 2.4 has the alternatives | `claude -p "Reply with exactly OK"` | +| the `claude` CLI, logged in | judge and repair coder default to Claude (`sonnet`); Part 2.4 has the alternatives | `claude -p "Reply with exactly OK"` | | 30 GB of disk | 17 GB checkpoint mirror + 11 GB image | `df -h` | Nothing from HuggingFace is gated for this cell; the ChartQA parquet is public. @@ -290,11 +290,11 @@ always the same provider. | `--judge-provider` | default `--judge-model` | binary in the container | `.env` mounts | |---|---|---|---| -| `claude` (default) | `claude-opus-5` | `claude` | `CLAUDE_PATH`, `CLAUDE_HOME`, `CLAUDE_JSON` | +| `claude` (default) | `sonnet` | `claude` | `CLAUDE_PATH`, `CLAUDE_HOME`, `CLAUDE_JSON` | | `codex` | `gpt-5.6-terra` | `codex` (`node` + the npm package) | `CODEX_NODE`, `CODEX_PACKAGE`, `CODEX_HOME` | | `agy` | none, pass one | `agy` (Antigravity CLI) | `AGY_PATH`, `AGY_GEMINI_HOME`, `AGY_CACHE_HOME` | -`--judge-effort` (default `high`) is passed through as `--effort` to Claude and +`--judge-effort` (default `medium`) is passed through as `--effort` to Claude and as `model_reasoning_effort` to Codex. The run opens with one availability probe (`Reply with exactly OK`) and stops immediately if the provider returns nothing, so a broken login costs seconds, not hours. diff --git a/examples/benchmark/tools/replay_narrate.py b/examples/benchmark/tools/replay_narrate.py index 8f6db8e2..2f2fafe0 100644 --- a/examples/benchmark/tools/replay_narrate.py +++ b/examples/benchmark/tools/replay_narrate.py @@ -33,7 +33,7 @@ def main() -> int: if args.color: os.environ["EVALRX_FORCE_COLOR"] = "1" - from evalrx.eval_agent.narration import LoopNarrator + from evalrx.eval_agent.runlog.narration import LoopNarrator logs = args.run_dir / "logs" if not (logs / "run.json").exists(): diff --git a/examples/benchmark/vlm/gemini/docker-compose.yml b/examples/benchmark/vlm/gemini/docker-compose.yml index 7f9c42be..6596a700 100644 --- a/examples/benchmark/vlm/gemini/docker-compose.yml +++ b/examples/benchmark/vlm/gemini/docker-compose.yml @@ -4,7 +4,7 @@ # GEMINI_API_KEY comes from examples/benchmark/.env (this leaf links to it); CONCURRENCY sets the # parallel discovery requests (default 4). EXTRA_ARGS passes more run.py flags (e.g. # EXTRA_ARGS='--baseline-only --limit 8', '--thinking-level low', '--request-retries 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). --backend gemini is forced for +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). --backend gemini is forced for # the family; the fix ladder is clamped to L2 (no internals, no logprobs). name: bench-vlm-gemini x-gemini: &gemini diff --git a/examples/benchmark/vlm/gemma/docker-compose.yml b/examples/benchmark/vlm/gemma/docker-compose.yml index cb04977d..18ffaafa 100644 --- a/examples/benchmark/vlm/gemma/docker-compose.yml +++ b/examples/benchmark/vlm/gemma/docker-compose.yml @@ -2,7 +2,7 @@ # DATASET=chartqa LIMIT=256 CUDA_VISIBLE_DEVICES=0 docker compose run -d --name vlm-gemma-4-e2b-chartqa gemma-4-e2b # Datasets for this modality: chartqa, spatial457, pope_random, pope_popular, pope_adversarial. # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-vlm-gemma x-gemma: &gemma extends: diff --git a/examples/benchmark/vlm/gemma_jax/docker-compose.yml b/examples/benchmark/vlm/gemma_jax/docker-compose.yml index bd7bc417..28343e11 100644 --- a/examples/benchmark/vlm/gemma_jax/docker-compose.yml +++ b/examples/benchmark/vlm/gemma_jax/docker-compose.yml @@ -6,7 +6,7 @@ # Weights: EVALRX_JAX_CKPT (examples/benchmark/.env) is a host directory holding gemma4--it/ # and tokenizer_gemma4.model, mounted at /ckpt; a size without a mirror there is read from the # public gs://gemma-data bucket on every load. -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-vlm-gemma-jax x-gemma-jax: &gemma_jax extends: diff --git a/examples/benchmark/vlm/nemotron/docker-compose.yml b/examples/benchmark/vlm/nemotron/docker-compose.yml index b5e428b4..8c529e83 100644 --- a/examples/benchmark/vlm/nemotron/docker-compose.yml +++ b/examples/benchmark/vlm/nemotron/docker-compose.yml @@ -2,7 +2,7 @@ # DATASET=chartqa LIMIT=256 CUDA_VISIBLE_DEVICES=0 docker compose run -d --name vlm-nemotron-3-nano-omni-30b-a3b-chartqa nemotron-3-nano-omni-30b-a3b # Datasets for this modality: chartqa, spatial457, pope_random, pope_popular, pope_adversarial. # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-vlm-nemotron x-nemotron: &nemotron extends: diff --git a/examples/benchmark/vlm/qwen/docker-compose.yml b/examples/benchmark/vlm/qwen/docker-compose.yml index 875cf445..edf493aa 100644 --- a/examples/benchmark/vlm/qwen/docker-compose.yml +++ b/examples/benchmark/vlm/qwen/docker-compose.yml @@ -2,7 +2,7 @@ # DATASET=chartqa LIMIT=256 CUDA_VISIBLE_DEVICES=0 docker compose run -d --name vlm-qwen3.5-2b-chartqa qwen3.5-2b # Datasets for this modality: chartqa, spatial457, pope_random, pope_popular, pope_adversarial. # EXTRA_ARGS passes more run.py flags (e.g. EXTRA_ARGS='--baseline-only --limit 8'). -# Judge/coder default to Claude claude-opus-5 at high effort (override via EXTRA_ARGS). +# Judge/coder default to Claude sonnet at medium effort (override via EXTRA_ARGS). name: bench-vlm-qwen x-qwen: &qwen extends: diff --git a/examples/dataset_selection/llm_benchmark/README.md b/examples/dataset_selection/llm_benchmark/README.md index fc9cdc65..44d6406b 100644 --- a/examples/dataset_selection/llm_benchmark/README.md +++ b/examples/dataset_selection/llm_benchmark/README.md @@ -64,8 +64,8 @@ claude --version # 必须有输出 claude # 首次需要交互登录一次完成认证 ``` -**默认 judge 与 coder 都是 `claude-opus-5`,effort `high`**(`config.yaml`)。 -模型名是**钉死的全名而不是 `opus` 别名** —— 别名会随最新 opus 漂移, +**默认 judge 与 coder 都跟随包的默认 Claude 模型(`ClaudeModel.DEFAULT_MODEL`,目前是别名 `sonnet`),effort `high`**(`config.yaml`)。 +要做可比较的多次运行时,请在 `config.yaml` 里把 `judge_model` / `codegen_model` 设成**钉死的全名** —— 别名会随该系列的最新模型漂移, judge 在两次运行之间变了,结果就不可比。 `--effort` 合法值:`low | medium | high | xhigh | max`。 @@ -161,7 +161,7 @@ M2 的工具目录与 e-BH,也不进 M4 / fix 门 —— 证据仍然只来自 M |---|---| | vLLM 加载权重 | 3–6 分钟(冷 page cache 更久) | | Stage 0 `build_cases.py` **全量** | **20 分钟 – 6.5 小时**,见下方逐数据集表 | -| M1→M4 | **30–90 分钟**(judge 是 `claude-opus-5 --effort high`,想得久) | +| M1→M4 | **30–90 分钟**(用 `claude-opus-5 --effort high` 作 judge 时实测,想得久;默认的 sonnet 更快) | | M5 修复 | **20–60 分钟** | **总计 1.5–8 小时**,几乎全部取决于切片大小(judge 用 high effort;调低 `judge_effort` 会快很多)。 建议 `setsid nohup ./run_all.sh ... > run.log 2>&1 &` 后台跑再轮询日志, @@ -598,8 +598,8 @@ $PY run_pipeline.py --model qwen3.5-9b --dataset supergpqa_law | 每例输出 | `logs*/fixes/NN__/outputs.jsonl`(fixed/broken/unchanged 三态) | 声明式候选以前不留任何输出,regressed 无法复盘 | | 判官/coder 看到的 | explore 半区的完整样例(prompt + 模型基线输出 + gold + PASS 对照)、评分规则(`make_scoring_note`)、基线解码、M2/M4/explore 证据、被 M5 反驳的假设 | 之前只有 160 字符的 prompt 开头 | | 家族地板 | `fix_floor_candidates: [self_consistency_5]`(文本任务) | 默认候选以前只在判官沉默时兜底,最基础的多数投票从没进过家族 | -| 并发 | `fix_concurrency: 6`(声明式候选按 case 多线程打 endpoint) | 5 样本 × 80 例串行要一个多小时 | -| **噪声模型** | `fix_baseline_repeats: 5`(基线 = 冻结样本 + 4 次新采样 → 每例通过率),`fix_candidate_repeats: 1` | 配对检验改为对每例通过率之差做 betting e-value(`compare_paired_rates`):不稳定的例子按幅度计权,不再丢弃,也不再让 T=0.6 的单次采样决定 fixed/broken(run7 差 1 个 break) | +| 并发 | `concurrency: 16`(全流程一个开关:fix 阶段把基线采样、声明式候选、coded pipeline 同时发出的调用成批交给模型,模型按这个数并发打 endpoint) | 5 样本 × 80 例串行要一个多小时 | +| **噪声模型** | `fix_baseline_repeats: 5`(基线 = 5 次新采样 → 每例通过率;冻结样本决定了标签,不计入),`fix_candidate_repeats: 1` | 配对检验改为对每例通过率之差做 betting e-value(`compare_paired_rates`):不稳定的例子按幅度计权,不再丢弃,也不再让 T=0.6 的单次采样决定 fixed/broken(run7 差 1 个 break) | `n_samples` 对每种 strategy 都生效(整条 least_to_most / self_refine 链重复 n 次, 按抽出的最终答案投票 —— 之前非 direct 策略会静默忽略 n_samples,而对 CoT 输出按全文投票等于不投票)。 diff --git a/examples/dataset_selection/llm_benchmark/config.yaml b/examples/dataset_selection/llm_benchmark/config.yaml index 19c5f526..fb063a14 100644 --- a/examples/dataset_selection/llm_benchmark/config.yaml +++ b/examples/dataset_selection/llm_benchmark/config.yaml @@ -45,7 +45,10 @@ enable_thinking: false # -> ~24h per model size. Run ONE dataset at a time; do not queue all eight # blindly. Pass an explicit n (./run_all.sh 120) to cap. n_cases: 0 -concurrency: 16 +concurrency: 16 # requests in flight against the endpoint, for every stage: Stage 0, + # the M1 analyzers, the fix stage's baseline, its declarative + # candidates and the calls a coded pipeline makes together. vLLM + # batches them. 1 = serial. # Logprobs over the SAME vLLM endpoint (it supports them; only our wrapper used # to throw them away). Unlocks the `logprob_entropy` and `calibration` @@ -71,12 +74,12 @@ logprobs_top_k: 5 # codegen coder for M2 statistics. Both are `claude -p` CLI calls, NOT the model # under test -- the model under test is the one vLLM is serving. # -# `claude --model` takes either an alias ('opus') or a pinned full name. Pinned -# here on purpose: an alias silently follows whatever the latest opus becomes, -# and a judge that changes underneath a run makes two runs incomparable. -judge_model: claude-opus-5 +# With no model named here both follow the package default +# (ClaudeModel.DEFAULT_MODEL, currently the alias 'sonnet'). An alias follows +# whatever the latest model of that name becomes, and a judge that changes +# underneath a run makes two runs incomparable: for runs you will compare, set +# judge_model / codegen_model to a pinned full name. judge_effort: high # low | medium | high | xhigh | max -codegen_model: claude-opus-5 codegen_effort: high # high effort costs more per call and thinks longer, so the budget and the # per-call timeout both have to come up with it or M2 codegen gets cut off @@ -114,25 +117,22 @@ fix_validation_cases: 0 # 0 = the whole partition (the default since 2026-08 # confirmed on ALL of CONFIRM. The old cap (40, label-stratified) # existed because candidates ran serially (~10 s/case on the 2B) and # an L2 coded pipeline makes 4-5 bridged calls per case; the bridge now - # services calls concurrently (fix_concurrency), and the e>=20 + # answers simultaneous calls as one batch (`concurrency`), and the e>=20 # certification gate is power-bound at n=40. Set N>0 to cap again. fix_exec_timeout_sec: 7200 # wall-clock per coded-pipeline run. Measured 16 s per bridged call # on the 2B (long direct answers): 80 cases x ~5 calls serial would be - # ~1.8 h, which is why the bridge now services calls concurrently - # (fix_concurrency below; since 2026-08-19 requests are id-tagged and - # the coder is told model_generate is thread-safe). The first attempt + # ~1.8 h, which is why the bridge answers the calls that arrive + # together as one batch (requests are id-tagged and the coder is + # told to run one thread per case). The first attempt # must be able to finish, or every coded candidate spends its one # repair round on the timeout instead of on the repair. -fix_concurrency: 12 # parallel model calls in the fix stage: threads per DECLARATIVE - # candidate (L1 templates / L2 specs) over the validation batch, the - # 5-sample baseline, AND how many bridged calls a coded pipeline gets - # serviced at once. vLLM batches them; Stage 0 runs 16. 1 = serial. fix_floor_candidates: # built-in defaults ALWAYS in the tested family for a text-only batch, - self_consistency_5 # next to the judge's proposals (5 samples, vote on the extracted # final answer). Before 2026-08-18 defaults were only a fallback for # a silent judge, so plain self-consistency was never tested. [] = off. -fix_baseline_repeats: 5 # baseline samples per case = frozen Stage 0 output + 4 fresh at the - # batch's own T. Each case gets a PASS RATE and the paired test runs +fix_baseline_repeats: 5 # fresh baseline samples per case at the batch's own T (the frozen + # Stage 0 output labelled the case, so it is not counted). Each case + # gets a PASS RATE and the paired test runs # on rate differences (betting e-value): a case the baseline gets right # 2/5 of the time and a candidate gets right counts +0.6, not +1, and # a fragile "correct" case the candidate misses counts -(its rate), not diff --git a/examples/dataset_selection/llm_benchmark/preflight.py b/examples/dataset_selection/llm_benchmark/preflight.py index 00cebf57..d6657e6d 100755 --- a/examples/dataset_selection/llm_benchmark/preflight.py +++ b/examples/dataset_selection/llm_benchmark/preflight.py @@ -120,7 +120,16 @@ def check_claude() -> None: except Exception: warn("cannot read config.yaml; skipped the judge round-trip") return - model, effort = str(cfg.get("judge_model", "")), str(cfg.get("judge_effort", "")) + # The model the run will use: config.yaml's, else the package default. + model = str(cfg.get("judge_model") or "") + if not model: + try: + from evalrx.agent_runtime.judges.claude import ClaudeModel + + model = ClaudeModel.DEFAULT_MODEL + except ImportError: # reported by the package check; probe the CLI's own default + pass + effort = str(cfg.get("judge_effort", "")) cmd = [exe] if model: cmd += ["--model", model] @@ -144,7 +153,7 @@ def check_claude() -> None: detail = (out.stderr or out.stdout).strip().splitlines() bad(f"judge probe failed for model={model!r} effort={effort!r}: " f"{detail[0][:120] if detail else 'empty reply'}", - "fix judge_model / judge_effort in config.yaml " + "set judge_model / fix judge_effort in config.yaml " "(effort must be low|medium|high|xhigh|max)") diff --git a/examples/dataset_selection/llm_benchmark/run_pipeline.py b/examples/dataset_selection/llm_benchmark/run_pipeline.py index f83918e1..4327af9d 100644 --- a/examples/dataset_selection/llm_benchmark/run_pipeline.py +++ b/examples/dataset_selection/llm_benchmark/run_pipeline.py @@ -4,7 +4,7 @@ python run_pipeline.py --analysis-only # M1->M2->M3, stop before M4/M5 python -m evalrx.cli serve outputs/qwen3.5-9b/supergpqa_law -Stages (evalrx.eval_agent.loop.VLDiagnoseLoop -- the class name says VL, but +Stages (evalrx.eval_agent.loop.diagnose.VLDiagnoseLoop -- the class name says VL, but it takes a plain Model plus an ExperimentProtocol whose target_modalities is {"text"} here, and nothing in it is vision-specific): @@ -57,6 +57,12 @@ CFG = yaml.safe_load((HERE / "config.yaml").read_text()) +# The judge and the coder follow the package default unless config.yaml names a model. +from evalrx.agent_runtime.judges.claude import ClaudeModel # noqa: E402 + +JUDGE_MODEL = str(CFG.get("judge_model") or ClaudeModel.DEFAULT_MODEL) +CODEGEN_MODEL = str(CFG.get("codegen_model") or ClaudeModel.DEFAULT_MODEL) + # ---------------------------------------------------------------- model #: Appended in ``mode="answer"`` so the scored tokens are an ANSWER rather than @@ -108,7 +114,7 @@ class EndpointModel(Model): def __init__(self, model_id: str, base_url: str, max_tokens: int, sampling: dict, logprobs_mode: str = "answer", logprobs_max_tokens: int = 64, - logprobs_top_k: int = 5): + logprobs_top_k: int = 5, concurrency: int = 1): from evalrx.core.capability import Capability self.capabilities = frozenset({Capability.GENERATE, Capability.LOGPROBS}) @@ -123,10 +129,13 @@ def __init__(self, model_id: str, base_url: str, max_tokens: int, sampling: dict self.n_calls = 0 self.n_truncated = 0 self.n_logprob_calls = 0 - # M1 analyzers and the fix module's declarative candidates call - # generate() from worker threads; the counters are read as telemetry - # (the fix module diffs n_truncated around each candidate), so they - # must not lose increments. + # Requests in flight for one generate_batch: the M1 analyzers and the + # fix stage hand their independent prompts over as a batch, and the + # vLLM server batches whatever arrives together. + self.concurrency = max(1, int(concurrency)) + # generate() therefore runs on worker threads; the counters are read + # as telemetry (the fix module diffs n_truncated around each + # candidate), so they must not lose increments. import threading self._lock = threading.Lock() @@ -487,7 +496,7 @@ def _spends_gpu(cls) -> bool: src = inspect.getsource(cls) except (OSError, TypeError): return True # unknown: cap it rather than risk another straggler - return "model.generate(" in src or "model.logprobs(" in src + return any(call in src for call in ("model.generate(", "model.generate_batch(", "Ask(", "model.logprobs(")) def build_analyzer_overrides(max_cases: int, model=None, verbose: bool = True) -> dict: @@ -695,7 +704,7 @@ def build_codegen(backend: str): effort = str(CFG.get("codegen_effort", "") or "") return CliAgentConfig( provider=provider, - model=str(CFG.get("codegen_model", "claude-opus-5")) if is_claude else "", + model=CODEGEN_MODEL if is_claude else "", max_budget_usd=float(CFG.get("codegen_budget_usd", 2.0)), timeout_sec=int(CFG.get("codegen_timeout_sec", 480)), extra_args=(("--effort", effort) if (effort and is_claude) else ()), @@ -729,7 +738,7 @@ def main() -> None: ap.add_argument("--model", default=CFG["model"]) ap.add_argument("--base-url", default=CFG["base_url"]) ap.add_argument("--dataset", default=CFG["dataset"]) - ap.add_argument("--judge-model", default=CFG["judge_model"]) + ap.add_argument("--judge-model", default=JUDGE_MODEL) ap.add_argument("--judge-effort", default=CFG["judge_effort"]) ap.add_argument("--backend", default="claude", choices=["claude", "codex", "agy"]) ap.add_argument("--max-cycles", type=int, default=CFG["max_cycles"]) @@ -830,7 +839,8 @@ def main() -> None: "top_p": float(CFG["top_p"]), "top_k": int(CFG["top_k"])}, logprobs_mode=str(CFG.get("logprobs_mode", "answer")), logprobs_max_tokens=int(CFG.get("logprobs_max_tokens", 64)), - logprobs_top_k=int(CFG.get("logprobs_top_k", 5))) + logprobs_top_k=int(CFG.get("logprobs_top_k", 5)), + concurrency=int(CFG.get("concurrency", 1))) judge = build_judge(args.judge_model, args.judge_effort, timeout_sec=int(CFG.get("judge_timeout_sec", 240))) codegen = build_codegen(args.backend) @@ -851,7 +861,7 @@ def main() -> None: if args.analyzer_max_cases > 0 else {}) # A confirm-only pass logs beside the analysis it reuses, never over it. # RunLogger writes run.json + one JSON per M-stage (M1/log.json .. - # M5/log.json) under this dir — see evalrx/eval_agent/RUN_LOGGER.md. + # M5/log.json) under this dir — see evalrx/eval_agent/runlog/README.md. logger = RunLogger(run_dir=out / ("logs_confirm" if args.confirm_only else "logs"), verbose=True) @@ -909,11 +919,8 @@ def main() -> None: baseline_generation_kwargs={"max_tokens": max_tokens, "temperature": float(CFG["temperature"]), "top_p": float(CFG["top_p"])}, - # Declarative candidates run their cases in parallel against the - # endpoint (coded pipelines stay serial through the bridge). - concurrency=int(CFG.get("fix_concurrency", 1)), - # Noise model: the baseline is a per-case PASS RATE (frozen sample - # + k-1 fresh at the batch's own T), the paired test runs on rate + # Noise model: the baseline is a per-case PASS RATE (k fresh + # samples at the batch's own T), the paired test runs on rate # differences (betting e-value) — sampling-unstable cases are # weighed, not dropped, and one T=0.6 sample per arm no longer # decides fixed/broken. Candidates default to one pass (coded diff --git a/examples/m1_m5/audiocaps_hallucination_qwen2_audio/docker-compose.yml b/examples/m1_m5/audiocaps_hallucination_qwen2_audio/docker-compose.yml index a23d208d..8e12f022 100644 --- a/examples/m1_m5/audiocaps_hallucination_qwen2_audio/docker-compose.yml +++ b/examples/m1_m5/audiocaps_hallucination_qwen2_audio/docker-compose.yml @@ -38,4 +38,4 @@ services: count: all capabilities: [gpu] command: > - sh -c "python download_audiohallucination.py --limit 300 --scan-rows 2000 && python run.py --model qwen2-audio-7b-instruct --limit 300 --judge-provider claude --judge-model claude-opus-5 --judge-effort high" + sh -c "python download_audiohallucination.py --limit 300 --scan-rows 2000 && python run.py --model qwen2-audio-7b-instruct --limit 300 --judge-provider claude --judge-effort high" diff --git a/examples/m1_m5/audiocaps_hallucination_qwen2_audio/run.py b/examples/m1_m5/audiocaps_hallucination_qwen2_audio/run.py index f4f48515..dad77137 100644 --- a/examples/m1_m5/audiocaps_hallucination_qwen2_audio/run.py +++ b/examples/m1_m5/audiocaps_hallucination_qwen2_audio/run.py @@ -194,7 +194,7 @@ def build_judge(provider: str, model_name: str, effort: str) -> "Any": else: from evalrx.eval_agent import ClaudeModel - model_name = model_name or "sonnet" + model_name = model_name or ClaudeModel.DEFAULT_MODEL judge = ClaudeModel(model=model_name, effort=effort) label = f"claude model={model_name} effort={effort or 'default'}" empty_hint = f"claude --model {model_name} returned empty (rate-limited?) -- try --judge-model sonnet or haiku" @@ -426,6 +426,11 @@ def main() -> int: help="fast wiring check (no GPU/model/judge) -- see module docstring", ) args = parser.parse_args() + if args.judge_provider == "claude" and not args.judge_model: + from evalrx.eval_agent import ClaudeModel + + # The package default, named once so the coder follows the judge. + args.judge_model = ClaudeModel.DEFAULT_MODEL if args.smoke_test: _run_smoke_test(args) diff --git a/examples/m1_m5/chartqa_qwen3_5_2b/README.md b/examples/m1_m5/chartqa_qwen3_5_2b/README.md index 1774a8c2..28b1dfc1 100644 --- a/examples/m1_m5/chartqa_qwen3_5_2b/README.md +++ b/examples/m1_m5/chartqa_qwen3_5_2b/README.md @@ -29,9 +29,10 @@ docker compose logs -f and, like every analyzer since 2026-08-21, each measures its whole partition (no per-analyzer `max_cases` cap). -The compose command pins judge and coder to Claude Opus 5 -(`--judge-provider claude --judge-model claude-opus-5 --judge-effort high`); -the CLI default provider is `agy`. With no M4-verified hypothesis the run +The compose command runs judge and coder on Claude at high effort +(`--judge-provider claude --judge-effort high`), on the package's default +Claude model (`ClaudeModel.DEFAULT_MODEL`, currently `sonnet`); add +`--judge-model ` to pin another. The CLI default provider is `agy`. With no M4-verified hypothesis the run still enters M5 and the fix stage on the best unverified leads (`allow_unverified=True` in `vlm_benchmark_common.py`). diff --git a/examples/m1_m5/chartqa_qwen3_5_2b/docker-compose.yml b/examples/m1_m5/chartqa_qwen3_5_2b/docker-compose.yml index cefd558e..f97c0d5c 100644 --- a/examples/m1_m5/chartqa_qwen3_5_2b/docker-compose.yml +++ b/examples/m1_m5/chartqa_qwen3_5_2b/docker-compose.yml @@ -28,4 +28,4 @@ services: # Judge = claude (sonnet, high effort). The frozen sample is deterministic # (seeded), so re-running the downloader is a no-op once data/ exists. command: > - sh -c "python download_chartqa.py --limit 256 --seed 5022 && python run.py --limit 256 --judge-provider claude --judge-model claude-opus-5 --judge-effort high --run-dir outputs" + sh -c "python download_chartqa.py --limit 256 --seed 5022 && python run.py --limit 256 --judge-provider claude --judge-effort high --run-dir outputs" diff --git a/examples/m1_m5/deco_chair/config.yaml b/examples/m1_m5/deco_chair/config.yaml index 6f76e822..af95d0b1 100755 --- a/examples/m1_m5/deco_chair/config.yaml +++ b/examples/m1_m5/deco_chair/config.yaml @@ -16,10 +16,10 @@ min_effect: 0.03 explore_frac: 0.6 # Judge for M1 selection / M2 / M3 / M4 + codegen coder — both are claude -p CLI -# calls; fable-5 is currently unavailable, so both use opus-4-8 low effort. -judge_model: claude-opus-4-8 +# calls at low effort. With no model named here they follow the package default +# (ClaudeModel.DEFAULT_MODEL, currently sonnet); set judge_model / codegen_model +# to pin one. judge_effort: low -codegen_model: claude-opus-4-8 codegen_effort: low codegen_budget_usd: 2.0 codegen_timeout_sec: 240 diff --git a/examples/m1_m5/deco_chair/run.py b/examples/m1_m5/deco_chair/run.py index b2d6e889..2ddd4128 100755 --- a/examples/m1_m5/deco_chair/run.py +++ b/examples/m1_m5/deco_chair/run.py @@ -43,6 +43,12 @@ OUT = Path(__file__).parent / "outputs" CFG = yaml.safe_load((Path(__file__).parent / "config.yaml").read_text()) +# The judge and the coder follow the package default unless config.yaml names a model. +from evalrx.agent_runtime.judges.claude import ClaudeModel # noqa: E402 + +JUDGE_MODEL = str(CFG.get("judge_model") or ClaudeModel.DEFAULT_MODEL) +CODEGEN_MODEL = str(CFG.get("codegen_model") or ClaudeModel.DEFAULT_MODEL) + # --------------------------------------------------------------------------- # CHAIR scoring (synonym map -> COCO category) with a recall floor @@ -223,7 +229,7 @@ def main() -> None: ap.add_argument("--max-analyzers", type=int, default=3) ap.add_argument("--smoke-test", action="store_true") ap.add_argument("--skip-m5", action="store_true") - ap.add_argument("--judge-model", default=CFG.get("judge_model", "claude-opus-4-8")) + ap.add_argument("--judge-model", default=JUDGE_MODEL) ap.add_argument("--judge-effort", default=CFG.get("judge_effort", "low")) ap.add_argument("--device", default="cuda") ap.add_argument("--dtype", default="bfloat16") @@ -271,7 +277,7 @@ def main() -> None: codegen_effort = str(CFG.get("codegen_effort", "") or "") codegen = CliAgentConfig( provider="claude_code", - model=str(CFG.get("codegen_model", "claude-opus-4-8")), + model=CODEGEN_MODEL, max_budget_usd=float(CFG.get("codegen_budget_usd", 2.0)), timeout_sec=int(CFG.get("codegen_timeout_sec", 240)), extra_args=(("--effort", codegen_effort) if codegen_effort else ()), diff --git a/examples/m1_m5/deco_hallu/config.yaml b/examples/m1_m5/deco_hallu/config.yaml index c51ace78..9819c44b 100755 --- a/examples/m1_m5/deco_hallu/config.yaml +++ b/examples/m1_m5/deco_hallu/config.yaml @@ -5,10 +5,10 @@ model: qwen3-vl-2b-instruct # also available: 4b / 8b (build_cases.py) # Judge for M1 selection / M2 / M3 / M4 + codegen coder — both are claude -p CLI -# calls; fable-5 is currently unavailable, so both use opus-4-8 low effort. -judge_model: claude-opus-4-8 +# calls at low effort. With no model named here they follow the package default +# (ClaudeModel.DEFAULT_MODEL, currently sonnet); set judge_model / codegen_model +# to pin one. judge_effort: low -codegen_model: claude-opus-4-8 codegen_effort: low codegen_budget_usd: 2.0 codegen_timeout_sec: 480 # bundled figure skills (eval-chart-style/nature-figure) add read+apply time diff --git a/examples/m1_m5/deco_hallu/run.py b/examples/m1_m5/deco_hallu/run.py index d3aedd38..88e9855b 100755 --- a/examples/m1_m5/deco_hallu/run.py +++ b/examples/m1_m5/deco_hallu/run.py @@ -37,6 +37,12 @@ OUT = HERE / "outputs" CFG = yaml.safe_load((HERE / "config.yaml").read_text()) +# The judge and the coder follow the package default unless config.yaml names a model. +from evalrx.agent_runtime.judges.claude import ClaudeModel # noqa: E402 + +JUDGE_MODEL = str(CFG.get("judge_model") or ClaudeModel.DEFAULT_MODEL) +CODEGEN_MODEL = str(CFG.get("codegen_model") or ClaudeModel.DEFAULT_MODEL) + # --------------------------------------------------------------------------- # 1. Frozen manifest -> CaseBatch (mixed PASS/FAIL — M2/M4 need both groups) @@ -117,7 +123,7 @@ def build_codegen(backend: str = "claude", skills=(), allow_skills: bool = False effort = str(CFG.get("codegen_effort", "") or "") cfg = CliAgentConfig( provider=provider, - model=str(CFG.get("codegen_model", "claude-opus-4-8")) if is_claude else "", + model=CODEGEN_MODEL if is_claude else "", max_budget_usd=float(CFG.get("codegen_budget_usd", 2.0)), timeout_sec=int(CFG.get("codegen_timeout_sec", 240)), extra_args=(("--effort", effort) if (effort and is_claude) else ()), @@ -207,7 +213,7 @@ def main() -> None: ap.add_argument("--max-analyzers", type=int, default=3) ap.add_argument("--smoke-test", action="store_true") ap.add_argument("--skip-m5", action="store_true") - ap.add_argument("--judge-model", default=CFG.get("judge_model", "claude-opus-4-8")) + ap.add_argument("--judge-model", default=JUDGE_MODEL) ap.add_argument("--judge-effort", default=CFG.get("judge_effort", "low")) ap.add_argument("--device", default="cuda") ap.add_argument("--dtype", default="bfloat16") @@ -249,7 +255,7 @@ def main() -> None: codegen_effort = str(CFG.get("codegen_effort", "") or "") codegen = CliAgentConfig( provider="claude_code", - model=str(CFG.get("codegen_model", "claude-opus-4-8")), + model=CODEGEN_MODEL, max_budget_usd=float(CFG.get("codegen_budget_usd", 2.0)), timeout_sec=int(CFG.get("codegen_timeout_sec", 240)), extra_args=(("--effort", codegen_effort) if codegen_effort else ()), diff --git a/examples/m1_m5/deco_hallu/run_analysis.py b/examples/m1_m5/deco_hallu/run_analysis.py index 007b8aeb..5fbe92fd 100644 --- a/examples/m1_m5/deco_hallu/run_analysis.py +++ b/examples/m1_m5/deco_hallu/run_analysis.py @@ -43,7 +43,7 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model", default=run.CFG["model"]) - ap.add_argument("--judge-model", default=run.CFG.get("judge_model", "claude-opus-4-8")) + ap.add_argument("--judge-model", default=run.JUDGE_MODEL) ap.add_argument("--judge-effort", default=run.CFG.get("judge_effort", "low")) ap.add_argument("--backend", default="claude", choices=["claude", "codex", "agy"], help="coder backend for M2 stats codegen (default claude)") diff --git a/examples/m1_m5/deco_hallu/run_confirm_fix.py b/examples/m1_m5/deco_hallu/run_confirm_fix.py index 394f1367..25de425c 100644 --- a/examples/m1_m5/deco_hallu/run_confirm_fix.py +++ b/examples/m1_m5/deco_hallu/run_confirm_fix.py @@ -40,7 +40,7 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model", default=run.CFG["model"]) ap.add_argument("--skip-m5", action="store_true") - ap.add_argument("--judge-model", default=run.CFG.get("judge_model", "claude-opus-4-8")) + ap.add_argument("--judge-model", default=run.JUDGE_MODEL) ap.add_argument("--judge-effort", default=run.CFG.get("judge_effort", "low")) ap.add_argument("--backend", default="claude", choices=["claude", "codex", "agy"], help="coder backend for M5/fix codegen (default claude)") diff --git a/examples/m1_m5/deco_hallu/run_m1.py b/examples/m1_m5/deco_hallu/run_m1.py index 59f41ab7..762f6ea1 100755 --- a/examples/m1_m5/deco_hallu/run_m1.py +++ b/examples/m1_m5/deco_hallu/run_m1.py @@ -30,7 +30,7 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--model", default=run.CFG["model"]) ap.add_argument("--max-analyzers", type=int, default=3) - ap.add_argument("--judge-model", default=run.CFG.get("judge_model", "claude-opus-4-8")) + ap.add_argument("--judge-model", default=run.JUDGE_MODEL) ap.add_argument("--judge-effort", default=run.CFG.get("judge_effort", "low")) ap.add_argument("--device", default="cuda") ap.add_argument("--dtype", default="bfloat16") @@ -57,7 +57,7 @@ def main() -> None: codegen_effort = str(run.CFG.get("codegen_effort", "") or "") codegen = CliAgentConfig( provider="claude_code", - model=str(run.CFG.get("codegen_model", "claude-opus-4-8")), + model=run.CODEGEN_MODEL, max_budget_usd=float(run.CFG.get("codegen_budget_usd", 2.0)), timeout_sec=int(run.CFG.get("codegen_timeout_sec", 240)), extra_args=(("--effort", codegen_effort) if codegen_effort else ()), diff --git a/examples/m1_m5/deco_hallu/run_m2-5.py b/examples/m1_m5/deco_hallu/run_m2-5.py index c857839f..2858e2e5 100755 --- a/examples/m1_m5/deco_hallu/run_m2-5.py +++ b/examples/m1_m5/deco_hallu/run_m2-5.py @@ -38,7 +38,7 @@ def main() -> None: ap.add_argument("--max-cycles", type=int, default=1, help="only one M1 pass was frozen, so default 1 cycle") ap.add_argument("--skip-m5", action="store_true") - ap.add_argument("--judge-model", default=run.CFG.get("judge_model", "claude-opus-4-8")) + ap.add_argument("--judge-model", default=run.JUDGE_MODEL) ap.add_argument("--judge-effort", default=run.CFG.get("judge_effort", "low")) ap.add_argument("--backend", default="claude", choices=["claude", "codex", "agy"], help="coder backend for M2/M5/fix codegen (default claude)") diff --git a/examples/m1_m5/deco_miss/config.yaml b/examples/m1_m5/deco_miss/config.yaml index 19db71f7..875a48c6 100755 --- a/examples/m1_m5/deco_miss/config.yaml +++ b/examples/m1_m5/deco_miss/config.yaml @@ -5,10 +5,10 @@ model: qwen3-vl-2b-instruct # also available: 4b / 8b (build_cases.py) max_correct: 120 # cap correct (PASS) cases; every MISS is kept # Judge for M1 selection / M2 / M3 / M4 + codegen coder — both are claude -p CLI -# calls; fable-5 is currently unavailable, so both use opus-4-8 low effort. -judge_model: claude-opus-4-8 +# calls at low effort. With no model named here they follow the package default +# (ClaudeModel.DEFAULT_MODEL, currently sonnet); set judge_model / codegen_model +# to pin one. judge_effort: low -codegen_model: claude-opus-4-8 codegen_effort: low codegen_budget_usd: 2.0 codegen_timeout_sec: 240 diff --git a/examples/m1_m5/deco_miss/run.py b/examples/m1_m5/deco_miss/run.py index 3077c80f..96860495 100755 --- a/examples/m1_m5/deco_miss/run.py +++ b/examples/m1_m5/deco_miss/run.py @@ -35,6 +35,12 @@ OUT = HERE / "outputs" CFG = yaml.safe_load((HERE / "config.yaml").read_text()) +# The judge and the coder follow the package default unless config.yaml names a model. +from evalrx.agent_runtime.judges.claude import ClaudeModel # noqa: E402 + +JUDGE_MODEL = str(CFG.get("judge_model") or ClaudeModel.DEFAULT_MODEL) +CODEGEN_MODEL = str(CFG.get("codegen_model") or ClaudeModel.DEFAULT_MODEL) + # --------------------------------------------------------------------------- # 1. Frozen manifest -> CaseBatch (mixed PASS/FAIL — M2/M4 need both groups) @@ -152,7 +158,7 @@ def main() -> None: ap.add_argument("--max-analyzers", type=int, default=3) ap.add_argument("--smoke-test", action="store_true") ap.add_argument("--skip-m5", action="store_true") - ap.add_argument("--judge-model", default=CFG.get("judge_model", "claude-opus-4-8")) + ap.add_argument("--judge-model", default=JUDGE_MODEL) ap.add_argument("--judge-effort", default=CFG.get("judge_effort", "low")) ap.add_argument("--max-correct", type=int, default=CFG.get("max_correct", 120), help="cap PASS (correct) cases; every MISS is always kept") @@ -194,7 +200,7 @@ def main() -> None: codegen_effort = str(CFG.get("codegen_effort", "") or "") codegen = CliAgentConfig( provider="claude_code", - model=str(CFG.get("codegen_model", "claude-opus-4-8")), + model=CODEGEN_MODEL, max_budget_usd=float(CFG.get("codegen_budget_usd", 2.0)), timeout_sec=int(CFG.get("codegen_timeout_sec", 240)), extra_args=(("--effort", codegen_effort) if codegen_effort else ()), diff --git a/examples/m1_m5/deco_pope/config.yaml b/examples/m1_m5/deco_pope/config.yaml index 8ac2511c..964459e3 100755 --- a/examples/m1_m5/deco_pope/config.yaml +++ b/examples/m1_m5/deco_pope/config.yaml @@ -16,17 +16,15 @@ top_p: 0.9 min_effect: 0.05 # pre-registered minimum effect for the fix explore_frac: 0.6 -# Judge for M1 selection / M2 / M3 / M4 (claude -p CLI). fable-5 is currently -# unavailable via the CLI ("Claude Fable 5 is currently unavailable"), so both -# claude -p roles (judge + codegen coder) use opus-4-8 low effort. -judge_model: claude-opus-4-8 +# Judge for M1 selection / M2 / M3 / M4 (claude -p CLI), at low effort. With no +# model named here it follows the package default (ClaudeModel.DEFAULT_MODEL, +# currently sonnet); set judge_model to pin one. judge_effort: low # Pipeline-autonomy codegen (tier-(b) probe generator, stats tools, M5 # experiment writer, fix module) — the loop writes its own code via this CLI -# agent (claude -p). Opus 4.8 low-effort: stronger coder than the fable-low -# judge, so probe/fix code is more likely to satisfy the sandbox contract. -codegen_model: claude-opus-4-8 +# agent (claude -p). It follows the package default too; set codegen_model to +# pin one. codegen_effort: low codegen_budget_usd: 2.0 codegen_timeout_sec: 240 diff --git a/examples/m1_m5/deco_pope/run.py b/examples/m1_m5/deco_pope/run.py index 5703d747..2e594dd8 100755 --- a/examples/m1_m5/deco_pope/run.py +++ b/examples/m1_m5/deco_pope/run.py @@ -32,6 +32,12 @@ OUT = Path(__file__).parent / "outputs" CFG = yaml.safe_load((Path(__file__).parent / "config.yaml").read_text()) +# The judge and the coder follow the package default unless config.yaml names a model. +from evalrx.agent_runtime.judges.claude import ClaudeModel # noqa: E402 + +JUDGE_MODEL = str(CFG.get("judge_model") or ClaudeModel.DEFAULT_MODEL) +CODEGEN_MODEL = str(CFG.get("codegen_model") or ClaudeModel.DEFAULT_MODEL) + # --------------------------------------------------------------------------- # 1. Frozen manifest -> CaseBatch (mixed PASS/FAIL — M2/M4 need both groups) @@ -107,8 +113,8 @@ def drift_check(model, cases, n: int = 10) -> None: def build_judge(model_name: str, effort: str): """Claude CLI judge for M2/M3/M4 (agy quota exhausted — swapped 2026-06-12). - Default claude-fable-5 at low effort; pass --judge-model sonnet|haiku for - cheap wiring tests. A tiny generation probe catches dead sessions early + Default: the package's Claude model at low effort; pass --judge-model haiku + for cheap wiring tests. A tiny generation probe catches dead sessions early (an empty response means rate-limit/quota, not an error exit). """ from evalrx.eval_agent import ClaudeModel @@ -154,7 +160,7 @@ def main() -> None: ap.add_argument("--max-analyzers", type=int, default=3) ap.add_argument("--smoke-test", action="store_true") ap.add_argument("--skip-m5", action="store_true") - ap.add_argument("--judge-model", default=CFG.get("judge_model", "claude-fable-5")) + ap.add_argument("--judge-model", default=JUDGE_MODEL) ap.add_argument("--judge-effort", default=CFG.get("judge_effort", "low")) ap.add_argument("--max-clean-images", type=int, default=0, help="shrink input by image: keep all fail-images + this many " @@ -207,7 +213,7 @@ def main() -> None: codegen_effort = str(CFG.get("codegen_effort", "") or "") codegen = CliAgentConfig( provider="claude_code", - model=str(CFG.get("codegen_model", "sonnet")), + model=CODEGEN_MODEL, max_budget_usd=float(CFG.get("codegen_budget_usd", 2.0)), timeout_sec=int(CFG.get("codegen_timeout_sec", 240)), # claude -p --effort ; appended verbatim to the CLI command diff --git a/examples/m1_m5/mmau_qwen2_audio/docker-compose.yml b/examples/m1_m5/mmau_qwen2_audio/docker-compose.yml index 55aa3a99..cc157489 100644 --- a/examples/m1_m5/mmau_qwen2_audio/docker-compose.yml +++ b/examples/m1_m5/mmau_qwen2_audio/docker-compose.yml @@ -38,4 +38,4 @@ services: count: all capabilities: [gpu] command: > - sh -c "python download_mmau.py --limit 1000 --scan-rows 1000 && python run.py --model qwen2-audio-7b-instruct --limit 896 --judge-provider claude --judge-model claude-opus-5 --judge-effort high" + sh -c "python download_mmau.py --limit 1000 --scan-rows 1000 && python run.py --model qwen2-audio-7b-instruct --limit 896 --judge-provider claude --judge-effort high" diff --git a/examples/m1_m5/mmau_qwen2_audio/run.py b/examples/m1_m5/mmau_qwen2_audio/run.py index bded3e6d..40180dca 100644 --- a/examples/m1_m5/mmau_qwen2_audio/run.py +++ b/examples/m1_m5/mmau_qwen2_audio/run.py @@ -216,7 +216,7 @@ def build_judge(provider: str, model_name: str, effort: str) -> "Any": elif provider == "claude": from evalrx.eval_agent import ClaudeModel - model_name = model_name or "claude-fable-5" + model_name = model_name or ClaudeModel.DEFAULT_MODEL judge = ClaudeModel(model=model_name, effort=effort) label = f"claude model={model_name} effort={effort or 'default'}" empty_hint = f"claude --model {model_name} returned empty (rate-limited?) -- try --judge-model sonnet or haiku" @@ -634,7 +634,7 @@ def main() -> int: parser.add_argument( "--judge-model", default="", help="model name passed to the judge CLI. Empty = provider default " - "(claude-fable-5 for --judge-provider claude; gpt-5.6-terra for " + "(sonnet for --judge-provider claude; gpt-5.6-terra for " "--judge-provider codex; agy session default for --judge-provider agy).", ) parser.add_argument("--judge-effort", default="low") @@ -688,6 +688,11 @@ def main() -> int: help="fast wiring check (no GPU/model/judge) -- see module docstring", ) args = parser.parse_args() + if args.judge_provider == "claude" and not args.judge_model: + from evalrx.eval_agent import ClaudeModel + + # The package default, named once so the coder follows the judge. + args.judge_model = ClaudeModel.DEFAULT_MODEL if args.smoke_test: _run_smoke_test(args) @@ -778,6 +783,19 @@ def baseline_generate(row: dict[str, Any]) -> str: diagnosis_agent = None if args.analysis_only else DiagnosisAgent(judge=judge) hypothesis_tester = None if args.analysis_only else HypothesisTester(judge=judge, min_effect=0.05) + from evalrx.eval_agent import CliAgentConfig, SurgeryAgent + from evalrx.eval_agent.stages.experiment_writer import ExperimentWriterConfig + + coder_cfg = CliAgentConfig( + provider={"agy": "antigravity", "claude": "claude_code", "codex": "codex"}[args.judge_provider], + model=(args.judge_model or "gpt-5.6-terra") if args.judge_provider == "codex" else args.judge_model, + timeout_sec=900, + extra_args=( + () if args.judge_provider in {"agy", "codex"} + else (("--effort", args.judge_effort) if args.judge_effort else ()) + ), + ) + fix_agent = FixAgent( judge=judge, max_tier=args.fix_max_tier, @@ -804,18 +822,6 @@ def baseline_generate(row: dict[str, Any]) -> str: print(f" explore/confirm split: {len(cases) - n_confirm} explore " f"(M1-M4 discovery) / {n_confirm} confirm (held out for run_fix)") - from evalrx.eval_agent import CliAgentConfig, SurgeryAgent - from evalrx.eval_agent.stages.experiment_writer import ExperimentWriterConfig - - coder_cfg = CliAgentConfig( - provider={"agy": "antigravity", "claude": "claude_code", "codex": "codex"}[args.judge_provider], - model=(args.judge_model or "gpt-5.6-terra") if args.judge_provider == "codex" else args.judge_model, - timeout_sec=900, - extra_args=( - () if args.judge_provider in {"agy", "codex"} - else (("--effort", args.judge_effort) if args.judge_effort else ()) - ), - ) explorer = None if args.explore and not args.analysis_only: from evalrx.agent_runtime.sandbox import ExperimentSandbox diff --git a/examples/m1_m5/musicavqa_videollama2/config.yaml b/examples/m1_m5/musicavqa_videollama2/config.yaml index 60dccb25..e1804da1 100644 --- a/examples/m1_m5/musicavqa_videollama2/config.yaml +++ b/examples/m1_m5/musicavqa_videollama2/config.yaml @@ -14,10 +14,10 @@ model: videollama2.1-7b-av model_path: DAMO-NLP-SG/VideoLLaMA2.1-7B-AV # Judge for M1 selection / M2 / M3 / M4 + codegen coder — both are `claude -p` -# CLI calls (this host's own authenticated `claude` binary). -judge_model: sonnet +# CLI calls (this host's own authenticated `claude` binary). With no model named +# here they follow the package default (ClaudeModel.DEFAULT_MODEL, currently +# sonnet); set judge_model / codegen_model to pin one. judge_effort: low -codegen_model: sonnet codegen_effort: low codegen_budget_usd: 2.0 codegen_timeout_sec: 240 diff --git a/examples/m1_m5/musicavqa_videollama2/run.py b/examples/m1_m5/musicavqa_videollama2/run.py index 55493e56..42537f3c 100644 --- a/examples/m1_m5/musicavqa_videollama2/run.py +++ b/examples/m1_m5/musicavqa_videollama2/run.py @@ -49,6 +49,12 @@ OUT = Path(__file__).parent / "outputs" CFG = yaml.safe_load((Path(__file__).parent / "config.yaml").read_text()) +# The judge and the coder follow the package default unless config.yaml names a model. +from evalrx.agent_runtime.judges.claude import ClaudeModel # noqa: E402 + +JUDGE_MODEL = str(CFG.get("judge_model") or ClaudeModel.DEFAULT_MODEL) +CODEGEN_MODEL = str(CFG.get("codegen_model") or ClaudeModel.DEFAULT_MODEL) + # See the module docstring for why this is pinned rather than judge-selected. # self_consistency + perturbation_battery are the two analyzers that produced # a verified (statistically-supported, protocol-consistent) hypothesis on a @@ -120,7 +126,7 @@ def main() -> None: help="use MockAVModel instead of the real checkpoint (drift_check " "+ any loop step that calls the model stay wiring-only)") ap.add_argument("--skip-m5", action="store_true") - ap.add_argument("--judge-model", default=CFG.get("judge_model", "claude-opus-4-8")) + ap.add_argument("--judge-model", default=JUDGE_MODEL) ap.add_argument("--judge-effort", default=CFG.get("judge_effort", "low")) ap.add_argument("--device", default="cpu") ap.add_argument("--load-4bit", action="store_true") @@ -175,7 +181,7 @@ def main() -> None: codegen_effort = str(CFG.get("codegen_effort", "") or "") codegen = CliAgentConfig( provider="claude_code", - model=str(CFG.get("codegen_model", "claude-opus-4-8")), + model=CODEGEN_MODEL, max_budget_usd=float(CFG.get("codegen_budget_usd", 2.0)), timeout_sec=int(CFG.get("codegen_timeout_sec", 240)), extra_args=(("--effort", codegen_effort) if codegen_effort else ()), diff --git a/examples/m1_m5/qwen_loop_claude/run.py b/examples/m1_m5/qwen_loop_claude/run.py index 152267e1..f18257f8 100755 --- a/examples/m1_m5/qwen_loop_claude/run.py +++ b/examples/m1_m5/qwen_loop_claude/run.py @@ -371,9 +371,8 @@ def _pick_agy_model() -> str: ) -# Claude judge candidates: the user's session model first (Fable), then -# cheaper aliases. Probed in order; first responder wins. -_CLAUDE_JUDGE_CANDIDATES = ("claude-fable-5", "sonnet", "haiku") +# Claude judge candidates, probed in order; first responder wins. +_CLAUDE_JUDGE_CANDIDATES = ("sonnet", "haiku") def _pick_claude_model() -> str: diff --git a/examples/m1_m5/spatial457_qwen3_5_2b/README.md b/examples/m1_m5/spatial457_qwen3_5_2b/README.md index e87f78e7..be00e9cb 100644 --- a/examples/m1_m5/spatial457_qwen3_5_2b/README.md +++ b/examples/m1_m5/spatial457_qwen3_5_2b/README.md @@ -29,9 +29,10 @@ docker compose logs -f and, like every analyzer since 2026-08-21, each measures its whole partition (no per-analyzer `max_cases` cap). -The compose command pins judge and coder to Claude Opus 5 -(`--judge-provider claude --judge-model claude-opus-5 --judge-effort high`); -the CLI default provider is `agy`. With no M4-verified hypothesis the run +The compose command runs judge and coder on Claude at high effort +(`--judge-provider claude --judge-effort high`), on the package's default +Claude model (`ClaudeModel.DEFAULT_MODEL`, currently `sonnet`); add +`--judge-model ` to pin another. The CLI default provider is `agy`. With no M4-verified hypothesis the run still enters M5 and the fix stage on the best unverified leads (`allow_unverified=True` in `vlm_benchmark_common.py`). diff --git a/examples/m1_m5/spatial457_qwen3_5_2b/docker-compose.yml b/examples/m1_m5/spatial457_qwen3_5_2b/docker-compose.yml index 77ba5212..33aa3ac3 100644 --- a/examples/m1_m5/spatial457_qwen3_5_2b/docker-compose.yml +++ b/examples/m1_m5/spatial457_qwen3_5_2b/docker-compose.yml @@ -28,4 +28,4 @@ services: # Judge = claude (sonnet, high effort). The frozen sample is deterministic # (seeded), so re-running the downloader is a no-op once data/ exists. command: > - sh -c "python download_spatial457.py --limit 256 --seed 7457 && python run.py --limit 256 --judge-provider claude --judge-model claude-opus-5 --judge-effort high --run-dir outputs" + sh -c "python download_spatial457.py --limit 256 --seed 7457 && python run.py --limit 256 --judge-provider claude --judge-effort high --run-dir outputs" diff --git a/examples/m1_m5/vlm_benchmark_common.py b/examples/m1_m5/vlm_benchmark_common.py index a46b53d8..21553bd8 100644 --- a/examples/m1_m5/vlm_benchmark_common.py +++ b/examples/m1_m5/vlm_benchmark_common.py @@ -172,6 +172,11 @@ def main(config: BenchmarkConfig) -> None: parser.add_argument("--run-dir", default="outputs") parser.add_argument("--smoke-test", action="store_true") args = parser.parse_args() + if args.judge_provider == "claude" and not args.judge_model: + from evalrx.eval_agent import ClaudeModel + + # The package default, named once so the coder follows the judge. + args.judge_model = ClaudeModel.DEFAULT_MODEL manifest = Path(args.manifest) if args.smoke_test: @@ -220,7 +225,7 @@ def main(config: BenchmarkConfig) -> None: from evalrx.eval_agent import ClaudeModel judge = ClaudeModel( - model=args.judge_model or "sonnet", + model=args.judge_model, effort=args.judge_effort, timeout_sec=300, ) diff --git a/examples/m2_m3/deco_hallu_explore/README.md b/examples/m2_m3/deco_hallu_explore/README.md index 244229f6..fc650bee 100644 --- a/examples/m2_m3/deco_hallu_explore/README.md +++ b/examples/m2_m3/deco_hallu_explore/README.md @@ -120,7 +120,8 @@ bash run_attn_pipeline.sh # full arc (phase 3 on GPU) SKIP_FIX=1 bash run_attn_pipeline.sh # stop after held-out testing (no GPU) ``` -Env overrides: `CODER_MODEL` / `JUDGE_MODEL` (e.g. `claude-opus-4-8`), +Env overrides: `CODER_MODEL` / `JUDGE_MODEL` (unset = the package's default +Claude model, currently `sonnet`), `CODER_PROVIDER` (`claude_code`/`antigravity`/`codex`), `OUT_ROOT` (default `outputs_pipeline`), `DEVICE` (default `cuda`), `TIMEOUT_SEC`, `SKIP_FIX=1`, `PY` (python interpreter for the host phases). diff --git a/examples/m2_m3/deco_hallu_explore/run_attn_pipeline.sh b/examples/m2_m3/deco_hallu_explore/run_attn_pipeline.sh index e6516715..6133a820 100755 --- a/examples/m2_m3/deco_hallu_explore/run_attn_pipeline.sh +++ b/examples/m2_m3/deco_hallu_explore/run_attn_pipeline.sh @@ -18,7 +18,7 @@ cd "$(dirname "$0")" CODER_PROVIDER="${CODER_PROVIDER:-claude_code}" CODER_MODEL="${CODER_MODEL:-}" -JUDGE_MODEL="${JUDGE_MODEL:-claude-opus-4-8}" +JUDGE_MODEL="${JUDGE_MODEL:-}" # empty = the package's default Claude model OUT_ROOT="${OUT_ROOT:-outputs_pipeline}" DEVICE="${DEVICE:-cuda}" PY="${PY:-python3}" @@ -40,7 +40,9 @@ if [[ -n "$CODER_MODEL" ]]; then cmd+=(--model "$CODER_MODEL"); fi "${cmd[@]}" echo "=== phase 2: held-out hypothesis testing (validate half) ===" -"$PY" test_hypotheses.py --pipeline-root "$OUT_ROOT" --judge-model "$JUDGE_MODEL" +judge=() +if [[ -n "$JUDGE_MODEL" ]]; then judge+=(--judge-model "$JUDGE_MODEL"); fi +"$PY" test_hypotheses.py --pipeline-root "$OUT_ROOT" "${judge[@]}" if [[ "${SKIP_FIX:-0}" == "1" ]]; then echo "SKIP_FIX=1 — stopping after phase 2." diff --git a/examples/m2_m3/deco_hallu_explore/run_surgery.py b/examples/m2_m3/deco_hallu_explore/run_surgery.py index 6cb24c2c..d1a4c1bf 100644 --- a/examples/m2_m3/deco_hallu_explore/run_surgery.py +++ b/examples/m2_m3/deco_hallu_explore/run_surgery.py @@ -161,10 +161,10 @@ def main() -> None: SurgeryAgent, VLDiagnoseLoop, ) - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.models.backends.base import RuntimeConfig - judge = loop_run.build_judge(loop_run.CFG.get("judge_model", "claude-opus-4-8"), + judge = loop_run.build_judge(loop_run.JUDGE_MODEL, loop_run.CFG.get("judge_effort", "low")) model = compose(args.model, "hf_local", runtime=RuntimeConfig(device=args.device, dtype=args.dtype), diff --git a/examples/m2_m3/deco_hallu_explore/test_hypotheses.py b/examples/m2_m3/deco_hallu_explore/test_hypotheses.py index 0e49b7b9..e53d0fac 100644 --- a/examples/m2_m3/deco_hallu_explore/test_hypotheses.py +++ b/examples/m2_m3/deco_hallu_explore/test_hypotheses.py @@ -104,7 +104,8 @@ def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--pipeline-root", default="outputs_pipeline") ap.add_argument("--validate-dir", default=str(HERE / "data_attn_validate")) - ap.add_argument("--judge-model", default="claude-opus-4-8") + ap.add_argument("--judge-model", default=None, + help="Claude model for the judge (default: the package default)") ap.add_argument("--judge-effort", default="low") ap.add_argument("--alpha", type=float, default=0.05) ap.add_argument("--no-judge", action="store_true", @@ -199,7 +200,8 @@ def main() -> None: if hypotheses and not args.no_judge: from evalrx.eval_agent import ClaudeModel - judge = ClaudeModel(model=args.judge_model, effort=args.judge_effort) + judge = ClaudeModel(model=args.judge_model or ClaudeModel.DEFAULT_MODEL, + effort=args.judge_effort) for h in hypotheses: prompt = JUDGE_PROMPT.format( statement=h.get("statement", ""), basis=h.get("basis", ""), diff --git a/pyproject.toml b/pyproject.toml index 8aa0960e..e08943d3 100755 --- a/pyproject.toml +++ b/pyproject.toml @@ -161,7 +161,7 @@ include = ["evalrx*"] [tool.setuptools.package-data] # Ship the published run log JSON Schema so non-Python consumers can # validate the log without installing evalrx. -"evalrx.eval_agent" = ["run_log.schema.json"] +"evalrx.eval_agent.runlog" = ["run_log.schema.json"] # Ship bundled Agent Skills (e.g. nature-figure) so `pip install` carries them # too, not just `git clone`. explore auto-applies them on claude/agy backends. "evalrx.agent_assets" = ["skills/**/*"] diff --git a/tests/test_analysis/test_audit_fixes.py b/tests/test_analysis/test_audit_fixes.py index 35416216..a8a2e12c 100644 --- a/tests/test_analysis/test_audit_fixes.py +++ b/tests/test_analysis/test_audit_fixes.py @@ -21,7 +21,7 @@ compile_recipes, per_case_to_records, ) -from evalrx.eval_agent.loop import VLDiagnoseLoop +from evalrx.eval_agent.loop.stages import Stages class _FakeResult: @@ -94,12 +94,12 @@ def test_loop_bridge_does_not_overwrite_real_analyzer(): probe_results = {"explored": real, "saliency": _FakeResult([{"case_id": "c0", "obj_size": 20}])} recipe = SignalRecipe(name="small", kind="expr", expr="saliency_obj_size < 40") me = SimpleNamespace( - _signal_recipes=[recipe], - _bridge_analyzer_name="explored", + signal_recipes=[recipe], + bridge_analyzer_name="explored", model="m", store=SimpleNamespace(add_result=lambda r: None), ) - VLDiagnoseLoop._bridge_signals(me, probe_results, None) + Stages.bridge_signals(me, probe_results, None) assert probe_results["explored"] is real # the real analyzer is untouched # the bridge landed under a deduped, non-colliding key diff --git a/tests/test_analysis/test_bridge_inloop.py b/tests/test_analysis/test_bridge_inloop.py index 6ce5a5d2..54cfecfb 100644 --- a/tests/test_analysis/test_bridge_inloop.py +++ b/tests/test_analysis/test_bridge_inloop.py @@ -11,7 +11,7 @@ safe_ident, ) from evalrx.analysis.stats_tools import build_stats_input -from evalrx.eval_agent.loop import VLDiagnoseLoop +from evalrx.eval_agent.loop.stages import Stages class _FakeResult: @@ -103,14 +103,14 @@ def test_bridge_returns_none_when_nothing_compiles(): # --------------------------------------------------------------------------- -# VLDiagnoseLoop._bridge_signals wiring (tested on a lightweight fake self) +# Stages.bridge_signals wiring (tested on a lightweight fake self) # --------------------------------------------------------------------------- def _fake_loop_self(recipes): added = [] return SimpleNamespace( - _signal_recipes=recipes, - _bridge_analyzer_name="explored", + signal_recipes=recipes, + bridge_analyzer_name="explored", model="m", store=SimpleNamespace(add_result=added.append), _added=added, @@ -125,7 +125,7 @@ def test_loop_bridge_signals_injects_synthetic_analyzer(): probe_results = _probe_results() me = _fake_loop_self([recipe]) - VLDiagnoseLoop._bridge_signals(me, probe_results, None) + Stages.bridge_signals(me, probe_results, None) assert "explored" in probe_results assert len(me._added) == 1 # also recorded into the store @@ -137,7 +137,7 @@ def test_loop_bridge_signals_is_noop_without_recipes(): probe_results = _probe_results() me = _fake_loop_self([]) - VLDiagnoseLoop._bridge_signals(me, probe_results, None) + Stages.bridge_signals(me, probe_results, None) assert "explored" not in probe_results assert me._added == [] @@ -154,7 +154,7 @@ def test_loop_bridge_raises_stats_signal_cap_so_bridged_signals_are_tested(): me = _fake_loop_self([recipe]) me.stats_agent = agent - VLDiagnoseLoop._bridge_signals(me, probe_results, None) + Stages.bridge_signals(me, probe_results, None) # 3 signals now in the family: saliency.obj_size, saliency.attention, explored.small assert agent._max_signal_tools >= 3 diff --git a/tests/test_analysis/test_case_partitions.py b/tests/test_analysis/test_case_partitions.py index 085eab26..83580c32 100644 --- a/tests/test_analysis/test_case_partitions.py +++ b/tests/test_analysis/test_case_partitions.py @@ -9,7 +9,7 @@ from __future__ import annotations from evalrx.core import CaseBatch, FailureCase, Label -from evalrx.eval_agent.run_logger import RunLogger +from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data diff --git a/tests/test_analysis/test_dynamic_report.py b/tests/test_analysis/test_dynamic_report.py index 30f3b24b..87500c87 100644 --- a/tests/test_analysis/test_dynamic_report.py +++ b/tests/test_analysis/test_dynamic_report.py @@ -6,7 +6,7 @@ def test_publish_report_contract_and_case_records(tmp_path): from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import load_published_report, publish_report logger = RunLogger(tmp_path) @@ -61,7 +61,7 @@ def generate(self, _prompt): def test_invalid_agent_output_falls_back(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import load_published_report, publish_report logger = RunLogger(tmp_path) @@ -83,7 +83,7 @@ def test_dynamic_api_filters_and_serves_spa(tmp_path): from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import publish_report from evalrx.reporting.server import create_app @@ -109,7 +109,7 @@ def test_runs_panel_lists_and_opens_sibling_experiments(tmp_path): from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import publish_report from evalrx.reporting.server import create_app @@ -166,7 +166,7 @@ def test_an_uploaded_run_gets_its_own_id_and_an_empty_server_names_no_run(tmp_pa from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.server import create_app run = tmp_path / "shared" / "logs" @@ -210,7 +210,7 @@ def test_runs_listing_keeps_the_most_recent_past_the_display_limit(tmp_path, mon from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting import server as server_mod monkeypatch.setattr(server_mod, "RUNS_DISPLAY_LIMIT", 2) @@ -242,7 +242,7 @@ def test_runs_listing_keeps_the_most_recent_past_the_display_limit(tmp_path, mon def test_runs_discovery_does_not_descend_into_a_found_runs_data_dir(tmp_path): from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.server import discover_runs run = tmp_path / "exp" / "outputs" / "logs" @@ -263,7 +263,7 @@ def test_runs_discovery_does_not_descend_into_a_found_runs_data_dir(tmp_path): def test_external_case_media_is_copied_into_durable_run(tmp_path): from evalrx.core import CaseBatch, FailureCase, Inputs - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.run_events import read_run_events media = tmp_path / "source.wav" @@ -283,7 +283,7 @@ def test_external_case_media_is_copied_into_durable_run(tmp_path): def _report_of_cases(tmp_path, cases): from evalrx.core import CaseBatch - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data run = tmp_path / "run" @@ -347,7 +347,7 @@ def test_case_choices_and_task_come_from_the_case_metadata(tmp_path): def test_m1_examples_are_logged_and_reconstructed_from_case_evidence(tmp_path): from evalrx.core import CaseBatch, FailureCase, Label, Result - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data case = FailureCase.from_prompt( @@ -389,7 +389,7 @@ def test_explicit_run_log_wins_over_a_nested_logs_subrun(tmp_path): def test_read_only_run_can_be_served_without_publishing(tmp_path, monkeypatch): from fastapi.testclient import TestClient - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.server import create_app logger = RunLogger(tmp_path) @@ -411,7 +411,7 @@ def test_case_media_is_served_from_the_copy_inside_the_run(tmp_path): from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Inputs - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.server import create_app source = tmp_path / "data" / "clip.wav" @@ -462,7 +462,7 @@ def _v2_run_with_explore_snapshot(tmp_path, report: dict, figure_names: list[str """A run whose explore step left its workdir to be inlined on the event.""" from types import SimpleNamespace - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger # Not beside logs/: the logger inlines it from the runtime tree. workdir = tmp_path / "sandbox" / "explore" @@ -549,7 +549,7 @@ def test_v2_explore_snapshot_links_takeaways_to_the_charts_they_cite(tmp_path): def test_v2_explore_event_without_a_snapshot_report_still_renders_its_sentences(tmp_path): # A run recorded before the snapshot carried the report (or one whose # report was over the inline cap) keeps the sentence-level fallback. - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data run_dir = tmp_path / "logs" @@ -614,7 +614,7 @@ def test_m5_confirmation_joins_the_winning_candidate_the_logger_recorded(tmp_pat from types import SimpleNamespace from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data logger = RunLogger(tmp_path, observability_mode="offline") @@ -704,7 +704,7 @@ def test_a_fused_output_reads_as_an_explore_report(tmp_path): def test_a_loop_run_beside_an_explore_report_stays_a_loop_run(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data _explore_output(tmp_path) @@ -770,7 +770,7 @@ def test_static_export_escapes_script_terminators(tmp_path): def test_report_reads_model_m1_and_m4_status(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.run_data import extract_run_data logger = RunLogger(tmp_path, observability_mode="offline") @@ -792,7 +792,7 @@ def test_report_reads_model_m1_and_m4_status(tmp_path): def test_langfuse_bundle_export(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.observability import export_to_langfuse_bundle logger = RunLogger(tmp_path / "run", observability_mode="offline") @@ -830,7 +830,7 @@ def test_serve_opens_an_explore_output_and_its_figures(tmp_path): def test_a_run_is_finished_once_its_logger_closes(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data from evalrx.reporting.server import _compile_report @@ -852,7 +852,7 @@ def test_a_run_is_finished_once_its_logger_closes(tmp_path): def test_follow_run_streams_updates_until_the_run_ends(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.server import RunRegistry, follow_run logger = RunLogger(tmp_path, observability_mode="offline") @@ -872,7 +872,7 @@ def test_follow_run_streams_updates_until_the_run_ends(tmp_path): def test_follow_run_ends_at_once_for_a_finished_run_and_yields_to_a_reconnect(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.server import RunRegistry, follow_run logger = RunLogger(tmp_path / "done", observability_mode="offline") @@ -891,7 +891,7 @@ def test_follow_run_ends_at_once_for_a_finished_run_and_yields_to_a_reconnect(tm def test_finalize_leaves_run_end_last_after_the_fix_step(tmp_path): from types import SimpleNamespace - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext from evalrx.reporting.dynamic import build_report_data from evalrx.reporting.run_events import read_run_events @@ -910,7 +910,7 @@ def test_finalize_leaves_run_end_last_after_the_fix_step(tmp_path): def test_a_second_logger_in_the_same_directory_is_followed_until_it_ends(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.server import RunRegistry, follow_run first = RunLogger(tmp_path, observability_mode="offline") diff --git a/tests/test_analyzers/test_reasoning_probes.py b/tests/test_analyzers/test_reasoning_probes.py index c2ff4602..e0b53422 100644 --- a/tests/test_analyzers/test_reasoning_probes.py +++ b/tests/test_analyzers/test_reasoning_probes.py @@ -674,8 +674,11 @@ def test_knowledge_split_shares_are_over_classified_failures(): _case("q2", None, "Paris", Label.FAIL), # no context -> unclassifiable ]) model = ScriptModel([ - "Answer: Lyon", "Answer: Lyon", "- a fact", "Answer: Lyon", "Answer: Paris", - "Answer: Lyon", "Answer: Lyon", "- a fact", "Answer: Lyon", + # both cases' first questions go out together, then their follow-ups + "Answer: Lyon", "Answer: Lyon", "- a fact", # q1: baseline, decomposed, recall + "Answer: Lyon", "Answer: Lyon", "- a fact", # q2 + "Answer: Lyon", "Answer: Paris", # q1: from its own facts, open book + "Answer: Lyon", # q2: from its own facts ]) f = KnowledgeReasoningSplit().run(model, batch).findings assert f["n_classified"] == 1 and f["n_unclassified"] == 1 diff --git a/tests/test_analyzers/test_text_probes.py b/tests/test_analyzers/test_text_probes.py index 35a57b75..36927e27 100644 --- a/tests/test_analyzers/test_text_probes.py +++ b/tests/test_analyzers/test_text_probes.py @@ -443,3 +443,98 @@ def test_answer_fn_still_detects_genuine_disagreement(): f = SelfConsistencyAnalyzer(n=4, semantic=False, answer_fn=extract_answer).run( _chain_model(["(A)", "(B)", "(A)", "(C)"]), _one_case()).findings assert f["consistency"] == 0.5 and f["n_unique"] == 3 + + +# ── the remaining per-case loops ask in batches ─────────────────────────────── + + +class BatchLog(PromptAwareModel): + """PromptAwareModel that records the size of every batch it is given.""" + + def __init__(self) -> None: + super().__init__([]) + self.generate_batches: list[int] = [] + self.logprob_batches: list[int] = [] + + def generate_batch(self, inputs, **kwargs): + self.generate_batches.append(len(inputs)) + return [self.generate(item, **kwargs) for item in inputs] + + def logprobs_batch(self, inputs, **kwargs): + self.logprob_batches.append(len(inputs)) + return [self.logprobs(item, **kwargs) for item in inputs] + + +def test_shapley_coalitions_are_exactly_what_the_estimator_evaluates(): + from evalrx.analyzers.perturbation._shapley import coalitions, shapley_values + + asked: list[frozenset] = [] + + def value(kept: set) -> float: + asked.append(frozenset(kept)) + return float(len(kept)) + (2.0 if 1 in kept else 0.0) + + direct = shapley_values(range(4), value, n_samples=6, seed=3) + planned = coalitions(range(4), n_samples=6, seed=3) + + assert planned == asked and planned[0] == frozenset() + table = {kept: float(len(kept)) + (2.0 if 1 in kept else 0.0) for kept in planned} + assert shapley_values(range(4), lambda kept: table[frozenset(kept)], n_samples=6, seed=3) == direct + + +def test_context_shap_asks_every_ablation_of_every_case_in_one_batch(): + ctx = "Alice owns a red car.\n\nBob owns a blue bike." + cases = CaseBatch([ + FailureCase(inputs=Inputs(prompt=f"Context:\n{ctx}\n\nWhat colour is Alice's car? ({i})"), + observed="red", label=Label.PASS, metadata={"context": ctx}) + for i in range(3) + ]) + model = BatchLog() + + rows = ContextShapAnalyzer(n_samples=8, seed=0).run(model, cases).findings["per_case"] + + assert len(model.generate_batches) == 1 # two chunks: at most four coalitions a case + assert model.generate_batches[0] <= 12 + assert all(row["top_chunk_index"] == 0 for row in rows) + + +def test_calibration_scores_logprobs_in_one_batch_and_survives_one_bad_case(): + batch = CaseBatch([ + FailureCase(id=f"c{i}", inputs=Inputs(prompt=f"q{i}"), + label=Label.PASS if i % 2 == 0 else Label.FAIL) + for i in range(4) + ]) + model = BatchLog() + assert CalibrationAnalyzer().run(model, batch).findings["logprob_channel"]["n"] == 4 + assert model.logprob_batches == [4] + + class OneBad(BatchLog): + def logprobs(self, inputs, **kwargs): + if inputs.prompt == "q2": + raise TimeoutError("endpoint timed out") + return super().logprobs(inputs, **kwargs) + + findings = CalibrationAnalyzer().run(OneBad(), batch).findings + assert findings["logprob_channel"]["n"] == 3 + (bad,) = [row for row in findings["per_case"] if "logprob_error" in row] + assert bad["sample_id"] == "c2" and "TimeoutError" in bad["logprob_error"] + + +def test_verbalized_confidence_asks_with_the_case_image(): + from evalrx.analyzers.uncertainty.verbalized_conf import VerbalizedConfidenceAnalyzer + + seen: list[Inputs] = [] + + class Sees(ScriptModel): + def generate(self, inputs, **kwargs): + seen.append(inputs) + return "A cat.\nConfidence: 80" + + picture = object() + case = FailureCase(inputs=Inputs(prompt="What animal is this?", image=picture)) + + findings = VerbalizedConfidenceAnalyzer().run(Sees(["x"]), CaseBatch([case])).findings + + assert findings["verbalized_confidence"] == 0.8 + assert seen[0].image is picture and seen[0].prompt.startswith("What animal is this?") + assert "Confidence:" in seen[0].prompt diff --git a/tests/test_benchmark/test_runner_run.py b/tests/test_benchmark/test_runner_run.py index 0a6cada4..28a3d4de 100644 --- a/tests/test_benchmark/test_runner_run.py +++ b/tests/test_benchmark/test_runner_run.py @@ -17,7 +17,7 @@ from evalrx.benchmark.tasks import get from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.eval_agent import CaseDiscoveryAgent, VLDiagnoseLoop -from evalrx.eval_agent.loop_reports import AutoDiagnoseReport +from evalrx.eval_agent.loop.report import AutoDiagnoseReport from evalrx.eval_agent.stages.fix.tiers import FixTier from evalrx.eval_agent.stages.fix.types import FixCandidate, FixOutcome, FixValidation from evalrx.reporting.run_events import read_run_events @@ -75,8 +75,9 @@ def load_model(*_a): cell.calls.append("load_model") return target, dict(GEN), get_spec(resolved.spec_key) - def discover(_agent, _model, candidates, protocol=None): + def discover(agent, _model, candidates, protocol=None): cell.calls.append(f"discover:{len(candidates)}") + cell.label_samples = agent.n_samples batch = CaseBatch(list(candidates)) return SimpleNamespace(cases=batch, n_pass=len(batch) // 2, n_fail=len(batch) - len(batch) // 2, n_unknown=0, has_m4_groups=cell.has_m4_groups) @@ -126,6 +127,29 @@ def cell(monkeypatch, tmp_path): return Cell(monkeypatch, tmp_path) +def test_a_sampling_cell_labels_by_five_answers_and_a_greedy_one_by_one(cell): + assert cell.run("--baseline-only") == 0 + assert cell.label_samples == 5 # llm tasks sample at T=0.6 + assert cell.read("baseline.json")["label_samples"] == 5 + + assert cell.run("--baseline-only", "--temperature", "0") == 0 + assert cell.label_samples == 1 + + assert cell.run("--baseline-only", "--label-samples", "3") == 0 + assert cell.label_samples == 3 + + +def test_the_baseline_file_carries_each_case_votes_and_the_split_count(): + cases = _batch("c", 3) + cases[0].metadata["discovery_votes"] = {"pass": 1, "fail": 4} + cases[1].metadata["discovery_votes"] = {"pass": 5, "fail": 0} + + rows = runner._case_labels(cases) + + assert rows[0]["votes"] == {"pass": 1, "fail": 4} and "votes" not in rows[2] + assert runner._split_votes(cases) == 1 + + def test_a_full_cell_runs_discovery_diagnosis_m5_and_the_fix_then_closes_the_log(cell, capsys): assert cell.run() == 0 @@ -174,8 +198,7 @@ def test_the_loop_is_wired_from_the_arguments(cell): assert loop.probe_agent.allow_codegen is True assert loop.fix_agent.proposer._floor_candidates == () config = cell.config() - assert (config["m1_workers"], config["m1_codegen"], config["m1_selection"], config["m2_codegen"]) == ( - 8, True, "judge", True) + assert (config["m1_codegen"], config["m1_selection"], config["m2_codegen"]) == (True, "judge", True) assert (config["split_mode"], config["n_cases"], config["manifest_seed"]) == ("explore_confirm", 8, 11) diff --git a/tests/test_contract/test_stage_detail.py b/tests/test_contract/test_stage_detail.py index d29e8445..7865f01f 100644 --- a/tests/test_contract/test_stage_detail.py +++ b/tests/test_contract/test_stage_detail.py @@ -60,7 +60,7 @@ def test_a_full_m1_to_m5_run_conforms(tmp_path): def test_a_logged_run_with_examples_and_a_repair_conforms(tmp_path): from evalrx.core import CaseBatch, FailureCase, Label, Result - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data cases = CaseBatch([ @@ -88,7 +88,7 @@ def test_a_logged_run_with_examples_and_a_repair_conforms(tmp_path): def test_an_empty_run_conforms(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.reporting.dynamic import build_report_data logger = RunLogger(tmp_path, observability_mode="offline") diff --git a/tests/test_core/test_generate_batch.py b/tests/test_core/test_generate_batch.py new file mode 100644 index 00000000..0e107d77 --- /dev/null +++ b/tests/test_core/test_generate_batch.py @@ -0,0 +1,161 @@ +"""Batch generation: the Model default, the per-case probe driver, and the run log.""" + +from __future__ import annotations + +import pytest + +from evalrx.core.analyzer import Ask, labelled_answers, run_probes +from evalrx.core.case import FailureCase, Inputs +from evalrx.eval_agent.runlog.context import RunContext +from evalrx.eval_agent.runlog.instrumentation import InstrumentedModel +from evalrx.reporting.run_events import read_run_events +from tests.conftest import FakeModel + + +class Echo(FakeModel): + """Answers ````; fails on a prompt containing ``boom``.""" + + def __init__(self) -> None: + super().__init__() + self.calls: list[tuple[str, dict]] = [] + + def generate(self, inputs, **kwargs) -> str: + prompt = inputs.prompt if isinstance(inputs, Inputs) else str(inputs) + self.calls.append((prompt, kwargs)) + if "boom" in prompt: + raise TimeoutError(prompt) + return f"<{prompt}>" + + +class Batched(Echo): + """A backend with a real batch call, which fails as a whole.""" + + def generate_batch(self, inputs, **kwargs): + self.batches = getattr(self, "batches", 0) + 1 + return [self.generate(item, **kwargs) for item in inputs] + + +def test_the_default_batch_asks_one_at_a_time_in_order(): + model = Echo() + assert model.generate_batch(["a", "b"], temperature=1.0) == ["", ""] + assert model.calls == [("a", {"temperature": 1.0}), ("b", {"temperature": 1.0})] + with pytest.raises(TimeoutError): + model.generate_batch(["a", "boom"]) + + +def test_a_tolerant_batch_returns_the_error_in_place_without_repeating_calls(): + model = Echo() + first, failed, last = model.try_generate_batch(["a", "boom", "c"]) + assert (first, last) == ("", "") and isinstance(failed, TimeoutError) + assert [prompt for prompt, _ in model.calls] == ["a", "boom", "c"] + + +def test_a_tolerant_batch_tries_a_real_batch_call_first(): + model = Batched() + assert model.try_generate_batch(["a", "b"]) == ["", ""] and model.batches == 1 + _, failed = model.try_generate_batch(["a", "boom"]) # the batch raised: asked one by one + assert isinstance(failed, TimeoutError) + + +def test_probes_advance_together_and_each_gets_its_own_answers(): + model = Echo() + + def probe(name: str): + first, second = yield Ask([f"{name}1", f"{name}2"]) + if name == "b": + return [first, second] + (third,) = yield Ask([f"{name}3 after {first}"], {"temperature": 1.0}) + return [first, second, third] + + rows = run_probes(model, [probe(name) for name in "abc"]) + + assert rows == [["", "", ">"], ["", ""], + ["", "", ">"]] + # one round per Ask: every case's first questions, then the follow-ups + assert [prompt for prompt, _ in model.calls] == [ + "a1", "a2", "b1", "b2", "c1", "c2", "a3 after ", "c3 after "] + assert model.calls[-1][1] == {"temperature": 1.0} + + +def test_a_probe_that_asks_nothing_returns_its_row(): + def probe(): + return {"skipped": "no gold answer"} + yield # pragma: no cover - makes this a generator + + assert run_probes(Echo(), [probe()]) == [{"skipped": "no gold answer"}] + + +def test_a_tolerant_run_hands_the_probe_its_error(): + def probe(prompt: str): + (answer,) = yield Ask([prompt]) + return "failed" if isinstance(answer, Exception) else answer + + assert run_probes(Echo(), [probe("a"), probe("boom")], tolerant=True) == ["", "failed"] + with pytest.raises(TimeoutError): + run_probes(Echo(), [probe("boom")]) + + +def test_labelled_answers_reads_the_stored_answer_and_asks_only_for_the_rest(): + model = Echo() + cases = [FailureCase(inputs=Inputs(prompt="q1"), observed="stored"), + FailureCase(inputs=Inputs(prompt="q2"))] + assert labelled_answers(model, cases) == ["stored", ""] + assert [prompt for prompt, _ in model.calls] == ["q2"] + + +def test_a_batch_is_logged_as_one_call_per_input_sharing_its_time(tmp_path): + ctx = RunContext(tmp_path / "run", verbose=False) + model = InstrumentedModel(Echo(), ctx.logger, cycle=0, analyzer="probe") + + assert model.generate_batch(["a", "b"]) == ["", ""] + _, failed = model.try_generate_batch(["c", "boom"]) + assert isinstance(failed, TimeoutError) + ctx.finalize() + + calls = [e for e in read_run_events(ctx.root) if e["event"] == "model_call"] + assert [c["output"] for c in calls] == ["", "", "", None] + assert all(c["batch_size"] == 2 for c in calls) and "TimeoutError" in calls[-1]["error"] + assert [c["call_index"] for c in calls] == [1, 2, 3, 4] + + +def test_a_model_runs_its_concurrency_of_generate_calls_at_once_and_keeps_the_order(): + import threading + import time + + class Endpoint(Echo): + concurrency = 4 + + def __init__(self) -> None: + super().__init__() + self.now = self.peak = 0 + self._lock = threading.Lock() + + def generate(self, inputs, **kwargs) -> str: + with self._lock: + self.now += 1 + self.peak = max(self.peak, self.now) + time.sleep(0.05) + with self._lock: + self.now -= 1 + return super().generate(inputs, **kwargs) + + model = Endpoint() + prompts = [str(i) for i in range(12)] + + assert model.generate_batch(prompts) == [f"<{p}>" for p in prompts] + assert model.peak == 4 + out = model.try_generate_batch(["a", "boom", "b"]) + assert out[0] == "" and isinstance(out[1], TimeoutError) and out[2] == "" + + +def test_logprobs_batch_scores_each_input_and_logs_one_call_each(tmp_path): + ctx = RunContext(tmp_path / "run", verbose=False) + model = InstrumentedModel(FakeModel(), ctx.logger, cycle=0, analyzer="probe") + + rows = model.logprobs_batch(["a", "b", "c"]) + ctx.finalize() + + assert len(rows) == 3 and all(row and row[0].token for row in rows) + calls = [e for e in read_run_events(ctx.root) if e["event"] == "model_call"] + assert [c["method"] for c in calls] == ["logprobs"] * 3 + assert all(c["batch_size"] == 3 for c in calls) diff --git a/tests/test_eval_agent/test_agent_architecture.py b/tests/test_eval_agent/test_agent_architecture.py index 9bac0c21..cc0f05a4 100644 --- a/tests/test_eval_agent/test_agent_architecture.py +++ b/tests/test_eval_agent/test_agent_architecture.py @@ -37,7 +37,7 @@ def test_codegen_runner_is_the_stage_cli_invocation_boundary(): production_paths = [ *(ROOT / "evalrx" / "analysis").glob("*.py"), *(EVAL_AGENT / "stages").rglob("*.py"), - *(EVAL_AGENT / "agentic").glob("*.py"), + *(EVAL_AGENT / "loop").rglob("*.py"), EVAL_AGENT / "nl_runner.py", ] @@ -137,7 +137,7 @@ def test_stage_prompt_templates_live_in_prompt_modules(): offenders: list[str] = [] for path in [ *(EVAL_AGENT / "stages").rglob("*.py"), - *(EVAL_AGENT / "agentic").glob("*.py"), + *(EVAL_AGENT / "loop").rglob("*.py"), *ANALYSIS.glob("*.py"), ]: tree = _tree(path) diff --git a/tests/test_eval_agent/test_agentic_actions.py b/tests/test_eval_agent/test_agentic_actions.py index e034d2f6..7d75d74f 100644 --- a/tests/test_eval_agent/test_agentic_actions.py +++ b/tests/test_eval_agent/test_agentic_actions.py @@ -9,14 +9,14 @@ import pytest from pydantic import ValidationError -from evalrx.eval_agent.agentic.actions import ( +from evalrx.eval_agent.loop.judge.actions import ( Action, _fallback_action, action_model, decide, ) -from evalrx.eval_agent.agentic.board import EvidenceBoard -from evalrx.eval_agent.agentic.tools import ToolOutcome, ToolRegistry, ToolSpec +from evalrx.eval_agent.loop.judge.board import EvidenceBoard +from evalrx.eval_agent.loop.judge.tools import ToolOutcome, ToolRegistry, ToolSpec def _registry() -> ToolRegistry: diff --git a/tests/test_eval_agent/test_agentic_launch_smoke.py b/tests/test_eval_agent/test_agentic_launch_smoke.py index 7300646c..21438c77 100644 --- a/tests/test_eval_agent/test_agentic_launch_smoke.py +++ b/tests/test_eval_agent/test_agentic_launch_smoke.py @@ -15,8 +15,8 @@ from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.core.result import Result from evalrx.eval_agent import DiagnosisAgent, HypothesisTester, JudgePolicy, VLDiagnoseLoop -from evalrx.eval_agent.log_schema import validate_event -from evalrx.eval_agent.run_context import RunContext +from evalrx.eval_agent.runlog.context import RunContext +from evalrx.eval_agent.runlog.schema import validate_event from evalrx.eval_agent.stages.probe_agent import ProbeAgent from evalrx.eval_agent.stages.protocol import ExperimentProtocol from evalrx.reporting.run_events import read_run_events diff --git a/tests/test_eval_agent/test_agentic_probe_tools.py b/tests/test_eval_agent/test_agentic_probe_tools.py index aba61294..7888a2c9 100644 --- a/tests/test_eval_agent/test_agentic_probe_tools.py +++ b/tests/test_eval_agent/test_agentic_probe_tools.py @@ -13,14 +13,14 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.eval_agent import DiagnosisAgent, HypothesisTester, JudgePolicy, VLDiagnoseLoop -from evalrx.eval_agent.agentic.actions import Action -from evalrx.eval_agent.agentic.board import EvidenceBoard -from evalrx.eval_agent.agentic.tools import ( +from evalrx.eval_agent.loop.judge.actions import Action +from evalrx.eval_agent.loop.judge.board import EvidenceBoard +from evalrx.eval_agent.loop.judge.tools import ( _requested_probes, build_default_registry, ) -from evalrx.eval_agent.policy import RunState -from evalrx.eval_agent.run_context import RunContext +from evalrx.eval_agent.loop.state import RunState +from evalrx.eval_agent.runlog.context import RunContext from evalrx.eval_agent.stages.probe_agent import ProbeAgent from evalrx.eval_agent.stages.protocol import ExperimentProtocol from tests.conftest import FakeModel @@ -73,7 +73,7 @@ def _setup(tmp_path, model=None, judge=None): run_logger=ctx.logger, ) data = _cases() - state = RunState(original_data=data, data=data, judge=judge) + state = RunState(original_data=data, data=data, stages=loop.stages(), judge=judge) return loop, state, build_default_registry(loop, state), EvidenceBoard() diff --git a/tests/test_eval_agent/test_agentic_search_probes_tool.py b/tests/test_eval_agent/test_agentic_search_probes_tool.py index 356833d6..0c60c652 100644 --- a/tests/test_eval_agent/test_agentic_search_probes_tool.py +++ b/tests/test_eval_agent/test_agentic_search_probes_tool.py @@ -6,9 +6,10 @@ from __future__ import annotations from evalrx.core.case import CaseBatch, FailureCase, Inputs -from evalrx.eval_agent.agentic.board import EvidenceBoard -from evalrx.eval_agent.agentic.tools import build_default_registry -from evalrx.eval_agent.policy import RunState +from evalrx.eval_agent.loop.judge.board import EvidenceBoard +from evalrx.eval_agent.loop.judge.tools import build_default_registry +from evalrx.eval_agent.loop.state import RunState +from tests.conftest import FakeModel class _ScriptedJudge: @@ -29,7 +30,7 @@ def generate(self, prompt: str, **kwargs) -> str: return '{"label": "PASS", "reason": "match"}' -class _AlwaysWrongModel: +class _AlwaysWrongModel(FakeModel): def generate(self, inputs, **kwargs) -> str: return "WRONG" @@ -52,14 +53,16 @@ def _seed_pool() -> CaseBatch: def test_search_probes_registered_in_default_registry(): loop = _FakeLoop(_AlwaysWrongModel()) - state = RunState(original_data=_seed_pool(), data=_seed_pool(), judge=_ScriptedJudge()) + state = RunState(original_data=_seed_pool(), data=_seed_pool(), stages=None, + judge=_ScriptedJudge()) registry = build_default_registry(loop, state) assert "search_probes" in registry.tool_names() def test_search_probes_runs_and_populates_board_and_state(): loop = _FakeLoop(_AlwaysWrongModel()) - state = RunState(original_data=_seed_pool(), data=_seed_pool(), judge=_ScriptedJudge()) + state = RunState(original_data=_seed_pool(), data=_seed_pool(), stages=None, + judge=_ScriptedJudge()) registry = build_default_registry(loop, state) board = EvidenceBoard() @@ -75,7 +78,8 @@ def test_search_probes_runs_and_populates_board_and_state(): def test_search_probes_empty_seed_pool_returns_failure_without_crashing(): loop = _FakeLoop(_AlwaysWrongModel()) - state = RunState(original_data=CaseBatch([]), data=CaseBatch([]), judge=_ScriptedJudge()) + state = RunState(original_data=CaseBatch([]), data=CaseBatch([]), stages=None, + judge=_ScriptedJudge()) registry = build_default_registry(loop, state) board = EvidenceBoard() @@ -85,10 +89,11 @@ def test_search_probes_empty_seed_pool_returns_failure_without_crashing(): def test_search_probes_respects_call_cap_via_registry_dispatch(): - from evalrx.eval_agent.agentic.actions import Action + from evalrx.eval_agent.loop.judge.actions import Action loop = _FakeLoop(_AlwaysWrongModel()) - state = RunState(original_data=_seed_pool(), data=_seed_pool(), judge=_ScriptedJudge()) + state = RunState(original_data=_seed_pool(), data=_seed_pool(), stages=None, + judge=_ScriptedJudge()) registry = build_default_registry(loop, state) board = EvidenceBoard() action = Action(tool="search_probes", params={"budget": 1}, rationale="t") diff --git a/tests/test_eval_agent/test_agentic_tools.py b/tests/test_eval_agent/test_agentic_tools.py index 1f1bb289..3f617b25 100644 --- a/tests/test_eval_agent/test_agentic_tools.py +++ b/tests/test_eval_agent/test_agentic_tools.py @@ -7,9 +7,9 @@ from __future__ import annotations from evalrx.core.result import Result -from evalrx.eval_agent.agentic.actions import Action -from evalrx.eval_agent.agentic.board import EvidenceBoard -from evalrx.eval_agent.agentic.tools import ( +from evalrx.eval_agent.loop.judge.actions import Action +from evalrx.eval_agent.loop.judge.board import EvidenceBoard +from evalrx.eval_agent.loop.judge.tools import ( ToolOutcome, ToolRegistry, ToolSpec, diff --git a/tests/test_eval_agent/test_auto_diagnose.py b/tests/test_eval_agent/test_auto_diagnose.py index ebecccee..6df8c3d3 100755 --- a/tests/test_eval_agent/test_auto_diagnose.py +++ b/tests/test_eval_agent/test_auto_diagnose.py @@ -468,7 +468,7 @@ def test_m5_experiment_gets_its_own_trial_with_kept_sandbox(tmp_path): so a *successful* experiment left no runnable code behind at all.""" import json - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext ctx = RunContext(tmp_path / "run1") agent = SurgeryAgent(judge=FakeModel(), run_context=ctx) diff --git a/tests/test_eval_agent/test_case_discovery.py b/tests/test_eval_agent/test_case_discovery.py index 8cc79f02..52061fbd 100644 --- a/tests/test_eval_agent/test_case_discovery.py +++ b/tests/test_eval_agent/test_case_discovery.py @@ -1,14 +1,14 @@ -# ── discovery may fan out, but only where fanning out is safe ──────────────── +# ── discovery hands the model one batch; the backend decides how many at once ─ -def test_discovery_fans_out_only_for_an_api_handle(): +def test_discovery_keeps_runtime_concurrency_requests_in_flight_on_an_api_handle(): """A served model can only batch the requests it has been handed. Discovery issued one generate at a time, so a local `vllm serve` sat at "Running: 1 reqs" for the whole baseline — the backend was swapped for - throughput and then fed serially. A local backend must still be forced to - 1: it shares one GPU and is not thread-safe. + throughput and then fed serially. The API backend now sends + ``runtime.concurrency`` requests at once, and never more. """ import threading @@ -37,15 +37,9 @@ def _generate(prompt, model="", **kw): FailureCase(id=f"c{i}", inputs=Inputs(prompt=f"q{i}"), expected="answer to q%d" % i) for i in range(4) ] - served = compose("qwen3.5-2b", "api", RuntimeConfig(generate_fn=_generate), set()) - from evalrx.eval_agent.model_instrumentation import InstrumentedModel - - wrapped = InstrumentedModel( - served, object(), cycle=-1, analyzer="case_discovery", - ) - assert CaseDiscoveryAgent(concurrency=4)._workers(wrapped, len(cases)) == 4 + served = compose("qwen3.5-2b", "api", RuntimeConfig(generate_fn=_generate, concurrency=4), set()) report = CaseDiscoveryAgent( - scorer=lambda case, observed: observed == case.expected, concurrency=4, + scorer=lambda case, observed: observed == case.expected, ).discover(served, cases) assert peak["n"] == 4, f"expected 4 concurrent generates, saw {peak['n']}" @@ -54,15 +48,24 @@ def _generate(prompt, model="", **kw): assert report.n_pass == 4 and report.n_fail == 0 -def test_a_local_backend_is_forced_back_to_one(): +def test_a_model_without_its_own_batch_call_is_asked_one_case_at_a_time(): + import threading + + from evalrx.core.case import FailureCase, Inputs from evalrx.eval_agent.stages.case_discovery import CaseDiscoveryAgent + from tests.conftest import FakeModel - class _Local: + threads: set[int] = set() + + class _Local(FakeModel): def generate(self, inputs, **kw): + threads.add(threading.get_ident()) return "x" - agent = CaseDiscoveryAgent(concurrency=8) - assert agent._workers(_Local(), 20) == 1 + cases = [FailureCase(id=f"c{i}", inputs=Inputs(prompt=f"q{i}"), expected="x") for i in range(5)] + report = CaseDiscoveryAgent(scorer=lambda case, observed: observed == case.expected).discover( + _Local(), cases) + assert report.n_pass == 5 and threads == {threading.get_ident()} def test_a_case_whose_generation_raises_still_lands_as_unknown(): @@ -78,13 +81,103 @@ def _generate(prompt, model="", **kw): return "ok" cases = [FailureCase(id=f"c{i}", inputs=Inputs(prompt=f"q{i}"), expected="ok") for i in range(3)] - served = compose("qwen3.5-2b", "api", RuntimeConfig(generate_fn=_generate), set()) + served = compose("qwen3.5-2b", "api", RuntimeConfig(generate_fn=_generate, concurrency=3), set()) report = CaseDiscoveryAgent( - scorer=lambda case, observed: observed == case.expected, - concurrency=3, include_unknown=True, + scorer=lambda case, observed: observed == case.expected, include_unknown=True, ).discover(served, cases) labels = {c.id: c.label for c in report.cases} assert labels["c0"] is Label.PASS and labels["c2"] is Label.PASS assert labels["c1"] is Label.UNKNOWN assert any("endpoint refused" in e for e in report.errors) + + +# ── a sampling model: the label is the majority of several answers ─────────── + +def _scripted(answers_by_prompt: "dict[str, list[str]]"): + """A model that gives each prompt its scripted answers in turn, and the batches it saw.""" + from tests.conftest import FakeModel + + class _Scripted(FakeModel): + def __init__(self) -> None: + super().__init__() + self.batches: list[list[str]] = [] + self._left = {prompt: list(answers) for prompt, answers in answers_by_prompt.items()} + + def generate(self, inputs, **kw): + answer = self._left[inputs.prompt].pop(0) + if answer == "RAISE": + raise RuntimeError("endpoint refused") + return answer + + def try_generate_batch(self, inputs, **kw): + self.batches.append([item.prompt for item in inputs]) + answers: list = [] + for item in inputs: + try: + answers.append(self.generate(item, **kw)) + except RuntimeError as exc: + answers.append(exc) + return answers + + return _Scripted() + + +def _discover(model, prompts, n_samples, **kwargs): + from evalrx.core.case import FailureCase, Inputs + from evalrx.eval_agent.stages.case_discovery import CaseDiscoveryAgent + + cases = [FailureCase(id=f"c{i}", inputs=Inputs(prompt=p), expected="yes") for i, p in enumerate(prompts)] + return CaseDiscoveryAgent( + scorer=lambda case, observed: observed.startswith(case.expected), + n_samples=n_samples, **kwargs, + ).discover(model, cases) + + +def test_a_case_is_labelled_by_the_majority_of_its_sampled_answers(): + from evalrx.core.case import Label + + model = _scripted({"q0": ["no", "yes 1", "yes 2"], "q1": ["yes", "no 1", "no 2"]}) + + report = _discover(model, ["q0", "q1"], n_samples=3) + + # Every sample of every case in one batch, a case's samples side by side. + assert model.batches == [["q0", "q0", "q0", "q1", "q1", "q1"]] + c0, c1 = report.cases + assert (c0.label, c1.label) == (Label.PASS, Label.FAIL) + assert (report.n_pass, report.n_fail, report.n_unknown) == (1, 1, 0) + # The recorded answer is the first one that earned the label, not the first drawn. + assert (c0.observed, c1.observed) == ("yes 1", "no 1") + assert c0.metadata["discovery_votes"] == {"pass": 2, "fail": 1} + assert c1.metadata["discovery_votes"] == {"pass": 1, "fail": 2} + assert c0.metadata["discovery_reason"].startswith("2 of 3 sampled answers passed") + + +def test_one_answer_per_case_records_no_votes(): + report = _discover(_scripted({"q0": ["yes"]}), ["q0"], n_samples=1) + + assert "discovery_votes" not in report.cases[0].metadata + assert report.cases[0].metadata["discovery_reason"] == "scored by injected scorer" + + +def test_a_failed_sample_does_not_vote_and_an_even_split_is_unknown(): + from evalrx.core.case import Label + + model = _scripted({"q0": ["RAISE", "yes", "yes"], "q1": ["RAISE", "yes", "no"]}) + + report = _discover(model, ["q0", "q1"], n_samples=3, include_unknown=True) + + c0, c1 = report.cases + assert c0.label is Label.PASS and c0.observed == "yes" + assert "discovery_error" not in c0.metadata # the case has a label; the error is in the report + assert c1.label is Label.UNKNOWN and "endpoint refused" in c1.metadata["discovery_error"] + assert sum("endpoint refused" in e for e in report.errors) == 2 + + +def test_fewer_than_one_sample_is_refused(): + import pytest + + from evalrx.eval_agent.stages.case_discovery import CaseDiscoveryAgent + + with pytest.raises(ValueError, match="n_samples"): + CaseDiscoveryAgent(n_samples=0) diff --git a/tests/test_eval_agent/test_confirm_split.py b/tests/test_eval_agent/test_confirm_split.py index fd4a0f3c..8ec4be90 100644 --- a/tests/test_eval_agent/test_confirm_split.py +++ b/tests/test_eval_agent/test_confirm_split.py @@ -15,8 +15,8 @@ from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.core.model import Model from evalrx.eval_agent.hypothesis import Hypothesis -from evalrx.eval_agent.loop import VLDiagnoseLoop -from evalrx.eval_agent.loop_reports import AutoDiagnoseReport +from evalrx.eval_agent.loop.diagnose import VLDiagnoseLoop +from evalrx.eval_agent.loop.report import AutoDiagnoseReport from evalrx.eval_agent.stages.fix.agent import FixCandidate, FixOutcome, FixValidation from evalrx.eval_agent.stages.fix.tiers import FixTier from evalrx.eval_agent.stages.protocol import ExperimentProtocol @@ -377,7 +377,7 @@ def operate(self, hypothesis, model, results, data): def test_confirm_with_no_explore_lead_routes_the_next_supported_tier(): """With nothing to freeze, the recommendation comes from the agent's own tier router (unsupported L3a/L3b skipped), not a flat "stay at the ceiling".""" - from evalrx.eval_agent.loop_fix import _confirm_from_explore + from evalrx.eval_agent.loop.fix import _confirm_from_explore from evalrx.eval_agent.stages.fix.agent import FixAgent confirm = CaseBatch([ @@ -395,7 +395,7 @@ def test_confirm_with_no_explore_lead_routes_the_next_supported_tier(): def test_confirm_routes_from_the_given_ceiling_not_the_agents(): """The loop passes the run's ceiling explicitly: an agent configured at L1 confirming under an L2 ceiling recommends past L2, not past L1.""" - from evalrx.eval_agent.loop_fix import _confirm_from_explore + from evalrx.eval_agent.loop.fix import _confirm_from_explore from evalrx.eval_agent.stages.fix.agent import FixAgent confirm = CaseBatch([ @@ -427,7 +427,7 @@ def test_run_fix_never_writes_to_the_fix_agent(): def test_confirm_freezes_the_supported_explore_lead_and_says_why_it_did_not_hold(): """The lead with support is the one frozen, and when it fails on CONFIRM the agent's recommendation is prefixed with that fact.""" - from evalrx.eval_agent.loop_fix import _confirm_from_explore + from evalrx.eval_agent.loop.fix import _confirm_from_explore from evalrx.eval_agent.stages.fix.types import FixCandidate, FixValidation def lead(name, n_pairs, n_fixed, n_broken): diff --git a/tests/test_eval_agent/test_diagnosis_handoff.py b/tests/test_eval_agent/test_diagnosis_handoff.py index cbd9794c..4b12e7f6 100755 --- a/tests/test_eval_agent/test_diagnosis_handoff.py +++ b/tests/test_eval_agent/test_diagnosis_handoff.py @@ -229,7 +229,7 @@ def generate(self, inputs, **kw) -> str: def test_loop_hands_the_case_batch_to_agents_that_accept_it_only(): - from evalrx.eval_agent.loop import _diagnose_with_optional_context + from evalrx.eval_agent.loop.stages import _diagnose_with_optional_context class Modern: def diagnose(self, stats_report, prior_cycles=None, explore_context=None, diff --git a/tests/test_eval_agent/test_explore_context.py b/tests/test_eval_agent/test_explore_context.py index 6994941d..b486af5f 100644 --- a/tests/test_eval_agent/test_explore_context.py +++ b/tests/test_eval_agent/test_explore_context.py @@ -159,7 +159,7 @@ def test_only_m3_diagnose_accepts_explore_context(): # --------------------------------------------------------------------------- def test_coerce_explore_context_accepts_dict_ctx_and_none(): - from evalrx.eval_agent.run_metadata import _coerce_explore_context + from evalrx.eval_agent.loop.metadata import _coerce_explore_context ctx = _coerce_explore_context({"observations": ["a"]}) assert isinstance(ctx, ExploreContext) @@ -171,7 +171,7 @@ def test_coerce_explore_context_accepts_dict_ctx_and_none(): def test_dispatch_passes_context_only_to_agents_that_accept_it(): - from evalrx.eval_agent.loop import _diagnose_with_optional_context + from evalrx.eval_agent.loop.stages import _diagnose_with_optional_context ctx = ExploreContext(observations=["x"]) @@ -195,14 +195,16 @@ def diagnose(self, report, prior_cycles=None): def test_loop_init_stores_coerced_explore_context(): - from evalrx.eval_agent.loop import VLDiagnoseLoop + from evalrx.eval_agent.loop.diagnose import VLDiagnoseLoop + from tests.conftest import FakeModel - loop = VLDiagnoseLoop.__new__(VLDiagnoseLoop) # avoid heavy __init__ deps - # exercise the coercion path used by __init__ - from evalrx.eval_agent.run_metadata import _coerce_explore_context - loop._explore_context = _coerce_explore_context({"charts": [{"title": "C", "figure_path": "/p.png"}]}) - assert isinstance(loop._explore_context, ExploreContext) - assert loop._explore_context.figure_paths == ["/p.png"] + loop = VLDiagnoseLoop( + model=FakeModel(), protocol=None, + explore_report={"charts": [{"title": "C", "figure_path": "/p.png"}]}, + ) + context = loop.stages().memory.explore_context + assert isinstance(context, ExploreContext) + assert context.figure_paths == ["/p.png"] # --------------------------------------------------------------------------- @@ -212,7 +214,7 @@ def test_loop_init_stores_coerced_explore_context(): def test_log_diagnosis_records_explore_provenance(tmp_path): import json - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.eval_agent.stages.diagnosis import DiagnosisResult logger = RunLogger(run_dir=tmp_path / "run1", observability_mode="offline") @@ -238,7 +240,7 @@ def test_log_diagnosis_persists_the_critic_prompt_beside_its_response(tmp_path): import json from evalrx.eval_agent.hypothesis import Hypothesis - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.eval_agent.stages.diagnosis import DiagnosisResult logger = RunLogger(run_dir=tmp_path / "run2", observability_mode="offline") diff --git a/tests/test_eval_agent/test_fix_agent.py b/tests/test_eval_agent/test_fix_agent.py index 8db7bfb9..937e729b 100644 --- a/tests/test_eval_agent/test_fix_agent.py +++ b/tests/test_eval_agent/test_fix_agent.py @@ -31,6 +31,7 @@ from evalrx.eval_agent.stages.fix.repair_catalog import discover_methods from evalrx.eval_agent.stages.fix.validation import Baseline from evalrx.eval_agent.stages.fix.verdict import recommend +from tests.conftest import FakeModel # ── tiers ───────────────────────────────────────────────────────────────────── @@ -213,11 +214,11 @@ def test_crop_case_bbox_no_bbox_is_noop_even_with_enhancement(): assert np.asarray(out).mean() == np.asarray(img).mean() -def test_run_pipeline_can_fix_textvqa_style_bbox_case(): +def test_run_pipelines_can_fix_textvqa_style_bbox_case(): PIL = pytest.importorskip("PIL") import numpy as np - from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipeline + from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipelines img = PIL.Image.new("RGB", (100, 100), color=(220, 220, 220)) for y in range(10, 14): @@ -230,7 +231,7 @@ def test_run_pipeline_can_fix_textvqa_style_bbox_case(): metadata={"answer_bbox_xyxy_norm": [0.8, 0.1, 0.84, 0.14]}, ) - class BBoxSensitiveModel: + class BBoxSensitiveModel(FakeModel): def generate(self, inputs, **kwargs): arr = np.asarray(inputs.image) dark = (arr[:, :, 0] < 80) & (arr[:, :, 1] < 80) & (arr[:, :, 2] < 80) @@ -241,7 +242,7 @@ def generate(self, inputs, **kwargs): image_ops=[{"tool": "crop_case_bbox", "params": {"padding": 0.0, "min_size_frac": 0.08}}], ) - assert run_pipeline(BBoxSensitiveModel(), case, spec, _label_score) is True + assert _label_score(case, run_pipelines(BBoxSensitiveModel(), [case], spec)[0].winner) is Label.PASS def test_separate_horizontal_bands_adds_visible_gaps(): @@ -326,11 +327,11 @@ def test_pipeline_spec_validation(): def test_pipeline_passes_bounded_generation_kwargs(): - from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipeline + from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipelines case = FailureCase(id="decode", inputs=Inputs(prompt="q"), expected="yes") - class DecodeBudgetModel: + class DecodeBudgetModel(FakeModel): def generate(self, inputs, **kwargs): return "yes" if kwargs.get("max_tokens") == 512 else "no" @@ -342,7 +343,7 @@ def generate(self, inputs, **kwargs): ) assert spec is not None assert spec.generation_kwargs == {"max_tokens": 512} - assert run_pipeline(DecodeBudgetModel(), case, spec, _label_score) is True + assert _label_score(case, run_pipelines(DecodeBudgetModel(), [case], spec)[0].winner) is Label.PASS def test_pipeline_normalizes_zero_temperature_and_empty_stop(): @@ -363,11 +364,11 @@ def test_pipeline_normalizes_zero_temperature_and_empty_stop(): def test_pipeline_self_refine_is_a_label_blind_reviewed_multicall_strategy(): - from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipeline + from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipelines case = FailureCase(id="review", inputs=Inputs(prompt="What is 2 + 2?"), expected="yes") - class SequencedModel: + class SequencedModel(FakeModel): def __init__(self): self.prompts: list[str] = [] @@ -377,37 +378,37 @@ def generate(self, inputs, **kwargs): model = SequencedModel() spec = PipelineSpec(name="review", strategy="self_refine") - assert run_pipeline(model, case, spec, _label_score) is True + assert _label_score(case, run_pipelines(model, [case], spec)[0].winner) is Label.PASS assert len(model.prompts) == 3 assert "yes" not in "\n".join(model.prompts).lower() # expected label never enters prompts def test_pipeline_preserves_non_image_modality_fields(): - """run_pipeline's inner generate() used to rebuild a bare Inputs(prompt=..., + """run_pipelines used to rebuild a bare Inputs(prompt=..., image=...), silently dropping .video/.audio -- every strategy was unconditionally inapplicable on any non-image FailureCase (generate() - raising on the missing modality, every call returning "", run_pipeline + raising on the missing modality, every call returning "", the run returning None -> "no applicable scorable pair" for every case, the exact failure musicavqa_videollama2's real run hit).""" - from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipeline + from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipelines case = FailureCase( id="clip", inputs=Inputs(prompt="What instrument is heard?", video="clip.mp4"), expected="cello", ) - class VideoRequiredModel: + class VideoRequiredModel(FakeModel): def generate(self, inputs, **kwargs): if getattr(inputs, "video", None) is None: raise ValueError("requires Inputs.video") return "cello" spec = PipelineSpec(name="direct", strategy="direct") - assert run_pipeline(VideoRequiredModel(), case, spec, _label_score) is True + assert _label_score(case, run_pipelines(VideoRequiredModel(), [case], spec)[0].winner) is Label.PASS def test_pipeline_votes_on_task_declared_output_key_not_hidden_score(): - from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipeline + from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipelines case = FailureCase( id="structured", @@ -416,7 +417,7 @@ def test_pipeline_votes_on_task_declared_output_key_not_hidden_score(): metadata={"output_key_pattern": r"FINAL:\s*(\d+)"}, ) - class Samples: + class Samples(FakeModel): def __init__(self): self.outputs = iter(["work FINAL: 4", "another FINAL: 4", "FINAL: 9"]) @@ -427,7 +428,7 @@ def four_is_correct(case, output): return "FINAL: 4" in output spec = PipelineSpec(name="vote", n_samples=3) - assert run_pipeline(Samples(), case, spec, four_is_correct) is True + assert four_is_correct(case, run_pipelines(Samples(), [case], spec)[0].winner) is True # ── fake models ─────────────────────────────────────────────────────────────── @@ -984,7 +985,7 @@ def test_chart_count_extract_gate_is_gold_free_and_excludes_color_questions(): def test_l1_template_candidate_preserves_non_image_modality_fields(): """The L1 template runner used to rebuild a bare Inputs(prompt=..., image=...), silently dropping .video/.audio -- identical bug to - run_pipeline's, in the sibling L1 (not L2) code path.""" + run_pipelines', in the sibling L1 (not L2) code path.""" case = FailureCase( id="clip", inputs=Inputs(prompt="What instrument is heard?", video="clip.mp4"), expected="cello", label=Label.FAIL, @@ -1027,7 +1028,8 @@ def test_image_l1_candidates_start_with_visual_grounding_control(): assert candidates[0].name == "visual_grounding" assert "visible evidence" in candidates[0].payload["prompt_template"] - assert FixAgent().validator.strategy(candidates[0])(BaselineFailsModel(), batch[0]) is True + scores = FixAgent().validator.scores(candidates[0], BaselineFailsModel(), batch) + assert scores[batch[0].id] is True def test_video_only_batch_is_treated_as_having_visual_content(): @@ -3022,7 +3024,7 @@ def test_signature_distinguishes_candidates_sharing_kind_and_payload(): def test_self_refine_offered_for_image_reasoning_tasks_not_yes_no(): """self_refine/self_consistency_5/least_to_most were only ever proposed - for text-only cases, even though run_pipeline already threads the case + for text-only cases, even though run_pipelines already threads the case image through every call -- nothing about them is text-specific. A multi-step reasoning task (multiple_choice/exact_or_numeric/ vqa_consensus) with an image should get self_refine and @@ -3251,7 +3253,7 @@ def test_declarative_candidate_gets_record_and_result_but_no_workspace(tmp_path) never gets a workspace/ subdir. There is no per-trial record.md/result.json either; the outcome data lives inline in M5/log.json's "fix" entry.""" - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext ctx = RunContext(tmp_path / "run1") judge = ScriptedJudge( @@ -3290,7 +3292,7 @@ def test_deduped_candidate_in_round_two_leaves_no_trial_folder(tmp_path): record.md/result.json), so the dedup guarantee is checked against the returned attempt list and the inlined M5/log.json record instead of a directory listing.""" - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext ctx = RunContext(tmp_path / "run1") judge = ScriptedJudge( @@ -3375,7 +3377,7 @@ def forward(self, inputs, capture, spec=None): def test_two_coded_fix_attempts_get_separate_trial_workspaces(tmp_path): pytest.importorskip("PIL") - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext ctx = RunContext(tmp_path / "run1") agent = FixAgent( @@ -3461,17 +3463,16 @@ def test_a_template_case_that_cannot_render_scores_none_not_a_crash(): from evalrx.core.case import FailureCase, Inputs, Label from evalrx.eval_agent.stages.fix.agent import FixAgent, FixCandidate - class _Boom: + class _Boom(FakeModel): def generate(self, *a, **k): raise RuntimeError("model down") agent = FixAgent() candidate = FixCandidate(tier=None, name="t", kind="template", payload={"prompt_template": r"{prompt} ${~m}$"}) - strategy = agent.validator.strategy(candidate) case = FailureCase(inputs=Inputs(prompt="q"), observed="o", expected="e", label=Label.FAIL) - assert strategy(_Boom(), case) is None + assert agent.validator.scores(candidate, _Boom(), CaseBatch([case])) == {case.id: None} # ── repair the model, not the task: the frozen-model control ───────────────── @@ -3905,7 +3906,7 @@ def test_coded_attempt_persists_guard_and_control_audit_files(tmp_path): record or reverted anything). Checked before finalize(): these live under RunContext's ephemeral runtime tree, which finalize() inlines and deletes, not under the run root itself.""" - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext ctx = RunContext(tmp_path / "run") agent = FixAgent( diff --git a/tests/test_eval_agent/test_fix_batching.py b/tests/test_eval_agent/test_fix_batching.py new file mode 100644 index 00000000..76b4cd6e --- /dev/null +++ b/tests/test_eval_agent/test_fix_batching.py @@ -0,0 +1,253 @@ +"""The fix stage asks the model in batches and owns no thread pool. + +What runs at once is the model's business (``Model.generate_batch``): the +baseline samples, a template or spec candidate, and the calls a coded pipeline +makes at the same moment each reach the model as one batch. +""" + +from __future__ import annotations + +import threading + +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.stages.fix.agent import FixAgent, FixCandidate +from evalrx.eval_agent.stages.fix.pipeline import run_coded_pipeline +from evalrx.eval_agent.stages.fix.tiers import FixTier +from evalrx.eval_agent.stages.fix.tools import PipelineSpec, SpecPipelineModel, run_pipelines + + +class Batched(Model): + """Answers " -> yes" and records every batch it was given.""" + + capabilities = frozenset({Capability.GENERATE}) + modalities = frozenset({"text"}) + + def __init__(self, fail_on: str = "") -> None: + self.batches: list[list[str]] = [] + self.threads: set[int] = set() + self.fail_on = fail_on + + def generate(self, inputs, **kwargs): + prompt = str(getattr(inputs, "prompt", inputs)) + if self.fail_on and self.fail_on in prompt: + raise RuntimeError("adapter hiccup") + return f"{prompt} -> yes" + + def generate_batch(self, inputs, **kwargs): + self.threads.add(threading.get_ident()) + self.batches.append([str(getattr(item, "prompt", item)) for item in inputs]) + return [self.generate(item, **kwargs) for item in inputs] + + def forward(self, inputs, capture, spec=None): + raise NotImplementedError + + +class Exchanges: + """A run logger that keeps the fix stage's model exchanges and outcomes.""" + + def __init__(self) -> None: + self.calls: list[dict] = [] + self.outcomes: list = [] + + def log_model_exchange(self, stage, **fields): + self.calls.append(fields) + + def log_fix(self, outcome): + self.outcomes.append(outcome) + + +def _cases(n: int = 4, observed: "str | None" = "no") -> CaseBatch: + return CaseBatch([ + FailureCase(id=f"c{i}", inputs=Inputs(prompt=f"Q{i}"), observed=observed, + label=Label.FAIL, expected="yes") + for i in range(n) + ]) + + +def _says_yes(case, output): + return "yes" in output + + +def _agent(**kwargs) -> FixAgent: + return FixAgent(judge=None, max_tier="L2", score_fn=_says_yes, floor_candidates=(), **kwargs) + + +def test_a_template_candidate_is_one_batch_and_one_exchange_per_case(): + log = Exchanges() + agent = _agent(run_logger=log) + model = Batched() + cand = FixCandidate(tier=FixTier.L1_PROMPT, name="t", kind="template", + payload={"prompt_template": "Think. {prompt}"}) + + scores = agent.validator.scores(cand, model, _cases()) + + assert model.batches == [["Think. Q0", "Think. Q1", "Think. Q2", "Think. Q3"]] + assert scores == {f"c{i}": True for i in range(4)} + assert [call["metadata"]["case_id"] for call in log.calls] == ["c0", "c1", "c2", "c3"] + assert all(call["operation"] == "template_candidate" for call in log.calls) + + +def test_a_candidate_that_leaves_a_case_untouched_is_not_run_on_it(): + model = Batched() + cand = FixCandidate(tier=FixTier.L1_PROMPT, name="identity", kind="template", + payload={"prompt_template": "{prompt}"}) + + scores = _agent().validator.scores(cand, model, _cases()) + + assert model.batches == [] and set(scores.values()) == {None} + + +def test_one_failed_case_scores_none_and_the_rest_keep_their_answers(): + model = Batched(fail_on="Q2") + for kind, payload in (("template", {"prompt_template": "x {prompt}"}), + ("spec", {"name": "s", "prompt_template": "x {prompt}"})): + cand = FixCandidate(tier=FixTier.L2_SCAFFOLD, name="t", kind=kind, payload=payload) + scores = _agent().validator.scores(cand, model, _cases()) + assert scores == {"c0": True, "c1": True, "c2": None, "c3": True}, kind + + +def test_a_multi_step_spec_advances_every_case_and_sample_together(): + model = Batched() + spec = PipelineSpec(name="refine", strategy="self_refine", n_samples=3) + cases = list(_cases(4)) + + runs = run_pipelines(model, cases, spec) + + # Three rounds (draft, feedback, final); each holds every case x sample. + assert [len(batch) for batch in model.batches] == [12, 12, 12] + assert model.batches[0].count("Q0") == 3 # identical prompts stay separate rows + assert all(len(run.calls) == 9 and len(run.outputs) == 3 for run in runs) + assert all("Attempt:" in prompt for prompt in model.batches[1]) + assert all(f"Q{i}" in run.winner for i, run in enumerate(runs)) + + +def test_a_deployed_spec_answers_a_batch_through_the_same_path(): + model = Batched() + deployed = SpecPipelineModel(model, PipelineSpec(name="s", prompt_template="x {prompt}", + n_samples=2)) + + answers = deployed.generate_batch([Inputs(prompt="A"), Inputs(prompt="B")]) + + assert model.batches == [["x A", "x A", "x B", "x B"]] + assert answers == ["x A -> yes", "x B -> yes"] + assert deployed.generate(Inputs(prompt="C")) == "x C -> yes" + + +def test_the_fresh_baseline_samples_are_one_batch(): + log = Exchanges() + agent = _agent(run_logger=log, baseline_repeats=3) + model = Batched() + + baseline = agent.validator.baseline(model, _cases(2)) + + # Three fresh samples per case, all at once. The recorded "no" labelled the + # case and is not counted among them. + assert model.batches == [["Q0", "Q0", "Q0", "Q1", "Q1", "Q1"]] + assert baseline.counts == {"c0": 3, "c1": 3} + assert baseline.rates == {"c0": 1.0, "c1": 1.0} + assert [call["operation"] for call in log.calls] == ["fresh_baseline"] * 6 + + +def test_an_unrepeated_baseline_is_the_recorded_answer(): + model = Batched() + + baseline = _agent(baseline_repeats=1).validator.baseline(model, _cases(2)) + + assert model.batches == [] + assert baseline.rates == {"c0": 0.0, "c1": 0.0} + + +_ONE_THREAD_PER_CASE = """ +import json +from concurrent.futures import ThreadPoolExecutor +cases = json.load(open("fix_cases.json"))["cases"] +def solve(c): + first = model_generate(c["id"], prompt="A " + c["prompt"]) + second = model_generate(c["id"], prompt="B " + first) + return {"sample_id": c["id"], "output": second} +with ThreadPoolExecutor(max_workers=len(cases)) as pool: + rows = list(pool.map(solve, cases)) +print("FIX_PIPELINE_RESULT_JSON=" + json.dumps({"per_case": rows})) +""" + + +def test_the_bridge_answers_simultaneous_calls_as_one_batch_from_one_thread(tmp_path): + model = Batched() + cases = _cases(8) + logged: list[dict] = [] + + result = run_coded_pipeline(_ONE_THREAD_PER_CASE, model, cases, workdir=tmp_path, + timeout_sec=60, call_logger=logged.append) + + assert result.ok, result.error + assert result.outputs == {f"c{i}": f"B A Q{i} -> yes -> yes" for i in range(8)} + assert sum(len(batch) for batch in model.batches) == 16 == result.n_calls == len(logged) + # Two rounds of eight; a slow machine may split a round, never one call each. + assert len(model.batches) <= 6 and max(len(batch) for batch in model.batches) > 1 + assert len(model.threads) == 1 and threading.get_ident() not in model.threads + + +def test_the_bridge_batches_by_decoding_setting_and_replays_the_recorded_answer(tmp_path): + code = """ +import json +from concurrent.futures import ThreadPoolExecutor +cases = json.load(open("fix_cases.json"))["cases"] +def solve(c): + kw = {"temperature": 0.7} if c["id"] in ("c0", "c1") else None + return {"sample_id": c["id"], + "output": model_generate(c["id"]) + "|" + model_generate( + c["id"], prompt="P " + c["prompt"], generation_kwargs=kw)} +with ThreadPoolExecutor(max_workers=len(cases)) as pool: + rows = list(pool.map(solve, cases)) +print("FIX_PIPELINE_RESULT_JSON=" + json.dumps({"per_case": rows})) +""" + model = Batched() + + result = run_coded_pipeline(code, model, _cases(4), workdir=tmp_path, timeout_sec=60) + + assert result.ok, result.error + assert result.outputs == {f"c{i}": f"no|P Q{i} -> yes" for i in range(4)} + assert result.n_replayed == 4 # the plain calls never reached the model + asked = sorted(prompt for batch in model.batches for prompt in batch) + assert asked == ["P Q0", "P Q1", "P Q2", "P Q3"] + # Sampled and default decoding never share a batch. + assert not any({"P Q0", "P Q1"} & set(batch) and {"P Q2", "P Q3"} & set(batch) + for batch in model.batches) + + +def test_the_baseline_is_measured_once_for_a_model_and_its_cases(): + agent = _agent(baseline_repeats=3) + model, cases = Batched(), _cases(2) + + first = agent.validator.baseline(model, cases) + again = agent.validator.baseline(model, cases) # the next tier of the same search + other = agent.validator.baseline(model, _cases(3)) # another partition + + assert again is first and other is not first + assert [len(batch) for batch in model.batches] == [6, 9] + + # A deployed template rewrites the prompts under the same case ids. + rewritten = _cases(2) + for case in rewritten: + case.inputs.prompt = "Think. " + case.inputs.prompt + assert agent.validator.baseline(model, rewritten) is not first + assert model.batches[-1] == ["Think. Q0"] * 3 + ["Think. Q1"] * 3 + + +def test_a_search_that_records_no_outcome_still_logs_what_the_model_was_asked(): + from evalrx.eval_agent.hypothesis import Hypothesis + + log = Exchanges() + agent = _agent(run_logger=log) + hypothesis = Hypothesis(statement="it guesses", target_model="m", predicted_failure_mode="x") + + outcome = agent.propose_and_validate(Batched(), _cases(), [hypothesis], max_tier="L1", + min_tier="L1", record=False) + + assert outcome.attempted and log.outcomes == [] + asked = [call for call in log.calls if call["role"] == "target_model"] + assert len(asked) == 4 * len(outcome.attempted) # one exchange per case per candidate + agent.propose_and_validate(Batched(), _cases(), [hypothesis], max_tier="L1", min_tier="L1") + assert len(log.outcomes) == 1 diff --git a/tests/test_eval_agent/test_fix_edit_candidates.py b/tests/test_eval_agent/test_fix_edit_candidates.py index a7eb7e8f..0cfed689 100644 --- a/tests/test_eval_agent/test_fix_edit_candidates.py +++ b/tests/test_eval_agent/test_fix_edit_candidates.py @@ -21,7 +21,7 @@ from evalrx.core.model import Model from evalrx.eval_agent import FixAgent from evalrx.eval_agent.hypothesis import Hypothesis -from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipeline +from evalrx.eval_agent.stages.fix.tools import PipelineSpec, run_pipelines _DEPLOYED = "{prompt}\n\nWork through this in three parts before answering." @@ -174,6 +174,6 @@ def forward(self, inputs, capture, spec=None): ) model = CaptureModel() spec = PipelineSpec(name="edit", prompt_template="Do it plainly. {original_prompt}") - result = run_pipeline(model, case, spec, score_fn=lambda c, o: "yes" in o) + result = "yes" in run_pipelines(model, [case], spec)[0].winner assert result is True assert model.prompts == ["Do it plainly. ORIGINAL TEXT"] diff --git a/tests/test_eval_agent/test_fix_validation_end.py b/tests/test_eval_agent/test_fix_validation_end.py index 455e5266..78aeed6d 100644 --- a/tests/test_eval_agent/test_fix_validation_end.py +++ b/tests/test_eval_agent/test_fix_validation_end.py @@ -38,7 +38,7 @@ MAX_TOKENS_CAP, PipelineSpec, answer_key, - run_pipeline, + run_pipelines, ) @@ -135,7 +135,7 @@ def forward(self, inputs, capture, spec=None): raise NotImplementedError -# ── run_pipeline: n_samples for every strategy + label-free vote key ────────── +# ── run_pipelines: n_samples for every strategy + label-free vote key ────────── def test_n_samples_applies_to_multi_call_strategies(): @@ -144,11 +144,11 @@ def test_n_samples_applies_to_multi_call_strategies(): model = CountingModel() case = list(_mc_batch(1, 0))[0] spec = PipelineSpec(name="l2m", strategy="least_to_most", n_samples=3) - capture: dict = {} - assert run_pipeline(model, case, spec, _mc_score, capture=capture) is True + (run,) = run_pipelines(model, [case], spec) + assert _mc_score(case, run.winner) is True assert len(model.calls) == 6 - assert capture["n_calls"] == 6 and len(capture["outputs"]) == 3 - assert capture["winner"].endswith("Answer: (B)") + assert len(run.calls) == 6 and len(run.outputs) == 3 + assert run.winner.endswith("Answer: (B)") def test_vote_uses_extracted_final_answer_not_whole_text(): @@ -166,9 +166,9 @@ def generate(self, inputs, **kwargs): case = list(_mc_batch(1, 0))[0] spec = PipelineSpec(name="sc", n_samples=3) - capture: dict = {} - assert run_pipeline(Sampler(), case, spec, _mc_score, capture=capture) is True - assert capture["winner"].endswith("Answer: (B)") + (run,) = run_pipelines(Sampler(), [case], spec) + assert _mc_score(case, run.winner) is True + assert run.winner.endswith("Answer: (B)") # the key itself is label-free and format-normalised assert answer_key("blah\nAnswer: (B)") == answer_key("other\nAnswer: B") assert answer_key("FINAL: 4 and more", r"FINAL:\s*(\d+)") == "4" @@ -193,13 +193,13 @@ def forward(self, inputs, capture, spec=None): spec = PipelineSpec( name="guarded", n_samples=3, baseline_override_min_support=2 ) - capture: dict = {} mixed = ["Answer: (B)", "Answer: (B)", "Answer: (C)"] - assert run_pipeline(Sampler(mixed), case, spec, _mc_score, capture=capture) is False - assert capture["winner"] == case.observed + (run,) = run_pipelines(Sampler(mixed), [case], spec) + assert _mc_score(case, run.winner) is False + assert run.winner == case.observed unanimous = ["Answer: (B)", "Answer: (B)", "Answer: (B)"] - assert run_pipeline(Sampler(unanimous), case, spec, _mc_score) is True + assert _mc_score(case, run_pipelines(Sampler(unanimous), [case], spec)[0].winner) is True roundtrip = PipelineSpec.from_dict(spec.to_dict()) assert roundtrip is not None and roundtrip.baseline_override_min_support == 2 @@ -273,7 +273,7 @@ def test_bridge_enforces_floor_and_passes_generation_kwargs(tmp_path): def test_candidate_outputs_and_truncation_are_recorded(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger class Truncating(CountingModel): def generate(self, inputs, **kwargs): @@ -502,15 +502,15 @@ def generate(self, inputs, **kwargs): return "Chain.\nAnswer: (B)" if ok else "Chain.\nAnswer: (C)" -def test_paired_rates_uses_frozen_sample_plus_fresh_and_weighs_unstable(): - """baseline_repeats=k: the frozen observed output is sample 1, k-1 are - generated; each case's baseline is a rate; unstable cases stay in.""" +def test_paired_rates_draws_fresh_samples_and_weighs_unstable(): + """baseline_repeats=k: k fresh samples per case, the frozen observed output + not among them; each case's baseline is a rate; unstable cases stay in.""" batch = _mc_batch(4, 4) # 4 FAIL (observed wrong) + 4 PASS (observed right) # fresh baseline samples: alternate right/wrong -> every case ends unstable model = _CoinModel([True, False]) agent = FixAgent(judge=None, max_tier="L1", baseline_repeats=3, floor_candidates=()) baseline = agent._baseline(model, batch) - assert len(model.calls) == 2 * len(batch) # k-1 fresh per case; frozen counted + assert len(model.calls) == 3 * len(batch) # the frozen output is not counted assert all(0.0 < agent._baseline_rates[c.id] < 1.0 for c in batch) assert len(baseline.unstable) == len(batch) cand = FixCandidate(tier=FixTier.L1_PROMPT, name="careful", kind="template", @@ -606,9 +606,9 @@ def test_spec_template_with_literal_braces_renders_and_never_aborts_the_stage(): prompt_template="{prompt}\nUse the set {1,2,3,4,5,6,7} and \\frac{a}{b}.") model = CountingModel() case = list(_mc_batch(1, 0))[0] - capture: dict = {} - assert run_pipeline(model, case, spec, _mc_score, capture=capture) is True - assert "{1,2,3,4,5,6,7}" in capture["prompt"] and "\\frac{a}{b}" in capture["prompt"] + (run,) = run_pipelines(model, [case], spec) + assert _mc_score(case, run.winner) is True + assert "{1,2,3,4,5,6,7}" in run.prompt and "\\frac{a}{b}" in run.prompt class Exploding(CountingModel): def generate(self, inputs, **kwargs): @@ -616,18 +616,15 @@ def generate(self, inputs, **kwargs): raise RuntimeError("adapter hiccup") return super().generate(inputs, **kwargs) - agent = FixAgent(judge=None, max_tier="L1", concurrency=3, floor_candidates=()) - - def raising_strategy(model, case): - if case.id == "q1": - raise KeyError("boom") - return True - - agent.validator.strategy = lambda candidate: raising_strategy # type: ignore[assignment] - cand = FixCandidate(tier=FixTier.L1_PROMPT, name="t", kind="template", - payload={"prompt_template": "x {prompt}"}) - scores = agent.validator.scores(cand, Exploding(), _mc_batch(2, 1)) - assert scores["q1"] is None and scores["q0"] is True and scores["q2"] is True + agent = FixAgent(judge=None, max_tier="L1", floor_candidates=()) + batch = _mc_batch(2, 1) + batch[1].inputs.prompt += " q1" + for payload in ({"prompt_template": "x {prompt}"}, + {"name": "s", "prompt_template": "x {prompt}", "n_samples": 2}): + kind = "spec" if "name" in payload else "template" + cand = FixCandidate(tier=FixTier.L1_PROMPT, name="t", kind=kind, payload=payload) + scores = agent.validator.scores(cand, Exploding(), batch) + assert scores == {batch[0].id: True, batch[1].id: None, batch[2].id: True}, kind # ── no verified hypothesis: M5 + fix on the best unverified lead (opt-in) ──── @@ -683,7 +680,7 @@ def test_run_fix_without_verified_skips_repair_authoring(): assert outcome.skip_reason == "no_accepted_hypothesis" -# ── coded-pipeline bridge: concurrent, request-id tagged ───────────────────── +# ── coded-pipeline bridge: request-id tagged, answered a batch at a time ───── class EchoPromptModel(Model): @@ -693,8 +690,9 @@ class EchoPromptModel(Model): capabilities = frozenset({Capability.GENERATE}) modalities = frozenset({"text"}) - def __init__(self, delay: float = 0.15) -> None: + def __init__(self, delay: float = 0.15, concurrency: int = 1) -> None: self.delay = delay + self.concurrency = concurrency self.n_truncated = 0 self._lock = __import__("threading").Lock() self.max_in_flight = 0 @@ -731,16 +729,16 @@ def solve(c): def test_threaded_coded_pipeline_gets_its_own_replies(tmp_path, concurrency): """Eight sandbox threads in flight: every reply must land in the thread that asked for it (old bridge: whichever thread read stdin next got it), - and with concurrency>1 the host really services calls in parallel.""" + and a model that takes several requests at once really gets them.""" import time as _t from evalrx.eval_agent.stages.fix.pipeline import run_coded_pipeline - model = EchoPromptModel(delay=0.15) + model = EchoPromptModel(delay=0.15, concurrency=concurrency) batch = _mc_batch(n_fail=6, n_pass=6) t0 = _t.monotonic() result = run_coded_pipeline(_THREADED_PIPELINE, model, batch, workdir=tmp_path, - timeout_sec=60, concurrency=concurrency) + timeout_sec=60) elapsed = _t.monotonic() - t0 assert result.ok, result.error assert result.n_calls == 36 @@ -751,7 +749,7 @@ def test_threaded_coded_pipeline_gets_its_own_replies(tmp_path, concurrency): assert model.max_in_flight > 1 assert elapsed < 36 * 0.15 # parallel: well under the serial sum else: - assert model.max_in_flight == 1 # serial host: arrival order + assert model.max_in_flight == 1 # one request at a time def test_bridge_reply_carries_rid_and_errors_route_to_the_caller(tmp_path): @@ -779,30 +777,13 @@ def good(c): """ batch = _mc_batch(n_fail=1, n_pass=0) result = run_coded_pipeline(code, EchoPromptModel(delay=0.05), batch, - workdir=tmp_path, timeout_sec=30, concurrency=4) + workdir=tmp_path, timeout_sec=30) assert result.ok, result.error out = result.outputs[batch[0].id] assert out.startswith(f"echo:ok-{batch[0].id}//err:") assert "unknown case_id" in out -def test_fix_agent_passes_concurrency_to_the_coded_bridge(monkeypatch): - from evalrx.eval_agent.stages.fix import codegen as fix_codegen - from evalrx.eval_agent.stages.fix.pipeline import CodedPipelineResult - - seen = {} - - def fake_run(code, model, data, **kw): - seen.update(kw) - return CodedPipelineResult(outputs={c.id: "Answer: (B)" for c in data}, ok=True) - - monkeypatch.setattr(fix_codegen, "run_coded_pipeline", fake_run) - agent = FixAgent(judge=ScriptedJudge("[]"), max_tier="L2", concurrency=5) - cand = FixCandidate(tier=FixTier.L2_SCAFFOLD, name="coded", payload={"code": "x"}) - agent.coder.run(cand, CountingModel(), _mc_batch()) - assert seen["concurrency"] == 5 - - # ── allow_unverified=True: the exploratory fix path, opt-in ────────────────── # # Without an M4-verified hypothesis run_fix records a skipped stage (above). diff --git a/tests/test_eval_agent/test_log_schema.py b/tests/test_eval_agent/test_log_schema.py index b3033f09..0ea5d50d 100755 --- a/tests/test_eval_agent/test_log_schema.py +++ b/tests/test_eval_agent/test_log_schema.py @@ -20,19 +20,19 @@ def test_committed_schema_matches_builder(): """The shipped JSON file must equal build_schema() — re-render after edits.""" - from evalrx.eval_agent.log_schema import SCHEMA_PATH, build_schema + from evalrx.eval_agent.runlog.schema import SCHEMA_PATH, build_schema committed = json.loads(SCHEMA_PATH.read_text(encoding="utf-8")) assert committed == build_schema(), ( "run_log.schema.json is stale. Re-render it:\n" - " python -c \"import json; from evalrx.eval_agent.log_schema import " + " python -c \"import json; from evalrx.eval_agent.runlog.schema import " "build_schema, SCHEMA_PATH; SCHEMA_PATH.write_text(json.dumps(build_schema(), " "indent=2)+chr(10))\"" ) def test_schema_is_valid_draft_2020_12(): - from evalrx.eval_agent.log_schema import build_schema + from evalrx.eval_agent.runlog.schema import build_schema schema = build_schema() cls = jsonschema.validators.validator_for(schema) @@ -42,7 +42,7 @@ def test_schema_is_valid_draft_2020_12(): def test_validation_rejects_malformed_events(): """The schema must actually reject the breakage it claims to catch.""" - from evalrx.eval_agent.log_schema import RUN_LOG_SCHEMA_VERSION, validate_event + from evalrx.eval_agent.runlog.schema import RUN_LOG_SCHEMA_VERSION, validate_event base = { "event": "probe", "schema_version": RUN_LOG_SCHEMA_VERSION, diff --git a/tests/test_eval_agent/test_loop_explore_step.py b/tests/test_eval_agent/test_loop_explore_step.py index 064f6688..efd34583 100644 --- a/tests/test_eval_agent/test_loop_explore_step.py +++ b/tests/test_eval_agent/test_loop_explore_step.py @@ -23,8 +23,8 @@ from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.core.result import Result from evalrx.eval_agent.hypothesis import Hypothesis -from evalrx.eval_agent.loop import VLDiagnoseLoop -from evalrx.eval_agent.run_logger import RunLogger +from evalrx.eval_agent.loop.diagnose import VLDiagnoseLoop +from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.eval_agent.stages.diagnosis import DiagnosisResult, ExploreContext from evalrx.eval_agent.stages.protocol import ExperimentProtocol from evalrx.reporting.run_events import read_run_events @@ -363,18 +363,18 @@ def test_real_m3_gets_the_explore_notes_and_the_rendered_png(tmp_path): def test_default_explore_dir_with_a_run_context_stays_off_the_run_root(tmp_path): - """Regression test for the bug where _explore_out_dir() hand-derived + """Regression test for the bug where explore_out_dir() hand-derived ctx.root/"explore" instead of calling ctx.explore_dir — which would have left real files outside the JSON-only run artifact, never cleaned up by finalize()'s runtime_root rmtree.""" - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext calls: list[str] = [] workdir = tmp_path / "sandbox" _seed_workdir(workdir) with RunContext(tmp_path / "run") as ctx: loop, _ = _loop(calls, _Explorer(calls, report=_report(workdir)), run_logger=ctx.logger) - out_dir = loop._explore_out_dir() + out_dir = loop.stages().explore_out_dir() assert out_dir == ctx.explore_dir assert ctx.runtime_root in out_dir.parents assert out_dir != ctx.root / "explore" @@ -392,20 +392,20 @@ def test_default_explore_dir_beside_a_standalone_logs_dir_and_inside_other_dirs( ("run_2026", tmp_path / "run_2026" / "explore")): logger = RunLogger(run_dir=tmp_path / name, observability_mode="offline") loop, _ = _loop(calls, _Explorer(calls, report=_report()), run_logger=logger) - assert loop._explore_out_dir() == expected, name + assert loop.stages().explore_out_dir() == expected, name logger.close() # no logger and no explicit dir: nothing is persisted, notes stay in memory loop, diag = _loop(calls, _Explorer(calls, report=_report())) - assert loop._explore_out_dir() is None + assert loop.stages().explore_out_dir() is None loop.run(_batch()) assert diag.seen_context[0] is not None def test_agentic_explore_publishes_artifacts_and_passes_notes_to_m3(tmp_path): - from evalrx.eval_agent.agentic.board import EvidenceBoard - from evalrx.eval_agent.agentic.tools import _explore_data - from evalrx.eval_agent.policy import RunState - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.loop.judge.board import EvidenceBoard + from evalrx.eval_agent.loop.judge.tools import _explore_data + from evalrx.eval_agent.loop.state import RunState + from evalrx.eval_agent.runlog.context import RunContext calls = [] workdir = tmp_path / 'sandbox' @@ -414,13 +414,13 @@ def test_agentic_explore_publishes_artifacts_and_passes_notes_to_m3(tmp_path): data = _batch() with RunContext(tmp_path / 'run') as ctx: loop, diag = _loop(calls, explorer, run_logger=ctx.logger) - state = RunState(original_data=data, data=data, timings={}) + state = RunState(original_data=data, data=data, stages=loop.stages(), timings={}) state.probe_results = loop.probe_agent.probe(loop.model, data) outcome = _explore_data(loop, state)(EvidenceBoard(), {'question': 'Inspect long chains'}) assert outcome.ok assert explorer.question == 'Inspect long chains' assert explorer.outcome_col == 'label' - loop._do_m3(0, None, [], state.timings, cases=data) + state.stages.diagnose(0, None, [], state.timings, cases=data) assert diag.seen_context[-1] is not None assert state.timings['explore'] > 0 events = read_run_events(tmp_path / 'run') diff --git a/tests/test_eval_agent/test_loop_narration.py b/tests/test_eval_agent/test_loop_narration.py index 03abc78a..970b5d13 100644 --- a/tests/test_eval_agent/test_loop_narration.py +++ b/tests/test_eval_agent/test_loop_narration.py @@ -5,7 +5,7 @@ import io -from evalrx.eval_agent.narration import LoopNarrator, _supports_color +from evalrx.eval_agent.runlog.narration import LoopNarrator, _supports_color def _narrator() -> tuple[LoopNarrator, io.StringIO]: diff --git a/tests/test_eval_agent/test_m1_full_logging.py b/tests/test_eval_agent/test_m1_full_logging.py index 43a7d0c2..b0c9ce20 100644 --- a/tests/test_eval_agent/test_m1_full_logging.py +++ b/tests/test_eval_agent/test_m1_full_logging.py @@ -13,7 +13,7 @@ def test_log_probe_persists_full_results_and_failed_analyzers(tmp_path): from evalrx.core.result import Result - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger logger = RunLogger(run_dir=tmp_path / "run", observability_mode="offline") res = Result( @@ -47,7 +47,7 @@ def test_log_probe_persists_full_results_and_failed_analyzers(tmp_path): def test_log_probe_without_failures_omits_failed_analyzers(tmp_path): """No failures -> no failed_analyzers key (kept optional/additive).""" from evalrx.core.result import Result - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger logger = RunLogger(run_dir=tmp_path / "run", observability_mode="offline") logger.log_probe(0, {"pope": Result(analyzer="pope", model="m", findings={"acc": 0.9})}) diff --git a/tests/test_eval_agent/test_model_call_instrumentation.py b/tests/test_eval_agent/test_model_call_instrumentation.py index 3b6c6a10..47949623 100644 --- a/tests/test_eval_agent/test_model_call_instrumentation.py +++ b/tests/test_eval_agent/test_model_call_instrumentation.py @@ -15,7 +15,7 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs -from evalrx.eval_agent.run_logger import RunLogger +from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.eval_agent.stages.probe_agent import ProbeAgent from tests.conftest import FakeModel @@ -135,7 +135,7 @@ def test_probe_still_works_when_run_logger_is_absent(tmp_path): def test_log_probe_drains_calls_tagged_under_a_stale_cycle(tmp_path): """Regression pin for the bug the advisor's review caught live: a caller - (VLDiagnoseLoop._m4_holdout_pass, before it was fixed) can stamp + (Stages.test_on_holdout, before it was fixed) can stamp current_cycle AFTER probe() already ran, so every call this round made gets tagged under the PREVIOUS cycle's number — a different key than the one log_probe is about to be called with. log_probe must drain the whole diff --git a/tests/test_eval_agent/test_policy.py b/tests/test_eval_agent/test_policy.py index 544a4553..95beffe1 100644 --- a/tests/test_eval_agent/test_policy.py +++ b/tests/test_eval_agent/test_policy.py @@ -8,7 +8,7 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.eval_agent import AutoDiagnoseReport, FixedOrderPolicy, JudgePolicy, VLDiagnoseLoop -from evalrx.eval_agent.run_context import RunContext +from evalrx.eval_agent.runlog.context import RunContext from evalrx.eval_agent.stages.protocol import ExperimentProtocol from evalrx.reporting.run_events import read_run_events from tests.conftest import FakeModel @@ -37,12 +37,12 @@ def test_a_custom_policy_gets_the_loop_and_the_run_bracket(tmp_path): class OneStep: def run(self, loop, data, timings): - seen["tokens_reset"] = loop._tokens_used == 0 + seen["tokens_reset"] = loop.stages().memory.tokens_used == 0 timings["m1"] = 1.5 return AutoDiagnoseReport(cycles=1, stopped_by="custom", store=loop.store) ctx, loop = _loop(tmp_path, policy=OneStep()) - loop._tokens_used = 99 + loop.stages().memory.tokens_used = 99 data = CaseBatch([FailureCase(inputs=Inputs(prompt="q"), label=Label.FAIL)]) report = loop.run(data) diff --git a/tests/test_eval_agent/test_probe_generator.py b/tests/test_eval_agent/test_probe_generator.py index c74d1797..78839de4 100755 --- a/tests/test_eval_agent/test_probe_generator.py +++ b/tests/test_eval_agent/test_probe_generator.py @@ -157,10 +157,11 @@ def _stub_run_direct(analyzer, m, data): @pytest.mark.parametrize("max_workers", [1, 8]) def test_whitebox_analyzers_run_serially_not_in_thread_pool(max_workers): - """White-box analyzers (GPU forward on the shared model) must run on the - calling thread, not the ThreadPoolExecutor — concurrent forwards race on - accelerate hooks (meta-tensor errors) and stack activations to OOM - (defect 7). Black-box analyzers may still parallelise.""" + """In-process analyzers run on the calling thread, whatever ``max_workers`` + says. White-box ones race on accelerate hooks (meta-tensor errors) and stack + activations to OOM in threads (defect 7); black-box ones already send their + questions to the backend as batches, so threads would only multiply the + requests in flight. ``max_workers`` is for Docker-mode analyzers.""" import threading from evalrx.core.analyzer import Analyzer @@ -194,8 +195,8 @@ def _run(self, model, cases): model = RefusingModel(capabilities={Capability.GENERATE, Capability.ATTENTION}) results = agent.probe(model, _cases()) assert set(results) == {"wb_a", "bb_b"} - assert ran_on["wb_a"] == main_thread # white-box ran serially - assert (ran_on["bb_b"] == main_thread) == (max_workers == 1) + assert ran_on["wb_a"] == main_thread + assert ran_on["bb_b"] == main_thread def test_failed_analyzers_surface_in_next_selection_prompt(): @@ -217,3 +218,73 @@ def generate(self, prompt, **kw): agent.probe(model, _cases(), protocol=proto) assert "FAILED AT RUNTIME" in captured["prompt"] assert "logit_lens" in captured["prompt"] + + +# ── the host's input file survives whatever the code writer does to it ────── + + +class TidyingCoder(ScriptedJudge): + """Writes a good probe, having first tried it on made-up cases and removed + the input file afterwards: what a coding agent did in 3 of 19 sessions.""" + + def __init__(self, code: str, workdir) -> None: + super().__init__(code) + self._workdir = workdir + + def generate(self, prompt: str, **kw) -> str: + path = self._workdir / "m1_probe_input.json" + path.write_text('{"cases": [{"id": "invented", "output": "sorry"}]}') + path.unlink() + return super().generate(prompt, **kw) + + +def test_the_probe_reads_the_real_cases_after_the_coder_deleted_the_input(tmp_path): + from evalrx.agent_runtime.sandbox import ExperimentSandbox + + sandbox = ExperimentSandbox(tmp_path) + gen = ProbeGenerator(judge=TidyingCoder(_GOOD_PROBE, sandbox.workdir), sandbox=sandbox) + + result, probe = gen.generate("detect refusals", RefusingModel(), _cases(), name="refusal") + + assert probe is not None and result is not None + assert [row["sample_id"] for row in result.findings["per_case"]] == ["c0", "c1", "c2", "c3"] + assert result.findings["refusal_rate"] == 0.5 + + +def test_a_sandbox_input_that_was_overwritten_is_restored_before_the_run(tmp_path): + from evalrx.agent_runtime.sandbox import ExperimentSandbox + + sandbox = ExperimentSandbox(tmp_path) + sandbox.put("data/in.json", '{"n": 3}') + (sandbox.workdir / "data" / "in.json").write_text('{"n": 0}') + + run = sandbox.run('import json; print(json.load(open("data/in.json"))["n"])') + + assert run.ok and run.stdout.strip() == "3" + + +class Events: + def __init__(self) -> None: + self.codegen: list[dict] = [] + + def log_tool_codegen(self, **fields): + self.codegen.append(fields) + + def log_model_call(self, **fields): + pass + + +@pytest.mark.parametrize("code, reason", [ + ("raise ValueError('bad column')", "exited with code 1: ValueError: bad column"), + (_NO_MARKER_PROBE, "printed no readable PROBE_RESULT_JSON= line"), + ("import time; time.sleep(30)", "was killed after 1s"), +]) +def test_a_failed_probe_run_is_logged_with_what_went_wrong(code, reason): + log = Events() + gen = ProbeGenerator(judge=ScriptedJudge(code), run_logger=log, timeout_sec=1) + + result, probe = gen.generate("detect refusals", RefusingModel(), _cases()) + + assert result is None and probe is None + (event,) = log.codegen + assert event["ok"] is False and reason in event["error"] diff --git a/tests/test_eval_agent/test_probe_limits.py b/tests/test_eval_agent/test_probe_limits.py new file mode 100644 index 00000000..1a9fc9f7 --- /dev/null +++ b/tests/test_eval_agent/test_probe_limits.py @@ -0,0 +1,112 @@ +"""M1 stays bounded: an analyzer cap, a time budget, and no analyzers that read one case.""" + +from __future__ import annotations + +import time + +from evalrx.core.capability import Capability +from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label +from evalrx.core.registry import registry +from evalrx.eval_agent.stages.probe_agent import ProbeAgent +from tests.conftest import FakeModel + + +def _batch(n: int) -> CaseBatch: + return CaseBatch([ + FailureCase(inputs=Inputs(prompt=f"What is {i}+{i}?"), expected=str(2 * i), + observed=str(2 * i), label=Label.FAIL if i % 2 else Label.PASS) + for i in range(n) + ]) + + +def _single_case_names() -> set[str]: + return {name for name in registry.analyzers.list() + if getattr(registry.analyzers.get(name), "single_case", False)} + + +def test_an_analyzer_that_reads_one_case_is_not_selected_for_a_batch(): + model = FakeModel(capabilities={Capability.GENERATE, Capability.LOGPROBS}) + assert {"self_consistency", "verbalized_confidence"} <= _single_case_names() + + agent = ProbeAgent(max_analyzers=None) + agent.probe(model, _batch(4)) + assert not set(agent.last_schema.selected_analyzers) & _single_case_names() + + one = ProbeAgent(max_analyzers=None) + one.probe(model, _batch(1)) + assert set(one.last_schema.selected_analyzers) & _single_case_names() + + +def test_a_caller_that_names_a_single_case_analyzer_still_gets_it(): + model = FakeModel(capabilities={Capability.GENERATE}) + results = ProbeAgent().probe(model, _batch(3), analyzers=["self_consistency"]) + assert set(results) == {"self_consistency"} # and nothing was added to reach the cap + + +def test_the_default_cap_bounds_how_many_analyzers_run(): + model = FakeModel(capabilities={Capability.GENERATE, Capability.LOGPROBS}) + agent = ProbeAgent() + agent.probe(model, _batch(4)) + assert 0 < len(agent.last_schema.selected_analyzers) <= 6 + + +def test_analyzers_that_have_not_started_when_the_budget_is_spent_are_skipped(): + class Slow(FakeModel): + def generate(self, inputs, **kwargs) -> str: + time.sleep(0.05) + return "Answer: 1" + + lines: list[str] = [] + + class Console: + current_cycle = 0 + + def progress(self, stage: str, text: str) -> None: + lines.append(f"{stage} {text}") + + def log_model_call(self, **record) -> None: + pass + + agent = ProbeAgent(time_budget_sec=0.01, max_workers=1, run_logger=Console()) + results = agent.probe(Slow(capabilities={Capability.GENERATE}), _batch(2), + analyzers=["prompt_contrast", "termination_audit"]) + + assert set(results) == {"prompt_contrast"} # the first one always runs + assert "termination_audit" in agent.last_schema.rationale + assert "time budget" in agent.last_schema.rationale + assert any("prompt_contrast: done" in line for line in lines) + assert any("termination_audit: skipped" in line for line in lines) + + +def test_an_api_model_never_sees_more_than_its_concurrency_in_flight(): + """Analyzers batch their questions; running analyzers in threads on top of + that would multiply the requests an endpoint receives.""" + import threading + + from evalrx.models import RuntimeConfig, compose + + lock = threading.Lock() + live, peak = [0], [0] + + def _generate(prompt, model="", **kw): + with lock: + live[0] += 1 + peak[0] = max(peak[0], live[0]) + time.sleep(0.01) + with lock: + live[0] -= 1 + return "Answer: 1" + + served = compose("qwen3.5-2b", "api", RuntimeConfig(generate_fn=_generate, concurrency=3), set()) + results = ProbeAgent(max_workers=8).probe( + served, _batch(6), analyzers=["prompt_contrast", "perturbation_battery", "cot_faithfulness"]) + + assert len(results) == 3 + assert peak[0] == 3 + + +def test_the_cap_does_not_shorten_a_list_the_caller_named(): + model = FakeModel(capabilities={Capability.GENERATE}) + named = ["prompt_contrast", "termination_audit", "self_repair"] + results = ProbeAgent(max_analyzers=2).probe(model, _batch(4), analyzers=named) + assert set(results) == set(named) diff --git a/tests/test_eval_agent/test_probe_search_agent.py b/tests/test_eval_agent/test_probe_search_agent.py index 377aa457..86e7e3d8 100644 --- a/tests/test_eval_agent/test_probe_search_agent.py +++ b/tests/test_eval_agent/test_probe_search_agent.py @@ -9,6 +9,7 @@ from evalrx.core.case import CaseBatch, FailureCase, Inputs from evalrx.eval_agent.stages.probe_search_agent import ProbeSearchAgent +from tests.conftest import FakeModel def _seed_pool() -> CaseBatch: @@ -39,12 +40,12 @@ def generate(self, prompt: str, **kwargs) -> str: return '{"label": "PASS", "reason": "observed matches expected"}' -class _AlwaysWrongModel: +class _AlwaysWrongModel(FakeModel): def generate(self, inputs, **kwargs) -> str: return "WRONG" -class _AlwaysRightModel: +class _AlwaysRightModel(FakeModel): def generate(self, inputs, **kwargs) -> str: return "definitely correct" diff --git a/tests/test_eval_agent/test_run_logger.py b/tests/test_eval_agent/test_run_logger.py index cae333f0..d2df2b2e 100644 --- a/tests/test_eval_agent/test_run_logger.py +++ b/tests/test_eval_agent/test_run_logger.py @@ -1,5 +1,5 @@ """RunLogger conformance: every log_* method, exercised end to end, must -produce the tidy M1..M5 layout described in RUN_LOGGER.md — few files, +produce the tidy M1..M5 layout described in runlog/README.md — few files, same-type-in-one-json, one folder per stage, nothing but JSON except real binary media. @@ -22,7 +22,7 @@ def _emit_every_method(run_dir) -> "RunLogger": # noqa: F821 from evalrx.core import CaseBatch, FailureCase from evalrx.core.result import Result from evalrx.eval_agent.hypothesis import Hypothesis, HypothesisStatus - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.eval_agent.stages.diagnosis import DiagnosisResult from evalrx.eval_agent.stages.surgery import InterventionResult @@ -249,7 +249,7 @@ def test_unroutable_tag_with_no_alias_warns_and_lands_in_run_json(tmp_path): run.json["unrouted"] rather than silently dropped.""" import pytest - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger run_dir = tmp_path / "run1" logger = RunLogger(run_dir=run_dir) @@ -287,7 +287,7 @@ def test_probe_artifacts_land_under_that_stages_artifacts_dir(tmp_path): import numpy as np from evalrx.core.result import Result - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger run_dir = tmp_path / "run1" logger = RunLogger(run_dir=run_dir) @@ -311,7 +311,7 @@ def test_model_calls_are_recorded_and_probe_events_stay_intact_alongside(tmp_pat """ProbeAgent + RunLogger together must capture every target-model call.""" from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.eval_agent.stages.probe_agent import ProbeAgent from tests.conftest import FakeModel @@ -345,7 +345,7 @@ def test_atomic_write_leaves_a_valid_file_after_every_event(tmp_path): def test_close_ends_the_langfuse_trace(tmp_path): run_dir = tmp_path / "run1" - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger logger = RunLogger(run_dir=run_dir) logger.log_run_start({"model": "fake"}) @@ -364,7 +364,7 @@ def test_full_loop_run_is_a_drop_in_replacement_for_run_logger(tmp_path): from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.eval_agent import DiagnosisAgent, VLDiagnoseLoop - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.eval_agent.stages.protocol import ExperimentProtocol from tests.conftest import FakeModel from tests.test_eval_agent.test_vl_diagnose import ScriptedModel @@ -408,7 +408,7 @@ def test_run_context_v2_keeps_only_json_and_media_and_inlines_reports(tmp_path): """The real integration boundary is RunContext, not a standalone logger.""" from types import SimpleNamespace - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext root = tmp_path / "run" ctx = RunContext(root, config={"model": "fake"}, observability_mode="offline") @@ -458,7 +458,7 @@ def test_run_context_v2_keeps_only_json_and_media_and_inlines_reports(tmp_path): def test_run_context_v2_snapshots_explore_text_and_media(tmp_path): from types import SimpleNamespace - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext root = tmp_path / "run" ctx = RunContext(root, observability_mode="offline") @@ -492,7 +492,7 @@ def test_run_context_v2_root_holds_no_v1_named_directories(tmp_path): asserts directory names directly.""" from types import SimpleNamespace - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext root = tmp_path / "run" ctx = RunContext(root, observability_mode="offline") @@ -550,7 +550,7 @@ def test_reporting_reader_and_server_discover_v2_run(tmp_path): def test_non_numeric_probe_artifacts_survive_without_sidecar_files(tmp_path): from evalrx.core.result import Result - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger artifacts = {"details": {"answer": "yes"}, "samples": ["yes", "no"], "rows": [{"case_id": "a", "score": 0.5}]} @@ -564,7 +564,7 @@ def test_non_numeric_probe_artifacts_survive_without_sidecar_files(tmp_path): def test_fix_trials_and_remaining_runtime_survive_cleanup(tmp_path): - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext with RunContext(tmp_path, observability_mode="offline") as ctx: trials = [ctx.new_trial("fixes", name) for name in ("first", "second")] @@ -606,7 +606,7 @@ def test_failed_runtime_archive_does_not_delete_source(tmp_path, monkeypatch): import pytest - from evalrx.eval_agent.run_context import RunContext + from evalrx.eval_agent.runlog.context import RunContext ctx = RunContext(tmp_path, observability_mode="offline") ctx.logger.log_run_start({}) @@ -637,7 +637,7 @@ def test_the_case_study_reads_m4_from_the_logged_bundle(tmp_path): def test_loop_summary_keeps_verified_hypothesis_evidence(tmp_path): from evalrx.eval_agent.hypothesis import Hypothesis, HypothesisStatus - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.eval_agent.stages.hypothesis_tester import HypothesisTestResult hypothesis = Hypothesis(statement="why", target_model="stub", predicted_failure_mode="mode") @@ -658,8 +658,8 @@ def test_loop_summary_keeps_verified_hypothesis_evidence(tmp_path): def test_persisted_event_identity_orders_concurrent_calls_and_validates(tmp_path, monkeypatch): from concurrent.futures import ThreadPoolExecutor - from evalrx.eval_agent.log_schema import EVENT_TYPES, _validator, build_schema - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger + from evalrx.eval_agent.runlog.schema import EVENT_TYPES, _validator, build_schema from evalrx.reporting.run_events import read_run_events monkeypatch.setenv("EVALRX_VALIDATE_LOG", "1") @@ -697,7 +697,7 @@ def test_persisted_event_identity_orders_concurrent_calls_and_validates(tmp_path def test_v2_schema_validation_warns_but_preserves_invalid_event(tmp_path, monkeypatch): import pytest - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger monkeypatch.setenv("EVALRX_VALIDATE_LOG", "1") with RunLogger(tmp_path, observability_mode="offline") as logger: @@ -737,7 +737,7 @@ def test_hypothesis_id_joins_m3_to_m4_and_m5(tmp_path): def test_outbox_dir_is_per_user(monkeypatch, tmp_path): # A shared /tmp/evalrx-outbox is owned by whoever created it first, so # every other user on the host failed with "unable to open database file". - import evalrx.eval_agent.run_logger as run_logger + import evalrx.eval_agent.runlog.logger as run_logger monkeypatch.setattr(run_logger.tempfile, "gettempdir", lambda: str(tmp_path)) monkeypatch.setattr(run_logger.getpass, "getuser", lambda: "alice") diff --git a/tests/test_eval_agent/test_run_logger_overlays.py b/tests/test_eval_agent/test_run_logger_overlays.py index 3d4b38e9..06c20bbe 100755 --- a/tests/test_eval_agent/test_run_logger_overlays.py +++ b/tests/test_eval_agent/test_run_logger_overlays.py @@ -54,7 +54,7 @@ class _FakeResultNoOverlays: def test_log_probe_returns_overlay_png_from_result_hook(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger logger = RunLogger(run_dir=tmp_path / "run1") pngs = logger.log_probe(0, {"fake_analyzer": _FakeResultWithOverlays()}) @@ -65,7 +65,7 @@ def test_log_probe_returns_overlay_png_from_result_hook(tmp_path): def test_log_probe_survives_image_overlays_raising(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger logger = RunLogger(run_dir=tmp_path / "run1") pngs = logger.log_probe(0, {"broken_analyzer": _FakeResultOverlaysRaise()}) @@ -74,7 +74,7 @@ def test_log_probe_survives_image_overlays_raising(tmp_path): def test_log_probe_without_image_overlays_hook_is_unaffected(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger logger = RunLogger(run_dir=tmp_path / "run1") pngs = logger.log_probe(0, {"plain_analyzer": _FakeResultNoOverlays()}) @@ -88,7 +88,7 @@ def test_log_probe_combines_overlay_and_npy_heatmap_pngs(tmp_path): pytest.importorskip("matplotlib") import numpy as np - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger @dataclass class _Mixed: diff --git a/tests/test_eval_agent/test_unmeasured_test_design.py b/tests/test_eval_agent/test_unmeasured_test_design.py new file mode 100644 index 00000000..368581b4 --- /dev/null +++ b/tests/test_eval_agent/test_unmeasured_test_design.py @@ -0,0 +1,52 @@ +"""M3 is asked to rewrite a test that names only evidence M2 did not measure.""" + +from __future__ import annotations + +from evalrx.analysis.stats_tools import StatsToolResult +from evalrx.eval_agent.stages.diagnosis import ( + HypothesisDraft, + Proposal, + _unmeasured_test_problems, +) +from evalrx.eval_agent.stages.hypothesis_tester import unmeasured_identifiers + +MEASURED = [ + StatsToolResult(tool="signal_label_assoc", effect=0.25, + config={"signal": "modality_ablation.grounded_in_image"}), + StatsToolResult(tool="signal_label_assoc", effect=None, # ran, no effect: not usable + config={"signal": "pope.gold_yes"}), +] + + +def _draft(test: str) -> HypothesisDraft: + return HypothesisDraft(hypothesis="The model answers without looking at the image.", + failure_mode="language_prior_bias", test=test) + + +def test_a_design_is_measured_when_it_names_a_signal_or_its_analyzer(): + for design in ("modality_ablation.grounded_in_image is lower on failures", + "grounded_in_image should be false on the failing cases", + "rerun modality_ablation and compare", + "failing cases should change less when the image is removed"): # prose only + assert unmeasured_identifiers(design, MEASURED) == set() + + +def test_a_design_that_names_only_case_ids_or_made_up_signals_is_unmeasured(): + assert unmeasured_identifiers("rad_pres_5 flips between runs", MEASURED) == {"rad_pres_5"} + assert unmeasured_identifiers("fixed_by_semantic_grading rises", MEASURED) == { + "fixed_by_semantic_grading"} + assert unmeasured_identifiers("pope.gold_yes is higher on failures", MEASURED) == { + "pope.gold_yes"} # measured without an effect + + +def test_the_feedback_names_the_hypothesis_and_what_it_asked_for(): + proposal = Proposal(hypotheses=[ + _draft("grounded_in_image is lower on failures"), + _draft("rad_pres_5 and rad_easy_1 are graded wrongly"), + ]) + feedback = _unmeasured_test_problems(proposal, MEASURED) + assert feedback is not None + assert "hypothesis 2's test names rad_easy_1, rad_pres_5" in feedback + assert "hypothesis 1" not in feedback + assert feedback.endswith("Signals with a result: modality_ablation.grounded_in_image") + assert _unmeasured_test_problems(Proposal(hypotheses=proposal.hypotheses[:1]), MEASURED) is None diff --git a/tests/test_eval_agent/test_verbose_logging.py b/tests/test_eval_agent/test_verbose_logging.py index 41b84f6c..8f4eb1c0 100644 --- a/tests/test_eval_agent/test_verbose_logging.py +++ b/tests/test_eval_agent/test_verbose_logging.py @@ -10,7 +10,7 @@ import logging import evalrx -from evalrx.eval_agent.loop import VLDiagnoseLoop +from evalrx.eval_agent.loop.diagnose import VLDiagnoseLoop from evalrx.eval_agent.stages.fix.agent import FixAgent from evalrx.eval_agent.stages.protocol import ExperimentProtocol from evalrx.logging_utils import _MARKER_ATTR, TOP_LEVEL_LOGGER_NAME @@ -57,7 +57,7 @@ def test_loop_stage_narration_is_actually_visible(capsys): VLDiagnoseLoop( model=FakeModel(), protocol=ExperimentProtocol(description="x"), verbose=True ) - logging.getLogger("evalrx.eval_agent.loop").info("m1 probing started") + logging.getLogger("evalrx.eval_agent.loop.diagnose").info("m1 probing started") out = capsys.readouterr() assert "m1 probing started" in out.out finally: diff --git a/tests/test_eval_agent/test_vl_diagnose.py b/tests/test_eval_agent/test_vl_diagnose.py index 9d28a2a1..4c702018 100755 --- a/tests/test_eval_agent/test_vl_diagnose.py +++ b/tests/test_eval_agent/test_vl_diagnose.py @@ -902,10 +902,12 @@ def test_analysis_only_stops_after_m2(self): def test_no_diagnosis_agent_stops_early(self, monkeypatch): loop = VLDiagnoseLoop(model=_vlm(), protocol=_spatial_protocol(), max_cycles=3) - def unavailable(): + from evalrx.eval_agent.loop.stages import Stages + + def unavailable(self): raise RuntimeError("judge unavailable") - monkeypatch.setattr(loop, "_get_diagnosis_agent", unavailable) + monkeypatch.setattr(Stages, "diagnosis_agent_or_default", unavailable) report = loop.run(_labeled_batch()) assert report.stopped_by == "diagnosis_error" assert report.cycles == 1 @@ -1080,7 +1082,7 @@ def diagnose(self, analysis, model_name="", prior_cycles=None): import json - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger run_logger = RunLogger(tmp_path / "logs") loop = VLDiagnoseLoop( @@ -1242,7 +1244,7 @@ def test_run_confirm_tests_on_holdout(self): def test_m3_transient_error_retries_without_reprobing(tmp_path): from types import SimpleNamespace - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger class Transient: calls = 0 @@ -1256,9 +1258,9 @@ def diagnose(self, analysis, **kwargs): agent = Transient() loop = VLDiagnoseLoop(model=_vlm(), protocol=_spatial_protocol(), diagnosis_agent=agent, run_logger=RunLogger(tmp_path / "logs")) - result = loop._do_m3(0, None, [], {}, log=False) + result = loop.stages().diagnose(0, None, [], {}, log=False) assert result is not None and result.hypotheses == [] assert agent.calls == 2 # A valid empty answer is not retried. - loop._do_m3(0, None, [], {}, log=False) + loop.stages().diagnose(0, None, [], {}, log=False) assert agent.calls == 3 diff --git a/tests/test_examples/test_benchmark_common.py b/tests/test_examples/test_benchmark_common.py index c9ffd907..4f600a2e 100644 --- a/tests/test_examples/test_benchmark_common.py +++ b/tests/test_examples/test_benchmark_common.py @@ -274,7 +274,7 @@ def test_cli_no_model_paths(common, capsys): _, _, _, run = common defaults = run.build_parser().parse_args([]) assert (defaults.judge_provider, defaults.judge_model, defaults.judge_effort) == ( - "claude", None, "high" + "claude", None, "medium" ) assert defaults.held_out is False assert defaults.fix_repair_rounds == 2 @@ -304,8 +304,8 @@ def test_leaf_compose_files_cover_every_cell_and_leave_judge_to_cli_default(comm svc = services[size.key] cmd = svc["command"] assert f"--model {size.key}" in cmd and f"--modality {modality}" in cmd - # no per-service judge pin: the CLI default (claude / claude-opus-5 / - # high) rules, and EXTRA_ARGS can still override per run + # no per-service judge pin: the CLI default (claude / sonnet / + # medium) rules, and EXTRA_ARGS can still override per run assert "--judge-provider" not in cmd assert ("--device auto" in cmd) == (size.gpus > 1) assert svc["extends"]["file"] == "../../_common/compose/base.yml" diff --git a/tests/test_models/test_wrap.py b/tests/test_models/test_wrap.py index 4cc4a86c..5767cbc8 100755 --- a/tests/test_models/test_wrap.py +++ b/tests/test_models/test_wrap.py @@ -280,3 +280,250 @@ def generate(self, **kwargs): assert recorder.captured["temperature"] == 0.7 assert recorder.captured["stop_strings"] == ["DONE"] assert recorder.captured["tokenizer"] is m._hf[1] + + +class _PaddingTokenizer(FakeTokenizer): + pad_token_id = 0 + + +class _RecordingLM(nn.Module): + """Appends one token to each row: 100 + the row's prompt length.""" + + def __init__(self): + super().__init__() + self.param = nn.Parameter(torch.zeros(1)) + self.calls: list[dict] = [] + + def generate(self, **kwargs): + self.calls.append(kwargs) + ids = kwargs["input_ids"] + mask = kwargs.get("attention_mask", torch.ones_like(ids)) + return torch.cat([ids, 100 + mask.sum(dim=1, keepdim=True)], dim=1) + + +def test_hf_local_generate_batch_pads_longest_first_and_keeps_input_order(): + m = evalrx.wrap(FakeCausalLM(), FakeTokenizer()) + m.runtime.batch_size = 2 + lm = _RecordingLM() + m._hf = (lm, _PaddingTokenizer()) + + out = m.generate_batch(["one", "one two three", "one two"], max_new_tokens=5) + + assert out == ["t101", "t103", "t102"] # answers follow the inputs + first, second = lm.calls # longest first + assert first["input_ids"].tolist() == [[1, 2, 3], [0, 1, 2]] # padded on the left + assert first["attention_mask"].tolist() == [[1, 1, 1], [0, 1, 1]] + assert second["input_ids"].tolist() == [[1]] + assert all(call["max_new_tokens"] == 5 for call in lm.calls) + + +def test_hf_local_batches_a_multimodal_spec_by_stacking_single_encodings(monkeypatch): + spec = ModelSpec(key="fake-vlm", family="fake", model_type="qwen3_5", hf_repo="", + auto_class="AutoModelForImageTextToText", processor_class="AutoProcessor", + vision=VisionSpec(image_token_id_attr="image_token_id")) + m = HFLocalModel(spec, RuntimeConfig(max_new_tokens=4)) + lm = _RecordingLM() + + class Processor: + tokenizer = _PaddingTokenizer() + + def encode(inputs, model, processor): + n = len(inputs.prompt.split()) + enc = {"input_ids": torch.arange(1, n + 1).unsqueeze(0), + "attention_mask": torch.ones(1, n, dtype=torch.long), + "pixel_values": torch.full((inputs.image, 3), float(n))} # one row per patch + return enc, [], [], None + + m._hf = (lm, Processor()) + monkeypatch.setattr(m, "_encode_vlm", encode) + + out = m.generate_batch([Inputs(prompt="a b", image=2), Inputs(prompt="a b c d", image=1), + Inputs(prompt="a", image=3)]) + + assert out == ["t102", "t104", "t101"] + (call,) = lm.calls + assert call["input_ids"].tolist() == [[1, 2, 3, 4], [0, 0, 1, 2], [0, 0, 0, 1]] + # Per-patch rows stay flat, in the order of the batch rows. + assert call["pixel_values"][:, 0].tolist() == [4.0, 2.0, 2.0, 1.0, 1.0, 1.0] + + +def test_hf_local_runs_inputs_one_at_a_time_when_their_media_do_not_stack(monkeypatch): + spec = ModelSpec(key="fake-vlm", family="fake", model_type="qwen3_5", hf_repo="", + auto_class="AutoModelForImageTextToText", processor_class="AutoProcessor", + vision=VisionSpec(image_token_id_attr="image_token_id")) + m = HFLocalModel(spec, RuntimeConfig(max_new_tokens=4)) + lm = _RecordingLM() + + class Processor: + tokenizer = _PaddingTokenizer() + + def encode(inputs, model, processor): + enc = {"input_ids": torch.tensor([[1, 2]]), + "pixel_values": torch.zeros(1, 3, inputs.image, inputs.image)} # per-input size + return enc, [], [], None + + m._hf = (lm, Processor()) + monkeypatch.setattr(m, "_encode_vlm", encode) + + out = m.generate_batch([Inputs(prompt="a b", image=4), Inputs(prompt="a b", image=8)]) + + assert out == ["t102", "t102"] + assert [call["input_ids"].shape[0] for call in lm.calls] == [1, 1] + + +def test_hf_local_batches_inputs_with_and_without_an_image_separately(monkeypatch): + spec = ModelSpec(key="fake-vlm", family="fake", model_type="qwen3_5", hf_repo="", + auto_class="AutoModelForImageTextToText", processor_class="AutoProcessor", + vision=VisionSpec(image_token_id_attr="image_token_id")) + m = HFLocalModel(spec, RuntimeConfig(max_new_tokens=4)) + lm = _RecordingLM() + + class Processor: + tokenizer = _PaddingTokenizer() + + def encode(inputs, model, processor): + n = len(inputs.prompt.split()) + enc = {"input_ids": torch.arange(1, n + 1).unsqueeze(0)} + if inputs.image is not None: + enc["pixel_values"] = torch.zeros(1, 3) + return enc, [], [], None + + m._hf = (lm, Processor()) + monkeypatch.setattr(m, "_encode_vlm", encode) + + out = m.generate_batch([Inputs(prompt="a", image=1), Inputs(prompt="a b"), + Inputs(prompt="a b c", image=1), Inputs(prompt="a b c d")]) + + assert out == ["t101", "t102", "t103", "t104"] + assert [("pixel_values" in call, call["input_ids"].shape[0]) for call in lm.calls] == [ + (True, 2), (False, 2)] + + +def test_hf_local_encodes_a_long_list_a_window_at_a_time(): + m = evalrx.wrap(FakeCausalLM(), FakeTokenizer()) + m.runtime.batch_size = 2 + events: list[str] = [] + + class Tok(_PaddingTokenizer): + def __call__(self, text, return_tensors="pt"): + events.append("encode") + return super().__call__(text, return_tensors) + + class LM(_RecordingLM): + def generate(self, **kwargs): + events.append(f"generate{kwargs['input_ids'].shape[0]}") + return super().generate(**kwargs) + + m._hf = (LM(), Tok()) + + out = m.generate_batch(["one"] * 20) + + assert out == ["t101"] * 20 + # Eight encodings, their four batches, then the next eight: never all twenty at once. + assert events[:12] == ["encode"] * 8 + ["generate2"] * 4 + assert events.count("encode") == 20 and events.count("generate2") == 10 + + +def test_hf_local_does_not_batch_a_multimodal_family_that_was_not_checked(monkeypatch): + spec = ModelSpec(key="fake-vlm", family="fake", model_type="some_new_vlm", hf_repo="", + auto_class="AutoModelForImageTextToText", processor_class="AutoProcessor", + vision=VisionSpec(image_token_id_attr="image_token_id")) + m = HFLocalModel(spec, RuntimeConfig(max_new_tokens=4)) + lm = _RecordingLM() + + class Processor: + tokenizer = _PaddingTokenizer() + + def encode(inputs, model, processor): + return ({"input_ids": torch.tensor([[1, 2]]), "pixel_values": torch.zeros(1, 3)}, + [], [], None) + + m._hf = (lm, Processor()) + monkeypatch.setattr(m, "_encode_vlm", encode) + + assert m.generate_batch([Inputs(prompt="a b", image=1)] * 3) == ["t102"] * 3 + assert [call["input_ids"].shape[0] for call in lm.calls] == [1, 1, 1] + + +def test_hf_local_logprobs_batch_ends_each_row_at_its_own_stop_token(): + m = evalrx.wrap(FakeCausalLM(), FakeTokenizer()) + + class Out: + # Row 0 stops after one token (7 = end of sequence) and is padded. + sequences = torch.tensor([[1, 2, 7, 0], [0, 1, 5, 6]]) + scores = (torch.zeros(2, 16), torch.zeros(2, 16)) + + class LM(nn.Module): + generation_config = type("G", (), {"eos_token_id": 7})() + + def __init__(self): + super().__init__() + self.param = nn.Parameter(torch.zeros(1)) + + def generate(self, **kwargs): + assert kwargs["output_scores"] and not kwargs["do_sample"] + return Out() + + m._hf = (LM(), _PaddingTokenizer()) + + first, second = m.logprobs_batch(["one two", "one"]) + + assert [t.token for t in first] == ["t7"] + assert [t.token for t in second] == ["t5", "t6"] + + +def test_hf_local_uses_the_runtime_sampling_unless_the_call_passes_its_own(): + m = evalrx.wrap(FakeCausalLM(), FakeTokenizer()) + m.runtime.sampling = {"do_sample": True, "temperature": 0.6, "top_p": 0.95} + lm = _RecordingLM() + m._hf = (lm, FakeTokenizer()) + + m.generate(Inputs(prompt="hi")) + assert {k: lm.calls[-1][k] for k in ("do_sample", "temperature", "top_p")} == { + "do_sample": True, "temperature": 0.6, "top_p": 0.95} + + m.generate(Inputs(prompt="hi"), temperature=1.0) + assert lm.calls[-1]["temperature"] == 1.0 and lm.calls[-1]["do_sample"] is True + + m.generate(Inputs(prompt="hi"), do_sample=False) # greedy: no sampling knobs reach HF + assert lm.calls[-1]["do_sample"] is False + assert not {"temperature", "top_p"} & set(lm.calls[-1]) + + +def test_vllm_offline_hands_the_engine_every_prompt_at_once(monkeypatch): + import sys + import types + + from evalrx.models.backends.vllm_offline import VLLMOfflineModel + + class SamplingParams: + def __init__(self, **kwargs): + self.kwargs = kwargs + + monkeypatch.setitem(sys.modules, "vllm", types.SimpleNamespace(SamplingParams=SamplingParams)) + + class Engine: + def __init__(self): + self.calls: list[tuple[list[str], dict]] = [] + + def get_tokenizer(self): + return FakeTokenizer() + + def generate(self, prompts, params): + self.calls.append((list(prompts), params.kwargs)) + completion = lambda p: types.SimpleNamespace( # noqa: E731 + text=p.upper(), token_ids=[len(p)], logprobs=[{len(p): -0.5, 99: -2.0}]) + return [types.SimpleNamespace(outputs=[completion(p)]) for p in prompts] + + spec = ModelSpec(key="fake-lm", family="fake", model_type="fake", hf_repo="", + auto_class="AutoModelForCausalLM", processor_class="AutoTokenizer") + m = VLLMOfflineModel(spec, RuntimeConfig(max_new_tokens=8)) + m._llm = engine = Engine() + + assert m.generate_batch(["ab", "cde"], do_sample=False) == ["AB", "CDE"] + rows = m.logprobs_batch(["ab", "cde"], top_k=2) + + assert [prompts for prompts, _ in engine.calls] == [["ab", "cde"], ["ab", "cde"]] + assert engine.calls[1][1]["logprobs"] == 2 + assert [[(t.token, t.logprob) for t in row] for row in rows] == [[("t2", -0.5)], [("t3", -0.5)]] + assert rows[0][0].top == {"t2": -0.5, "t99": -2.0} diff --git a/tests/test_observability/test_outbox.py b/tests/test_observability/test_outbox.py index 11b1a8ec..87cf6f48 100644 --- a/tests/test_observability/test_outbox.py +++ b/tests/test_observability/test_outbox.py @@ -69,7 +69,7 @@ def test_skipped_stage_keeps_its_pipeline_stage_in_the_envelope(): def test_backfill_dry_run_preserves_existing_trace_and_order(tmp_path): - from evalrx.eval_agent.run_logger import RunLogger + from evalrx.eval_agent.runlog.logger import RunLogger from evalrx.observability import backfill_run_to_langfuse trace_id = "00000000-0000-0000-0000-000000000001" diff --git a/tools/demo_video/storyboard.py b/tools/demo_video/storyboard.py index b656adb4..9a1a3485 100644 --- a/tools/demo_video/storyboard.py +++ b/tools/demo_video/storyboard.py @@ -35,7 +35,7 @@ from pathlib import Path from typing import Any -# The narrator's own geometry (evalrx/eval_agent/narration.py), duplicated here +# The narrator's own geometry (evalrx/eval_agent/runlog/narration.py), duplicated here # so a storyboard can be built without importing evalrx. LABEL_WIDTH = 12 STAGE_LABELS = {"M1": "probe", "M2": "explore", "M3": "diagnose", @@ -288,7 +288,7 @@ def from_run_dir(path: Path) -> dict[str, Any]: import sys sys.path.insert(0, str(Path(__file__).resolve().parents[2])) - from evalrx.eval_agent.narration import LoopNarrator # noqa: E402 + from evalrx.eval_agent.runlog.narration import LoopNarrator # noqa: E402 logs = path / "logs" if (path / "logs" / "run.json").exists() else path run = json.loads((logs / "run.json").read_text())