Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
91b7f5d
Group eval_agent into loop/ and runlog/
Nanboy-Ronan Nov 20, 2026
2a41967
Move the stages out of the loop class into Stages
Nanboy-Ronan Nov 20, 2026
cfa7301
Default the Claude judge to sonnet
Nanboy-Ronan Nov 21, 2026
6d72422
Make batch generation part of the Model interface
Nanboy-Ronan Nov 21, 2026
620ad46
Bound M1: analyzer cap, time budget, progress lines
Nanboy-Ronan Nov 21, 2026
e66319b
Default hf_local batches to 32 prompts
Nanboy-Ronan Nov 21, 2026
b3af818
Ask M3 once to rewrite a test that names unmeasured evidence
Nanboy-Ronan Nov 21, 2026
154a6a1
One setting for requests in flight against an API backend
Nanboy-Ronan Nov 21, 2026
4daa90f
Record how much of an answer flip is decoding noise under sampling
Nanboy-Ronan Nov 21, 2026
d8d66f1
Update the JAX design note on concurrency and batching
Nanboy-Ronan Nov 21, 2026
07cbf95
Batch the fix stage's model calls and drop its thread pools
Nanboy-Ronan Nov 21, 2026
a7ce636
Keep a generated script's input files when the coding agent removes them
Nanboy-Ronan Nov 21, 2026
bde6f8e
Define the mmau example's coder config before the fix agent reads it
Nanboy-Ronan Nov 21, 2026
a206dbb
Let the examples follow the package's default Claude model
Nanboy-Ronan Nov 21, 2026
e5a247b
Batch multimodal inputs and logprobs on hf_local; batch the last per-…
Nanboy-Ronan Nov 21, 2026
17d45eb
Measure the fix baseline once for a model and its cases
Nanboy-Ronan Nov 21, 2026
8baf99b
Encode a long batch a window at a time; key the fix baseline on what …
Nanboy-Ronan Nov 21, 2026
9c7a5e9
Probe the judge model the run will use; score vl_shap's masks in chunks
Nanboy-Ronan Nov 21, 2026
5fe0bc9
Log the model and judge calls of a fix search that records no outcome
Nanboy-Ronan Nov 21, 2026
cd886f1
Ask verbalized_confidence's question with the case's image
Nanboy-Ronan Nov 21, 2026
78a6840
Label a sampled case by the majority of five answers in Stage 0
Nanboy-Ronan Nov 21, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
318 changes: 318 additions & 0 deletions CHANGELOG.md

Large diffs are not rendered by default.

120 changes: 101 additions & 19 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -209,26 +274,33 @@ 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.

### Package layout

```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<n>/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<n>/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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/contract/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 6 additions & 4 deletions docs/design_jax_backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/stage_io.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions evalrx/agent_runtime/judges/autodetect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
7 changes: 6 additions & 1 deletion evalrx/agent_runtime/judges/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 33 additions & 0 deletions evalrx/agent_runtime/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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.

Expand All @@ -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
Expand Down
Loading
Loading