API Reference for evaluation

evaluation

Evaluation library for adapter benchmarking and fitness scoring.

Provides functions for running benchmarks (HumanEval), calculating metrics (Pass@k, quality scores), comparing adapters, testing generalization, and computing evolutionary fitness for the evolution operator.

Functions

calculate_pass_at_k

calculate_pass_at_k(
    n_samples: int, n_correct: int, k: int = 1
) -> float

Calculate the Pass@k metric for code generation evaluation.

Computes the probability that at least one of k sampled solutions is correct, using the unbiased estimator from the HumanEval paper (Chen et al., 2021). This avoids the high-variance naive estimator.

Formula: 1 - prod((n-c-i)/(n-i) for i in range(k))

Parameters:

Name Type Description Default
n_samples int

Total number of samples generated per problem.

required
n_correct int

Number of correct samples out of n_samples.

required
k int

Number of attempts allowed for the Pass@k metric. Defaults to 1.

1

Returns:

Type Description
float

Pass@k probability as a float between 0.0 and 1.0.

Raises:

Type Description
ValueError

If n_correct > n_samples.

Example

score = calculate_pass_at_k(n_samples=100, n_correct=85, k=1) score 0.85

Source code in libs/evaluation/src/evaluation/metrics.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def calculate_pass_at_k(n_samples: int, n_correct: int, k: int = 1) -> float:
    """Calculate the Pass@k metric for code generation evaluation.

    Computes the probability that at least one of k sampled solutions is
    correct, using the unbiased estimator from the HumanEval paper
    (Chen et al., 2021). This avoids the high-variance naive estimator.

    Formula: 1 - prod((n-c-i)/(n-i) for i in range(k))

    Args:
        n_samples: Total number of samples generated per problem.
        n_correct: Number of correct samples out of n_samples.
        k: Number of attempts allowed for the Pass@k metric. Defaults to 1.

    Returns:
        Pass@k probability as a float between 0.0 and 1.0.

    Raises:
        ValueError: If n_correct > n_samples.

    Example:
        >>> score = calculate_pass_at_k(n_samples=100, n_correct=85, k=1)
        >>> score
        0.85
    """
    if n_correct > n_samples:
        raise ValueError(
            f"n_correct ({n_correct}) cannot be greater than n_samples ({n_samples})"
        )
    if n_correct == n_samples:
        return 1.0
    if n_samples - n_correct < k:
        return 1.0
    # Unbiased estimator: 1 - prod((n-c-i)/(n-i) for i in range(k))
    product = math.prod((n_samples - n_correct - i) / (n_samples - i) for i in range(k))
    return 1.0 - product

compare_adapters

compare_adapters(
    adapter_ids: list[str], benchmark: str = "humaneval"
) -> dict[str, Any]

Compare multiple adapters head-to-head on a benchmark.

Evaluates each adapter in the list on the specified benchmark and produces a comparative report with per-adapter scores, rankings, and a summary of which adapter performs best.

Parameters:

Name Type Description Default
adapter_ids list[str]

List of adapter UUIDs to compare. Must contain at least two adapter IDs.

required
benchmark str

Benchmark name to use for comparison. Currently supports "humaneval". Defaults to "humaneval".

'humaneval'

Returns:

Type Description
dict[str, Any]

Dictionary with comparison results including: - "scores": dict mapping adapter_id to its benchmark score - "rankings": list of adapter_ids sorted best-to-worst - "best_adapter": str, UUID of the top-performing adapter - "summary": str, human-readable comparison summary

Raises:

Type Description
NotImplementedError

compare_adapters is not yet implemented.

Example

results = compare_adapters(["adapter-001", "adapter-002"]) results["best_adapter"] in ["adapter-001", "adapter-002"] True results["best_adapter"] in results["rankings"] True

Source code in libs/evaluation/src/evaluation/metrics.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def compare_adapters(
    adapter_ids: list[str],
    benchmark: str = "humaneval",
) -> dict[str, Any]:
    """Compare multiple adapters head-to-head on a benchmark.

    Evaluates each adapter in the list on the specified benchmark and produces
    a comparative report with per-adapter scores, rankings, and a summary of
    which adapter performs best.

    Args:
        adapter_ids: List of adapter UUIDs to compare. Must contain at least
            two adapter IDs.
        benchmark: Benchmark name to use for comparison. Currently supports
            "humaneval". Defaults to "humaneval".

    Returns:
        Dictionary with comparison results including:
            - "scores": dict mapping adapter_id to its benchmark score
            - "rankings": list of adapter_ids sorted best-to-worst
            - "best_adapter": str, UUID of the top-performing adapter
            - "summary": str, human-readable comparison summary

    Raises:
        NotImplementedError: compare_adapters is not yet implemented.

    Example:
        >>> results = compare_adapters(["adapter-001", "adapter-002"])
        >>> results["best_adapter"] in ["adapter-001", "adapter-002"]
        True
        >>> results["best_adapter"] in results["rankings"]
        True
    """
    if len(adapter_ids) < 2:
        raise ValueError("compare_adapters requires at least 2 adapter IDs")

    # Without live inference, return a stub comparison based on adapter order
    scores: dict[str, float] = {}
    for i, aid in enumerate(adapter_ids):
        scores[aid] = 1.0 / (i + 1)  # Placeholder scoring

    rankings = sorted(scores, key=lambda x: scores[x], reverse=True)
    best = rankings[0]
    summary = f"Compared {len(adapter_ids)} adapters on {benchmark}; best={best}"

    return {
        "scores": scores,
        "rankings": rankings,
        "best_adapter": best,
        "summary": summary,
    }

evaluate_fitness

evaluate_fitness(
    adapter_id: str,
    pass_rate: float,
    diversity_score: float = 0.0,
) -> float

Calculate evolutionary fitness score for the evolution operator.

Computes a composite fitness score used by the evolutionary algorithm to rank and select adapters for mutation and crossover. Balances raw performance (pass_rate) with adapter diversity to avoid population collapse.

Parameters:

Name Type Description Default
adapter_id str

UUID of the adapter to evaluate.

required
pass_rate float

Fraction of benchmark tasks passed, in range 0.0 to 1.0.

required
diversity_score float

Adapter uniqueness metric representing how different this adapter is from others in the current population. Range 0.0 to 1.0; higher values indicate more unique adapters. Defaults to 0.0.

0.0

Returns:

Type Description
float

Fitness score as a float between 0.0 and 1.0. Higher values indicate

float

adapters more likely to be selected for the next evolutionary generation.

Raises:

Type Description
NotImplementedError

evaluate_fitness is not yet implemented.

Example

fitness = evaluate_fitness( ... "adapter-001", pass_rate=0.85, diversity_score=0.3, ... ) fitness 0.795 low_diversity = evaluate_fitness( ... "adapter-001", pass_rate=0.85, diversity_score=0.0, ... ) low_diversity < fitness True

Source code in libs/evaluation/src/evaluation/metrics.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def evaluate_fitness(
    adapter_id: str,
    pass_rate: float,
    diversity_score: float = 0.0,
) -> float:
    """Calculate evolutionary fitness score for the evolution operator.

    Computes a composite fitness score used by the evolutionary algorithm to
    rank and select adapters for mutation and crossover. Balances raw
    performance (pass_rate) with adapter diversity to avoid population collapse.

    Args:
        adapter_id: UUID of the adapter to evaluate.
        pass_rate: Fraction of benchmark tasks passed, in range 0.0 to 1.0.
        diversity_score: Adapter uniqueness metric representing how different
            this adapter is from others in the current population. Range 0.0
            to 1.0; higher values indicate more unique adapters. Defaults to 0.0.

    Returns:
        Fitness score as a float between 0.0 and 1.0. Higher values indicate
        adapters more likely to be selected for the next evolutionary generation.

    Raises:
        NotImplementedError: evaluate_fitness is not yet implemented.

    Example:
        >>> fitness = evaluate_fitness(
        ...     "adapter-001", pass_rate=0.85, diversity_score=0.3,
        ... )
        >>> fitness
        0.795
        >>> low_diversity = evaluate_fitness(
        ...     "adapter-001", pass_rate=0.85, diversity_score=0.0,
        ... )
        >>> low_diversity < fitness
        True
    """
    fitness = 0.7 * pass_rate + 0.3 * diversity_score
    return fitness

run_humaneval_subset

run_humaneval_subset(
    adapter_id: Optional[str],
    subset_size: int = 20,
    model: str = "Qwen/Qwen3.5-9B",
    completions: Optional[dict[str, str]] = None,
) -> dict[str, Any]

Run a HumanEval benchmark subset to evaluate an adapter.

Loads tasks from the bundled 20-task HumanEval subset JSON and evaluates them using the provided completions. For each task, concatenates prompt + completion + test + check(entry_point), writes to a temp script, and executes via subprocess. Exit code 0 = passed.

Parameters:

Name Type Description Default
adapter_id Optional[str]

UUID of the adapter to test (None = baseline, no adapter). Currently informational; inference wiring happens at a higher level.

required
subset_size int

Ignored — always uses the fixed 20-task bundled subset.

20
model str

Base model name (informational only, not used for inference here).

'Qwen/Qwen3.5-9B'
completions Optional[dict[str, str]]

Dict mapping task_id -> completion string. Only tasks with an entry in this dict are evaluated. If None or empty, returns empty results.

None

Returns:

Type Description
dict[str, Any]

Dictionary with benchmark results including: - "pass_count": int, number of tasks passed - "fail_count": int, number of tasks failed - "pass_rate": float, fraction of tasks passed (0.0 to 1.0) - "task_results": list of per-task result dicts with task_id, passed - "summary": str, human-readable summary

Raises:

Type Description
NotImplementedError

If completions are not provided (inference not wired).

Example

completions = {"HumanEval/0": " return []"} results = run_humaneval_subset(adapter_id=None, completions=completions) results["pass_count"] 0

Source code in libs/evaluation/src/evaluation/metrics.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def run_humaneval_subset(
    adapter_id: Optional[str],
    subset_size: int = 20,
    model: str = "Qwen/Qwen3.5-9B",
    completions: Optional[dict[str, str]] = None,
) -> dict[str, Any]:
    """Run a HumanEval benchmark subset to evaluate an adapter.

    Loads tasks from the bundled 20-task HumanEval subset JSON and evaluates
    them using the provided completions. For each task, concatenates
    prompt + completion + test + check(entry_point), writes to a temp script,
    and executes via subprocess. Exit code 0 = passed.

    Args:
        adapter_id: UUID of the adapter to test (None = baseline, no adapter).
            Currently informational; inference wiring happens at a higher level.
        subset_size: Ignored — always uses the fixed 20-task bundled subset.
        model: Base model name (informational only, not used for inference here).
        completions: Dict mapping task_id -> completion string. Only tasks with
            an entry in this dict are evaluated. If None or empty, returns empty
            results.

    Returns:
        Dictionary with benchmark results including:
            - "pass_count": int, number of tasks passed
            - "fail_count": int, number of tasks failed
            - "pass_rate": float, fraction of tasks passed (0.0 to 1.0)
            - "task_results": list of per-task result dicts with task_id, passed
            - "summary": str, human-readable summary

    Raises:
        NotImplementedError: If completions are not provided (inference not wired).

    Example:
        >>> completions = {"HumanEval/0": "    return []"}
        >>> results = run_humaneval_subset(adapter_id=None, completions=completions)
        >>> results["pass_count"]
        0
    """
    if completions is None:
        raise NotImplementedError("run_humaneval_subset is not yet implemented.")

    # Load bundled task data
    subset_path = _DATA_DIR / "humaneval_subset.json"
    with subset_path.open() as f:
        all_tasks: list[dict[str, str]] = json.load(f)

    # Build lookup by task_id
    task_map = {t["task_id"]: t for t in all_tasks}

    task_results: list[dict[str, Any]] = []

    with tempfile.TemporaryDirectory() as tmpdir:
        for task_id, completion in completions.items():
            task = task_map.get(task_id)
            if task is None:
                continue

            # Build executable script: prompt + completion + test + check(entry_point)
            script = (
                task["prompt"]
                + completion
                + "\n"
                + task["test"]
                + f"\ncheck({task['entry_point']})\n"
            )

            script_path = Path(tmpdir) / f"{task_id.replace('/', '_')}.py"
            script_path.write_text(script)

            passed = safe_subprocess_run(script_path, cwd=tmpdir)
            task_results.append({"task_id": task_id, "passed": passed})

    pass_count = sum(1 for r in task_results if r["passed"])
    fail_count = len(task_results) - pass_count
    total = len(task_results)
    pass_rate = pass_count / total if total > 0 else 0.0

    summary = (
        f"HumanEval subset: {pass_count}/{total} passed "
        f"(pass_rate={pass_rate:.2%}, adapter_id={adapter_id})"
    )
    print(summary)

    return {
        "pass_count": pass_count,
        "fail_count": fail_count,
        "pass_rate": pass_rate,
        "task_results": task_results,
        "summary": summary,
    }

run_kill_switch_gate

run_kill_switch_gate(
    baseline_pass1: float,
    adapter_pass1: float,
    threshold: float = 0.05,
) -> dict[str, object]

Compare baseline vs adapter Pass@1 scores and return a PASS/FAIL verdict.

Computes the relative improvement of the adapter over the baseline and returns PASS if the improvement meets the threshold, FAIL otherwise.

Parameters:

Name Type Description Default
baseline_pass1 float

Pass@1 score for the baseline model (no adapter).

required
adapter_pass1 float

Pass@1 score for the adapter model.

required
threshold float

Minimum required relative improvement (default 0.05 = 5%).

0.05

Returns:

Type Description
dict[str, object]

Dictionary with: - "baseline_pass1": float - "adapter_pass1": float - "relative_delta": float, relative improvement over baseline - "verdict": str, "PASS" or "FAIL"

Example

result = run_kill_switch_gate(0.50, 0.55) result["verdict"] 'PASS'

Source code in libs/evaluation/src/evaluation/metrics.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def run_kill_switch_gate(
    baseline_pass1: float,
    adapter_pass1: float,
    threshold: float = 0.05,
) -> dict[str, object]:
    """Compare baseline vs adapter Pass@1 scores and return a PASS/FAIL verdict.

    Computes the relative improvement of the adapter over the baseline and
    returns PASS if the improvement meets the threshold, FAIL otherwise.

    Args:
        baseline_pass1: Pass@1 score for the baseline model (no adapter).
        adapter_pass1: Pass@1 score for the adapter model.
        threshold: Minimum required relative improvement (default 0.05 = 5%).

    Returns:
        Dictionary with:
            - "baseline_pass1": float
            - "adapter_pass1": float
            - "relative_delta": float, relative improvement over baseline
            - "verdict": str, "PASS" or "FAIL"

    Example:
        >>> result = run_kill_switch_gate(0.50, 0.55)
        >>> result["verdict"]
        'PASS'
    """
    # 1e-9 prevents division-by-zero when baseline is 0.0
    relative_delta = (adapter_pass1 - baseline_pass1) / max(baseline_pass1, 1e-9)
    verdict = "PASS" if adapter_pass1 >= baseline_pass1 * (1 + threshold) else "FAIL"

    print(
        f"Kill-switch gate result: {verdict}\n"
        f"  Baseline  Pass@1: {baseline_pass1:.4f}\n"
        f"  Adapter   Pass@1: {adapter_pass1:.4f}\n"
        f"  Relative delta:   {relative_delta:+.2%} (threshold: {threshold:+.0%})"
    )

    return {
        "baseline_pass1": baseline_pass1,
        "adapter_pass1": adapter_pass1,
        "relative_delta": relative_delta,
        "verdict": verdict,
    }

score_adapter_quality

score_adapter_quality(
    adapter_id: str,
    pass_rate: float,
    generalization_delta: float | None = None,
) -> float

Compute an overall quality score for an adapter.

Aggregates the adapter's benchmark pass rate with its generalization performance (if available) into a single scalar quality score. When generalization data is absent, quality is derived from pass rate alone.

Parameters:

Name Type Description Default
adapter_id str

UUID of the adapter to score.

required
pass_rate float

Fraction of benchmark tasks passed, in range 0.0 to 1.0.

required
generalization_delta float | None

Optional difference between in-distribution and out-of-distribution (OOD) performance. Positive values indicate the adapter generalizes well; negative values indicate overfitting. Defaults to None (not measured).

None

Returns:

Type Description
float

Quality score as a float between 0.0 and 1.0. Higher values indicate

float

a better overall adapter quality.

Raises:

Type Description
NotImplementedError

score_adapter_quality is not yet implemented.

Example

score = score_adapter_quality("adapter-001", pass_rate=0.85) score 0.85 score_with_gen = score_adapter_quality( ... "adapter-001", 0.85, generalization_delta=0.1, ... ) score_with_gen > score True

Source code in libs/evaluation/src/evaluation/metrics.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def score_adapter_quality(
    adapter_id: str,
    pass_rate: float,
    generalization_delta: float | None = None,
) -> float:
    """Compute an overall quality score for an adapter.

    Aggregates the adapter's benchmark pass rate with its generalization
    performance (if available) into a single scalar quality score. When
    generalization data is absent, quality is derived from pass rate alone.

    Args:
        adapter_id: UUID of the adapter to score.
        pass_rate: Fraction of benchmark tasks passed, in range 0.0 to 1.0.
        generalization_delta: Optional difference between in-distribution and
            out-of-distribution (OOD) performance. Positive values indicate
            the adapter generalizes well; negative values indicate overfitting.
            Defaults to None (not measured).

    Returns:
        Quality score as a float between 0.0 and 1.0. Higher values indicate
        a better overall adapter quality.

    Raises:
        NotImplementedError: score_adapter_quality is not yet implemented.

    Example:
        >>> score = score_adapter_quality("adapter-001", pass_rate=0.85)
        >>> score
        0.85
        >>> score_with_gen = score_adapter_quality(
        ...     "adapter-001", 0.85, generalization_delta=0.1,
        ... )
        >>> score_with_gen > score
        True
    """
    if generalization_delta is not None:
        quality = min(pass_rate + 0.1 * max(generalization_delta, 0), 1.0)
    else:
        quality = pass_rate
    return quality

test_generalization

test_generalization(
    adapter_id: str,
    in_distribution_tasks: list[str] | None = None,
    ood_tasks: list[str] | None = None,
) -> dict[str, Any]

Test whether an adapter generalizes beyond its training distribution.

Evaluates the adapter on both in-distribution tasks (matching the training data distribution) and out-of-distribution (OOD) tasks to measure how well the adapter generalizes to novel problems.

Parameters:

Name Type Description Default
adapter_id str

UUID of the adapter to evaluate.

required
in_distribution_tasks list[str] | None

Optional list of task IDs matching the adapter's training distribution. If None, uses a default in-distribution set.

None
ood_tasks list[str] | None

Optional list of out-of-distribution task IDs to test generalization on. If None, uses a default OOD task set.

None

Returns:

Type Description
dict[str, Any]

Dictionary with generalization results including: - "in_distribution_score": float, performance on training-distribution tasks - "ood_score": float, performance on out-of-distribution tasks - "generalization_delta": float, difference (in_distribution - ood) - "generalizes": bool, True if generalization_delta is within threshold

Raises:

Type Description
NotImplementedError

test_generalization is not yet implemented.

Example

results = test_generalization("adapter-001") results["generalization_delta"] 0.05 results["generalizes"] True

Source code in libs/evaluation/src/evaluation/metrics.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def test_generalization(
    adapter_id: str,
    in_distribution_tasks: list[str] | None = None,
    ood_tasks: list[str] | None = None,
) -> dict[str, Any]:
    """Test whether an adapter generalizes beyond its training distribution.

    Evaluates the adapter on both in-distribution tasks (matching the training
    data distribution) and out-of-distribution (OOD) tasks to measure how well
    the adapter generalizes to novel problems.

    Args:
        adapter_id: UUID of the adapter to evaluate.
        in_distribution_tasks: Optional list of task IDs matching the adapter's
            training distribution. If None, uses a default in-distribution set.
        ood_tasks: Optional list of out-of-distribution task IDs to test
            generalization on. If None, uses a default OOD task set.

    Returns:
        Dictionary with generalization results including:
            - "in_distribution_score": float, performance on training-distribution tasks
            - "ood_score": float, performance on out-of-distribution tasks
            - "generalization_delta": float, difference (in_distribution - ood)
            - "generalizes": bool, True if generalization_delta is within threshold

    Raises:
        NotImplementedError: test_generalization is not yet implemented.

    Example:
        >>> results = test_generalization("adapter-001")
        >>> results["generalization_delta"]
        0.05
        >>> results["generalizes"]
        True
    """
    in_dist_score = 0.8  # Placeholder until live inference wired
    ood_score = 0.6
    gen_delta = in_dist_score - ood_score
    generalizes = abs(gen_delta) <= 0.2

    return {
        "adapter_id": adapter_id,
        "in_distribution_score": in_dist_score,
        "ood_score": ood_score,
        "generalization_delta": gen_delta,
        "generalizes": generalizes,
    }

compute_generalization_delta

compute_generalization_delta(
    in_dist_rate: float, ood_rate: float
) -> float

Compute the generalization delta between in-distribution and OOD performance.

A positive delta means the adapter does better on OOD tasks relative to in-distribution performance. A negative delta indicates overfitting.

Parameters:

Name Type Description Default
in_dist_rate float

Pass rate on in-distribution tasks (0.0 to 1.0).

required
ood_rate float

Pass rate on OOD tasks (0.0 to 1.0).

required

Returns:

Type Description
float

Generalization delta as ood_rate - in_dist_rate.

Source code in libs/evaluation/src/evaluation/ood_benchmark.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def compute_generalization_delta(
    in_dist_rate: float,
    ood_rate: float,
) -> float:
    """Compute the generalization delta between in-distribution and OOD performance.

    A positive delta means the adapter does better on OOD tasks relative to
    in-distribution performance. A negative delta indicates overfitting.

    Args:
        in_dist_rate: Pass rate on in-distribution tasks (0.0 to 1.0).
        ood_rate: Pass rate on OOD tasks (0.0 to 1.0).

    Returns:
        Generalization delta as ood_rate - in_dist_rate.
    """
    return ood_rate - in_dist_rate

run_ood_benchmark

run_ood_benchmark(
    adapter_id: str | None,
    completions: dict[str, str],
    benchmark_name: str = "ood_python",
) -> dict[str, Any]

Run an out-of-distribution benchmark on provided completions.

Evaluates completions against OOD tasks from the bundled task set. Each task's prompt + completion is executed in a subprocess with its test harness.

Parameters:

Name Type Description Default
adapter_id str | None

UUID of the adapter being tested (informational).

required
completions dict[str, str]

Dict mapping task_id to completion string.

required
benchmark_name str

Name of the OOD benchmark set.

'ood_python'

Returns:

Type Description
dict[str, Any]

Dictionary with ood_pass_rate and per-task results.

Source code in libs/evaluation/src/evaluation/ood_benchmark.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def run_ood_benchmark(
    adapter_id: str | None,
    completions: dict[str, str],
    benchmark_name: str = "ood_python",
) -> dict[str, Any]:
    """Run an out-of-distribution benchmark on provided completions.

    Evaluates completions against OOD tasks from the bundled task set.
    Each task's prompt + completion is executed in a subprocess with its
    test harness.

    Args:
        adapter_id: UUID of the adapter being tested (informational).
        completions: Dict mapping task_id to completion string.
        benchmark_name: Name of the OOD benchmark set.

    Returns:
        Dictionary with ood_pass_rate and per-task results.
    """
    ood_path = _OOD_DATA_DIR / "ood_tasks.json"
    with ood_path.open() as f:
        all_tasks: list[dict[str, str]] = json.load(f)

    task_map = {t["task_id"]: t for t in all_tasks}
    task_results: list[dict[str, Any]] = []

    with tempfile.TemporaryDirectory() as tmpdir:
        for task_id, completion in completions.items():
            task = task_map.get(task_id)
            if task is None:
                continue

            script = task["prompt"] + completion + "\n" + task["test"] + "\n"
            script_path = Path(tmpdir) / f"{task_id.replace('/', '_')}.py"
            script_path.write_text(script)

            passed = safe_subprocess_run(script_path, cwd=tmpdir)

            task_results.append({"task_id": task_id, "passed": passed})

    total = len(task_results)
    pass_count = sum(1 for r in task_results if r["passed"])
    ood_pass_rate = pass_count / total if total > 0 else 0.0

    return {
        "adapter_id": adapter_id,
        "benchmark_name": benchmark_name,
        "ood_pass_rate": ood_pass_rate,
        "pass_count": pass_count,
        "total": total,
        "task_results": task_results,
    }

Modules

benchmarks

Unified benchmark harness for Pass@1 evaluation.

Public API re-exported for convenience:

from evaluation.benchmarks import (
    Problem,
    PassVerdict,
    BenchmarkAdapter,
    BenchmarkConfig,
    BenchmarkResult,
    run_benchmark,
    load_adapter_stack,
    load_problems,
)
Classes
BenchmarkAdapter

Bases: Protocol

Protocol that every benchmark adapter must satisfy.

Implementations are stateless loaders + scorers. Each adapter is responsible for exactly one benchmark (HumanEval, MBPP, etc.).

Implementors

HumanEvalAdapter, MBPPAdapter, APPSAdapter, BigCodeBenchAdapter, DS1000Adapter, LiveCodeBenchAdapter, SWEBenchLiteAdapter, CodeContestsAdapter

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load benchmark problems, optionally capped and seeded.

Parameters:

Name Type Description Default
max_samples int | None

Maximum number of problems to return. None means return all available problems.

None
seed int

Random seed for subsampling when max_samples < total.

42

Returns:

Type Description
list[Problem]

List of Problem instances ready for scoring.

Source code in libs/evaluation/src/evaluation/benchmarks/protocol.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load benchmark problems, optionally capped and seeded.

    Args:
        max_samples: Maximum number of problems to return.
            None means return all available problems.
        seed: Random seed for subsampling when max_samples < total.

    Returns:
        List of Problem instances ready for scoring.
    """
    ...
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a single model generation against the problem's tests.

Parameters:

Name Type Description Default
problem Problem

The Problem instance (from load_problems).

required
generation str

Raw text generated by the model. This is the model's completion of problem.prompt.

required
timeout_s int

Sandbox timeout in seconds.

30

Returns:

Type Description
PassVerdict

A PassVerdict indicating pass/fail and any error output.

Source code in libs/evaluation/src/evaluation/benchmarks/protocol.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def score(
    self, problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict:
    """Score a single model generation against the problem's tests.

    Args:
        problem: The Problem instance (from load_problems).
        generation: Raw text generated by the model. This is the
            model's completion of problem.prompt.
        timeout_s: Sandbox timeout in seconds.

    Returns:
        A PassVerdict indicating pass/fail and any error output.
    """
    ...
BenchmarkConfig dataclass
BenchmarkConfig(
    timeout_s: int = 30,
    max_workers: int = 4,
    max_samples: int | None = None,
    seed: int = 42,
)

Runtime configuration for a benchmark run.

Attributes:

Name Type Description
timeout_s int

Per-problem execution timeout in seconds. Default 30.

max_workers int

ThreadPoolExecutor worker count. Default 4.

max_samples int | None

Cap on problems loaded. None means load all.

seed int

Random seed for subsampling (APPS stratified sampler). Default 42.

BenchmarkResult dataclass
BenchmarkResult(
    benchmark_id: str, verdicts: list[PassVerdict]
)

Aggregated result of a full benchmark run.

Attributes:

Name Type Description
benchmark_id str

Identifier of the benchmark (e.g. "humaneval").

verdicts list[PassVerdict]

Per-problem PassVerdict list.

Attributes
n_problems property
n_problems: int

Total number of problems evaluated.

n_passed property
n_passed: int

Number of problems where passed=True.

pass_at_1 property
pass_at_1: float

Pass@1 as a fraction in [0.0, 1.0].

Returns 0.0 when there are no verdicts.

PassVerdict dataclass
PassVerdict(
    problem_id: str,
    passed: bool,
    generation: str,
    error: str | None,
    timed_out: bool,
)

Verdict for a single problem evaluation.

Attributes:

Name Type Description
problem_id str

Matches the Problem.problem_id that was evaluated.

passed bool

True if the generation passed all tests.

generation str

The raw text generated by the model.

error str | None

Error message from the sandbox, or None if passed.

timed_out bool

True if the sandbox terminated the process for timeout.

Problem dataclass
Problem(
    problem_id: str,
    prompt: str,
    test_code: str,
    entry_point: str | None = None,
    metadata: dict[str, Any] = dict(),
)

A single benchmark problem to be solved by the model.

Attributes:

Name Type Description
problem_id str

Unique identifier (e.g. "HumanEval/0", "mbpp/1").

prompt str

The code prompt / problem description shown to the model.

test_code str

Python code that asserts correctness of a solution. This is appended to the model's generation and executed.

entry_point str | None

Optional function name the model must define. Used by HumanEval-style benchmarks to construct the test harness.

metadata dict[str, Any]

Arbitrary extra fields (difficulty, source, etc.).

Functions
load_problems
load_problems(
    benchmark_id: str,
    problem_ids: list[str] | None = None,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]

Load problems for a benchmark via its registered adapter.

For APPS, passing max_samples triggers the adapter's stratified-random sampler by difficulty (identical to what run_benchmark would do — the caller gets Plan A's APPSAdapter._stratified_sample output, not a separate code path). This is the APPS stratification parity point between Plan A and Plan C.

Parameters:

Name Type Description Default
benchmark_id str

One of the registered benchmark IDs: humaneval, mbpp, apps, bigcodebench, ds_1000, livecodebench, swe_bench_lite, codecontests.

required
problem_ids list[str] | None

Optional list of explicit problem ids to keep. When provided, the adapter's own sampling is bypassed and only matching ids are returned.

None
max_samples int | None

Adapter-level cap. For APPS this drives stratified sampling; for other adapters it is a simple head-cap.

None
seed int

Sampling seed (APPS uses this for stratification).

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Raises:

Type Description
ValueError

If benchmark_id is not in the runner's registry.

Source code in libs/evaluation/src/evaluation/benchmarks/__init__.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def load_problems(
    benchmark_id: str,
    problem_ids: list[str] | None = None,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load problems for a benchmark via its registered adapter.

    For APPS, passing ``max_samples`` triggers the adapter's stratified-random
    sampler by difficulty (identical to what ``run_benchmark`` would do — the
    caller gets Plan A's APPSAdapter._stratified_sample output, not a separate
    code path). This is the APPS stratification parity point between Plan A
    and Plan C.

    Args:
        benchmark_id: One of the registered benchmark IDs:
            humaneval, mbpp, apps, bigcodebench, ds_1000, livecodebench,
            swe_bench_lite, codecontests.
        problem_ids: Optional list of explicit problem ids to keep. When
            provided, the adapter's own sampling is bypassed and only matching
            ids are returned.
        max_samples: Adapter-level cap. For APPS this drives stratified
            sampling; for other adapters it is a simple head-cap.
        seed: Sampling seed (APPS uses this for stratification).

    Returns:
        List of Problem instances.

    Raises:
        ValueError: If benchmark_id is not in the runner's registry.
    """
    from evaluation.benchmarks.runner import (  # noqa: PLC0415
        _ADAPTER_REGISTRY,
        _import_adapter,
    )

    if benchmark_id not in _ADAPTER_REGISTRY:
        raise ValueError(
            f"Unknown benchmark_id {benchmark_id!r}. "
            f"Known benchmarks: {sorted(_ADAPTER_REGISTRY)}"
        )

    adapter = _import_adapter(_ADAPTER_REGISTRY[benchmark_id])
    problems: list[Problem] = adapter.load_problems(max_samples=max_samples, seed=seed)

    if problem_ids is not None:
        id_set = set(problem_ids)
        problems = [p for p in problems if p.problem_id in id_set]

    return problems
Modules
adapter_stack

Adapter stack loader for benchmark evaluation.

Resolves a list of adapter_ids from AdapterRegistry into file paths, and bundles them with an InferenceProvider into an AdapterStack that the benchmark runner uses to generate completions.

No GPU imports. CPU-safe.

Classes
AdapterStack dataclass
AdapterStack(
    base_model: str,
    adapter_ids: list[str],
    adapter_paths: dict[str, str],
    provider: InferenceProvider,
)

Bundle of base model + ordered adapter stack + provider.

Attributes:

Name Type Description
base_model str

HuggingFace model ID or local path for the base model.

adapter_ids list[str]

Ordered list of adapter IDs to apply (first = innermost).

adapter_paths dict[str, str]

Dict mapping adapter_id -> filesystem path.

provider InferenceProvider

InferenceProvider used to generate completions.

Functions
describe
describe() -> dict[str, Any]

Return a JSON-serialisable summary of this stack.

Returns:

Type Description
dict[str, Any]

Dict with keys: base_model, adapter_ids, adapter_paths.

Source code in libs/evaluation/src/evaluation/benchmarks/adapter_stack.py
41
42
43
44
45
46
47
48
49
50
51
def describe(self) -> dict[str, Any]:
    """Return a JSON-serialisable summary of this stack.

    Returns:
        Dict with keys: base_model, adapter_ids, adapter_paths.
    """
    return {
        "base_model": self.base_model,
        "adapter_ids": list(self.adapter_ids),
        "adapter_paths": dict(self.adapter_paths),
    }
Functions
load_adapter_stack
load_adapter_stack(
    base_model: str,
    adapter_ids: list[str],
    provider: InferenceProvider,
    registry: Any,
) -> AdapterStack

Resolve adapter IDs to file paths and construct an AdapterStack.

Queries the AdapterRegistry for each adapter_id to retrieve its file_path. Raises ValueError for any unknown adapter_id.

Parameters:

Name Type Description Default
base_model str

HuggingFace model ID or local path for the base model.

required
adapter_ids list[str]

Ordered list of adapter registry IDs to load. Pass an empty list to use the base model only.

required
provider InferenceProvider

InferenceProvider instance for generating completions.

required
registry Any

AdapterRegistry instance (or compatible duck-type) with a retrieve_by_id(adapter_id: str) -> AdapterRecord method.

required

Returns:

Type Description
AdapterStack

AdapterStack with resolved file paths.

Raises:

Type Description
ValueError

If any adapter_id is not found in the registry.

Example

from sqlalchemy import create_engine from adapter_registry.registry import AdapterRegistry engine = create_engine("sqlite:///adapters.db") reg = AdapterRegistry(engine=engine) stack = load_adapter_stack("Qwen/Qwen3.5-9B", ["a1"], provider, reg)

Source code in libs/evaluation/src/evaluation/benchmarks/adapter_stack.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def load_adapter_stack(
    base_model: str,
    adapter_ids: list[str],
    provider: InferenceProvider,
    registry: Any,
) -> AdapterStack:
    """Resolve adapter IDs to file paths and construct an AdapterStack.

    Queries the AdapterRegistry for each adapter_id to retrieve its
    file_path. Raises ValueError for any unknown adapter_id.

    Args:
        base_model: HuggingFace model ID or local path for the base model.
        adapter_ids: Ordered list of adapter registry IDs to load.
            Pass an empty list to use the base model only.
        provider: InferenceProvider instance for generating completions.
        registry: AdapterRegistry instance (or compatible duck-type) with
            a retrieve_by_id(adapter_id: str) -> AdapterRecord method.

    Returns:
        AdapterStack with resolved file paths.

    Raises:
        ValueError: If any adapter_id is not found in the registry.

    Example:
        >>> from sqlalchemy import create_engine
        >>> from adapter_registry.registry import AdapterRegistry
        >>> engine = create_engine("sqlite:///adapters.db")
        >>> reg = AdapterRegistry(engine=engine)
        >>> stack = load_adapter_stack("Qwen/Qwen3.5-9B", ["a1"], provider, reg)
    """
    adapter_paths: dict[str, str] = {}
    for aid in adapter_ids:
        try:
            record = registry.retrieve_by_id(aid)
            adapter_paths[aid] = str(record.file_path)
        except Exception as exc:
            raise ValueError(f"Adapter '{aid}' not found in registry: {exc}") from exc

    return AdapterStack(
        base_model=base_model,
        adapter_ids=list(adapter_ids),
        adapter_paths=adapter_paths,
        provider=provider,
    )
aggregator

Pass@1 aggregation from a list of PassVerdict instances.

Pure function; no I/O, no GPU dependencies. Suitable for direct import in CPU-only environments and in test fixtures.

Classes Functions
pass_at_1_from_verdicts
pass_at_1_from_verdicts(
    verdicts: list[PassVerdict],
) -> float

Compute Pass@1 from a list of per-problem verdicts.

Pass@1 is the fraction of problems where the model's single generation passed all tests. Timed-out problems count as failures.

Parameters:

Name Type Description Default
verdicts list[PassVerdict]

List of PassVerdict instances. May be empty.

required

Returns:

Type Description
float

Float in [0.0, 1.0]. Returns 0.0 for an empty list.

Example

v = [PassVerdict("p1", True, "", None, False), ... PassVerdict("p2", False, "", "err", False)] pass_at_1_from_verdicts(v) 0.5

Source code in libs/evaluation/src/evaluation/benchmarks/aggregator.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def pass_at_1_from_verdicts(verdicts: list[PassVerdict]) -> float:
    """Compute Pass@1 from a list of per-problem verdicts.

    Pass@1 is the fraction of problems where the model's single generation
    passed all tests. Timed-out problems count as failures.

    Args:
        verdicts: List of PassVerdict instances. May be empty.

    Returns:
        Float in [0.0, 1.0]. Returns 0.0 for an empty list.

    Example:
        >>> v = [PassVerdict("p1", True, "", None, False),
        ...      PassVerdict("p2", False, "", "err", False)]
        >>> pass_at_1_from_verdicts(v)
        0.5
    """
    if not verdicts:
        return 0.0
    n_passed = sum(1 for v in verdicts if v.passed)
    return n_passed / len(verdicts)
apps

APPS benchmark adapter.

Loads from codeparrot/apps (all config). Applies stratified-random subsampling by difficulty when max_samples is set. Seed=42 by default. Max cap: 5000 problems.

Note: The APPS dataset uses a legacy loading script incompatible with current datasets>=2.x. Offline mode (parquet fixture) is the default path for CI. Online mode falls back gracefully if the dataset loads.

Classes
APPSAdapter

Benchmark adapter for the APPS dataset.

Applies stratified-random subsampling by difficulty level. Hard max cap: 5000 problems.

Attributes:

Name Type Description
benchmark_id str

"apps".

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load APPS problems with stratified subsampling by difficulty.

Parameters:

Name Type Description Default
max_samples int | None

Cap applied after stratified sampling. Hard-capped at 5000 regardless.

None
seed int

Random seed for reproducibility.

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Source code in libs/evaluation/src/evaluation/benchmarks/apps.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load APPS problems with stratified subsampling by difficulty.

    Args:
        max_samples: Cap applied after stratified sampling.
            Hard-capped at 5000 regardless.
        seed: Random seed for reproducibility.

    Returns:
        List of Problem instances.
    """
    rows = self._load_rows()
    cap = min(max_samples or _APPS_MAX_SAMPLES, _APPS_MAX_SAMPLES)
    if cap < len(rows):
        rows = self._stratified_sample(rows, cap, seed)
    return [self._row_to_problem(r) for r in rows]
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a generation against APPS input/output test cases.

APPS provides input_output JSON with "inputs" and "outputs" lists. Runs the generation for each input via stdin and compares stdout.

Note: Strict I/O equality is used; multi-valid-output problems may be undercounted (APPS open question #3 from plan).

Parameters:

Name Type Description Default
problem Problem

Problem instance.

required
generation str

Model's complete Python program.

required
timeout_s int

Per-test-case timeout.

30

Returns:

Type Description
PassVerdict

PassVerdict — passed only if all test cases produce correct output.

Source code in libs/evaluation/src/evaluation/benchmarks/apps.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def score(
    self,
    problem: Problem,
    generation: str,
    timeout_s: int = 30,
) -> PassVerdict:
    """Score a generation against APPS input/output test cases.

    APPS provides input_output JSON with "inputs" and "outputs" lists.
    Runs the generation for each input via stdin and compares stdout.

    Note: Strict I/O equality is used; multi-valid-output problems may
    be undercounted (APPS open question #3 from plan).

    Args:
        problem: Problem instance.
        generation: Model's complete Python program.
        timeout_s: Per-test-case timeout.

    Returns:
        PassVerdict — passed only if all test cases produce correct output.
    """
    from shared.sandbox import SubprocessBackend  # deferred: INFRA-05

    backend = SubprocessBackend()
    io_data_raw = problem.metadata.get("input_output", "")
    try:
        io_data = json.loads(io_data_raw) if io_data_raw else {}
    except (json.JSONDecodeError, TypeError):
        io_data = {}

    inputs: list[str] = io_data.get("inputs", [])
    outputs: list[str] = io_data.get("outputs", [])

    if not inputs:
        return PassVerdict(
            problem_id=problem.problem_id,
            passed=False,
            generation=generation,
            error="No test cases found in problem metadata",
            timed_out=False,
        )

    for inp, expected_out in zip(inputs, outputs):
        harness = (
            f"import sys\nfrom io import StringIO\n"
            f"sys.stdin = StringIO({inp!r})\n"
            f"{generation}\n"
        )
        result = backend.run(harness, timeout=timeout_s)
        if result.is_timed_out:
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=f"Timed out on input: {inp!r}",
                timed_out=True,
            )
        if result.exit_code != 0:
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=result.stderr or result.stdout,
                timed_out=False,
            )
        actual = result.stdout.strip()
        if actual != str(expected_out).strip():
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=f"Expected {expected_out!r}, got {actual!r}",
                timed_out=False,
            )

    return PassVerdict(
        problem_id=problem.problem_id,
        passed=True,
        generation=generation,
        error=None,
        timed_out=False,
    )
bigcodebench

BigCodeBench benchmark adapter.

Loads from bigcode/bigcodebench (v0.1.2 split, default config). Each problem has a complete_prompt and a test field with unittest assertions.

HF dataset: bigcode/bigcodebench Split: v0.1.2 (verified: splits are v0.1.0_hf, v0.1.1, v0.1.2, v0.1.3, v0.1.4) Config: default (no config argument needed)

Classes
BigCodeBenchAdapter

Benchmark adapter for BigCodeBench.

Attributes:

Name Type Description
benchmark_id str

"bigcodebench".

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load BigCodeBench problems.

Parameters:

Name Type Description Default
max_samples int | None

Cap on returned problems.

None
seed int

Subsampling seed.

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Source code in libs/evaluation/src/evaluation/benchmarks/bigcodebench.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load BigCodeBench problems.

    Args:
        max_samples: Cap on returned problems.
        seed: Subsampling seed.

    Returns:
        List of Problem instances.
    """
    rows = self._load_rows()
    if max_samples is not None and max_samples < len(rows):
        rng = random.Random(seed)
        rows = rng.sample(rows, max_samples)
    return [self._row_to_problem(r) for r in rows]
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a generation against BigCodeBench test assertions.

Parameters:

Name Type Description Default
problem Problem

Problem instance.

required
generation str

Model's completion of the prompt.

required
timeout_s int

Sandbox timeout.

30

Returns:

Type Description
PassVerdict

PassVerdict.

Source code in libs/evaluation/src/evaluation/benchmarks/bigcodebench.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def score(
    self,
    problem: Problem,
    generation: str,
    timeout_s: int = 30,
) -> PassVerdict:
    """Score a generation against BigCodeBench test assertions.

    Args:
        problem: Problem instance.
        generation: Model's completion of the prompt.
        timeout_s: Sandbox timeout.

    Returns:
        PassVerdict.
    """
    from shared.sandbox import SubprocessBackend  # deferred: INFRA-05

    code = f"{problem.prompt}\n{generation}\n\n{problem.test_code}\n"
    backend = SubprocessBackend()
    result = backend.run(code, timeout=timeout_s)
    passed = result.exit_code == 0 and not result.is_timed_out
    return PassVerdict(
        problem_id=problem.problem_id,
        passed=passed,
        generation=generation,
        error=(result.stderr or result.stdout or None) if not passed else None,
        timed_out=result.is_timed_out,
    )
codecontests

CodeContests benchmark adapter (held-out generalization set).

Loads from deepmind/code_contests. Uses public_tests and private_tests input/output pairs for scoring. Held-out from training; used only for generalization evaluation.

HF dataset: deepmind/code_contests Config: default Split: test

Classes
CodeContestsAdapter

Benchmark adapter for DeepMind CodeContests (held-out generalization set).

Attributes:

Name Type Description
benchmark_id str

"codecontests".

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load CodeContests problems.

Parameters:

Name Type Description Default
max_samples int | None

Cap on returned problems.

None
seed int

Subsampling seed.

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Source code in libs/evaluation/src/evaluation/benchmarks/codecontests.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load CodeContests problems.

    Args:
        max_samples: Cap on returned problems.
        seed: Subsampling seed.

    Returns:
        List of Problem instances.
    """
    rows = self._load_rows()
    if max_samples is not None and max_samples < len(rows):
        rng = random.Random(seed)
        rows = rng.sample(rows, max_samples)
    return [self._row_to_problem(r) for r in rows]
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a generation against CodeContests public + private test cases.

Runs the generation as a complete Python program, feeding each test input via stdin and comparing stdout to expected output.

Parameters:

Name Type Description Default
problem Problem

Problem instance.

required
generation str

Model's complete Python solution.

required
timeout_s int

Per-test-case timeout.

30

Returns:

Type Description
PassVerdict

PassVerdict — passed only if all test cases pass.

Source code in libs/evaluation/src/evaluation/benchmarks/codecontests.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def score(
    self,
    problem: Problem,
    generation: str,
    timeout_s: int = 30,
) -> PassVerdict:
    """Score a generation against CodeContests public + private test cases.

    Runs the generation as a complete Python program, feeding each
    test input via stdin and comparing stdout to expected output.

    Args:
        problem: Problem instance.
        generation: Model's complete Python solution.
        timeout_s: Per-test-case timeout.

    Returns:
        PassVerdict — passed only if all test cases pass.
    """
    from shared.sandbox import SubprocessBackend  # deferred: INFRA-05

    backend = SubprocessBackend()
    all_pairs: list[tuple[str, str]] = []

    for key in ("public_tests", "private_tests"):
        raw = problem.metadata.get(key, [])
        if isinstance(raw, str):
            try:
                raw = json.loads(raw)
            except (json.JSONDecodeError, ValueError):
                raw = []
        all_pairs.extend(_extract_io_pairs(raw))

    if not all_pairs:
        return PassVerdict(
            problem_id=problem.problem_id,
            passed=False,
            generation=generation,
            error="No test cases found",
            timed_out=False,
        )

    for inp, expected in all_pairs:
        harness = (
            f"import sys\nfrom io import StringIO\n"
            f"sys.stdin = StringIO({inp!r})\n"
            f"{generation}\n"
        )
        result = backend.run(harness, timeout=timeout_s)
        if result.is_timed_out:
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=f"Timed out on input: {inp!r}",
                timed_out=True,
            )
        if result.exit_code != 0 or result.stdout.strip() != expected.strip():
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=(
                    result.stderr or f"Wrong answer: got {result.stdout.strip()!r}"
                ),
                timed_out=False,
            )

    return PassVerdict(
        problem_id=problem.problem_id,
        passed=True,
        generation=generation,
        error=None,
        timed_out=False,
    )
ds1000

DS-1000 benchmark adapter.

Loads from xlangai/DS-1000. Each problem has a prompt and a reference_code solution; test harness uses code_context with exec(). The metadata.library column indicates which data-science library is tested.

HF dataset: xlangai/DS-1000 Config: default Split: test

Classes
DS1000Adapter

Benchmark adapter for DS-1000.

Attributes:

Name Type Description
benchmark_id str

"ds_1000".

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load DS-1000 problems.

Parameters:

Name Type Description Default
max_samples int | None

Cap on returned problems.

None
seed int

Subsampling seed.

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Source code in libs/evaluation/src/evaluation/benchmarks/ds1000.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load DS-1000 problems.

    Args:
        max_samples: Cap on returned problems.
        seed: Subsampling seed.

    Returns:
        List of Problem instances.
    """
    rows = self._load_rows()
    if max_samples is not None and max_samples < len(rows):
        rng = random.Random(seed)
        rows = rng.sample(rows, max_samples)
    return [self._row_to_problem(r) for r in rows]
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a generation against DS-1000 test code.

DS-1000 uses an exec-based harness via code_context. We run: {generation}

Parameters:

Name Type Description Default
problem Problem

Problem instance.

required
generation str

Model completion.

required
timeout_s int

Sandbox timeout.

30

Returns:

Type Description
PassVerdict

PassVerdict.

Source code in libs/evaluation/src/evaluation/benchmarks/ds1000.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def score(
    self,
    problem: Problem,
    generation: str,
    timeout_s: int = 30,
) -> PassVerdict:
    """Score a generation against DS-1000 test code.

    DS-1000 uses an exec-based harness via code_context. We run:
        {generation}
        {test_code}

    Args:
        problem: Problem instance.
        generation: Model completion.
        timeout_s: Sandbox timeout.

    Returns:
        PassVerdict.
    """
    from shared.sandbox import SubprocessBackend  # deferred: INFRA-05

    code = f"{generation}\n\n{problem.test_code}\n"
    backend = SubprocessBackend()
    result = backend.run(code, timeout=timeout_s)
    passed = result.exit_code == 0 and not result.is_timed_out
    return PassVerdict(
        problem_id=problem.problem_id,
        passed=passed,
        generation=generation,
        error=(result.stderr or result.stdout or None) if not passed else None,
        timed_out=result.is_timed_out,
    )
humaneval

HumanEval benchmark adapter.

Loads problems from openai/openai_humaneval via HuggingFace datasets. Falls back to a local parquet fixture when HF_DATASETS_OFFLINE=1.

Scoring: concatenate prompt + generation + test_code and execute via SubprocessBackend. HumanEval test harnesses use assert statements and a check(candidate) call pattern.

Classes
HumanEvalAdapter

Benchmark adapter for the OpenAI HumanEval dataset.

Attributes:

Name Type Description
benchmark_id str

Identifier string "humaneval".

_fixture_path Path

Path to the local parquet fixture used in offline mode.

Example

adapter = HumanEvalAdapter() problems = adapter.load_problems(max_samples=10) verdict = adapter.score(problems[0], " return sorted(lst)")

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load HumanEval problems from HF or local fixture.

Parameters:

Name Type Description Default
max_samples int | None

Cap on problems returned. None returns all 164.

None
seed int

Random seed for subsampling when max_samples < total.

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Source code in libs/evaluation/src/evaluation/benchmarks/humaneval.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load HumanEval problems from HF or local fixture.

    Args:
        max_samples: Cap on problems returned. None returns all 164.
        seed: Random seed for subsampling when max_samples < total.

    Returns:
        List of Problem instances.
    """
    rows = self._load_rows()
    if max_samples is not None and max_samples < len(rows):
        rng = random.Random(seed)
        rows = rng.sample(rows, max_samples)
    return [self._row_to_problem(r) for r in rows]
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a generation against HumanEval test harness.

Constructs: {prompt}\n{generation}\n\n{test_code}\ncheck({entry_point}) and executes via SubprocessBackend.

Parameters:

Name Type Description Default
problem Problem

Problem instance from load_problems().

required
generation str

Model completion (body of the function).

required
timeout_s int

Sandbox timeout in seconds.

30

Returns:

Type Description
PassVerdict

PassVerdict with passed=True iff exit_code==0 and not timed_out.

Source code in libs/evaluation/src/evaluation/benchmarks/humaneval.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def score(
    self,
    problem: Problem,
    generation: str,
    timeout_s: int = 30,
) -> PassVerdict:
    r"""Score a generation against HumanEval test harness.

    Constructs: ``{prompt}\n{generation}\n\n{test_code}\ncheck({entry_point})``
    and executes via SubprocessBackend.

    Args:
        problem: Problem instance from load_problems().
        generation: Model completion (body of the function).
        timeout_s: Sandbox timeout in seconds.

    Returns:
        PassVerdict with passed=True iff exit_code==0 and not timed_out.
    """
    from shared.sandbox import SubprocessBackend  # deferred: INFRA-05

    entry = problem.entry_point or ""
    code = (
        f"{problem.prompt}\n{generation}\n\n{problem.test_code}\ncheck({entry})\n"
    )
    backend = SubprocessBackend()
    result = backend.run(code, timeout=timeout_s)
    passed = result.exit_code == 0 and not result.is_timed_out
    error: str | None = None
    if not passed:
        error = result.stderr or result.stdout or "unknown error"
    return PassVerdict(
        problem_id=problem.problem_id,
        passed=passed,
        generation=generation,
        error=error,
        timed_out=result.is_timed_out,
    )
livecodebench

LiveCodeBench benchmark adapter.

Loads from livecodebench/code_generation_lite, pinned to release_v4 split. Test harness uses the public_tests field (input/output pairs).

HF dataset: livecodebench/code_generation_lite Note: This dataset uses a legacy loading script. The fixture-based offline path is the primary CI path. Online loading may fail with current datasets>=2.x.

Classes
LiveCodeBenchAdapter

Benchmark adapter for LiveCodeBench (release_v4).

Attributes:

Name Type Description
benchmark_id str

"livecodebench".

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load LiveCodeBench problems from release_v4.

Parameters:

Name Type Description Default
max_samples int | None

Cap on returned problems.

None
seed int

Subsampling seed.

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Source code in libs/evaluation/src/evaluation/benchmarks/livecodebench.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load LiveCodeBench problems from release_v4.

    Args:
        max_samples: Cap on returned problems.
        seed: Subsampling seed.

    Returns:
        List of Problem instances.
    """
    rows = self._load_rows()
    if max_samples is not None and max_samples < len(rows):
        rng = random.Random(seed)
        rows = rng.sample(rows, max_samples)
    return [self._row_to_problem(r) for r in rows]
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a generation using LiveCodeBench public test cases.

Runs the generation as a complete Python program, feeding each public_test input via stdin and comparing stdout to expected output.

Parameters:

Name Type Description Default
problem Problem

Problem instance.

required
generation str

Model's complete Python solution.

required
timeout_s int

Per-test-case timeout.

30

Returns:

Type Description
PassVerdict

PassVerdict.

Source code in libs/evaluation/src/evaluation/benchmarks/livecodebench.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def score(
    self,
    problem: Problem,
    generation: str,
    timeout_s: int = 30,
) -> PassVerdict:
    """Score a generation using LiveCodeBench public test cases.

    Runs the generation as a complete Python program, feeding each
    public_test input via stdin and comparing stdout to expected output.

    Args:
        problem: Problem instance.
        generation: Model's complete Python solution.
        timeout_s: Per-test-case timeout.

    Returns:
        PassVerdict.
    """
    from shared.sandbox import SubprocessBackend  # deferred: INFRA-05

    backend = SubprocessBackend()
    public_tests_raw = problem.metadata.get("public_tests", "[]")
    try:
        public_tests: list[dict[str, str]] = (
            json.loads(public_tests_raw)
            if isinstance(public_tests_raw, str)
            else list(public_tests_raw)
        )
    except (json.JSONDecodeError, TypeError):
        public_tests = []

    if not public_tests:
        return PassVerdict(
            problem_id=problem.problem_id,
            passed=False,
            generation=generation,
            error="No public test cases available",
            timed_out=False,
        )

    for tc in public_tests:
        inp = str(tc.get("input", ""))
        expected = str(tc.get("output", "")).strip()
        harness = (
            f"import sys\nfrom io import StringIO\n"
            f"sys.stdin = StringIO({inp!r})\n"
            f"{generation}\n"
        )
        result = backend.run(harness, timeout=timeout_s)
        if result.is_timed_out:
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=f"Timed out on input: {inp!r}",
                timed_out=True,
            )
        if result.exit_code != 0 or result.stdout.strip() != expected:
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=(
                    result.stderr or f"Wrong answer: got {result.stdout.strip()!r}"
                ),
                timed_out=False,
            )

    return PassVerdict(
        problem_id=problem.problem_id,
        passed=True,
        generation=generation,
        error=None,
        timed_out=False,
    )
mbpp

MBPP benchmark adapter.

Loads from google-research-datasets/mbpp (full config, train split). MBPP test_list field contains assert statements; we join and execute them.

Classes
MBPPAdapter

Benchmark adapter for the MBPP dataset.

Attributes:

Name Type Description
benchmark_id str

"mbpp".

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load MBPP problems.

Parameters:

Name Type Description Default
max_samples int | None

Cap on returned problems.

None
seed int

Subsampling seed.

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Source code in libs/evaluation/src/evaluation/benchmarks/mbpp.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load MBPP problems.

    Args:
        max_samples: Cap on returned problems.
        seed: Subsampling seed.

    Returns:
        List of Problem instances.
    """
    rows = self._load_rows()
    if max_samples is not None and max_samples < len(rows):
        rng = random.Random(seed)
        rows = rng.sample(rows, max_samples)
    return [self._row_to_problem(r) for r in rows]
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a generation against MBPP test assertions.

Parameters:

Name Type Description Default
problem Problem

Problem instance from load_problems().

required
generation str

Model completion (function body or full function).

required
timeout_s int

Sandbox timeout in seconds.

30

Returns:

Type Description
PassVerdict

PassVerdict.

Source code in libs/evaluation/src/evaluation/benchmarks/mbpp.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def score(
    self,
    problem: Problem,
    generation: str,
    timeout_s: int = 30,
) -> PassVerdict:
    """Score a generation against MBPP test assertions.

    Args:
        problem: Problem instance from load_problems().
        generation: Model completion (function body or full function).
        timeout_s: Sandbox timeout in seconds.

    Returns:
        PassVerdict.
    """
    from shared.sandbox import SubprocessBackend  # deferred: INFRA-05

    # MBPP prompt is a natural-language description, not Python —
    # only generation + assertions are executed.
    code = f"{generation}\n\n{problem.test_code}\n"
    backend = SubprocessBackend()
    result = backend.run(code, timeout=timeout_s)
    passed = result.exit_code == 0 and not result.is_timed_out
    return PassVerdict(
        problem_id=problem.problem_id,
        passed=passed,
        generation=generation,
        error=(result.stderr or result.stdout or None) if not passed else None,
        timed_out=result.is_timed_out,
    )
protocol

Protocol types for the benchmark harness.

Defines Problem, PassVerdict, BenchmarkAdapter (runtime-checkable protocol), BenchmarkConfig, and BenchmarkResult. All are dataclasses or frozen dataclasses to prevent accidental mutation during concurrent evaluation.

No GPU imports. CPU-safe.

Classes
Problem dataclass
Problem(
    problem_id: str,
    prompt: str,
    test_code: str,
    entry_point: str | None = None,
    metadata: dict[str, Any] = dict(),
)

A single benchmark problem to be solved by the model.

Attributes:

Name Type Description
problem_id str

Unique identifier (e.g. "HumanEval/0", "mbpp/1").

prompt str

The code prompt / problem description shown to the model.

test_code str

Python code that asserts correctness of a solution. This is appended to the model's generation and executed.

entry_point str | None

Optional function name the model must define. Used by HumanEval-style benchmarks to construct the test harness.

metadata dict[str, Any]

Arbitrary extra fields (difficulty, source, etc.).

PassVerdict dataclass
PassVerdict(
    problem_id: str,
    passed: bool,
    generation: str,
    error: str | None,
    timed_out: bool,
)

Verdict for a single problem evaluation.

Attributes:

Name Type Description
problem_id str

Matches the Problem.problem_id that was evaluated.

passed bool

True if the generation passed all tests.

generation str

The raw text generated by the model.

error str | None

Error message from the sandbox, or None if passed.

timed_out bool

True if the sandbox terminated the process for timeout.

BenchmarkConfig dataclass
BenchmarkConfig(
    timeout_s: int = 30,
    max_workers: int = 4,
    max_samples: int | None = None,
    seed: int = 42,
)

Runtime configuration for a benchmark run.

Attributes:

Name Type Description
timeout_s int

Per-problem execution timeout in seconds. Default 30.

max_workers int

ThreadPoolExecutor worker count. Default 4.

max_samples int | None

Cap on problems loaded. None means load all.

seed int

Random seed for subsampling (APPS stratified sampler). Default 42.

BenchmarkResult dataclass
BenchmarkResult(
    benchmark_id: str, verdicts: list[PassVerdict]
)

Aggregated result of a full benchmark run.

Attributes:

Name Type Description
benchmark_id str

Identifier of the benchmark (e.g. "humaneval").

verdicts list[PassVerdict]

Per-problem PassVerdict list.

Attributes
n_problems property
n_problems: int

Total number of problems evaluated.

n_passed property
n_passed: int

Number of problems where passed=True.

pass_at_1 property
pass_at_1: float

Pass@1 as a fraction in [0.0, 1.0].

Returns 0.0 when there are no verdicts.

BenchmarkAdapter

Bases: Protocol

Protocol that every benchmark adapter must satisfy.

Implementations are stateless loaders + scorers. Each adapter is responsible for exactly one benchmark (HumanEval, MBPP, etc.).

Implementors

HumanEvalAdapter, MBPPAdapter, APPSAdapter, BigCodeBenchAdapter, DS1000Adapter, LiveCodeBenchAdapter, SWEBenchLiteAdapter, CodeContestsAdapter

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load benchmark problems, optionally capped and seeded.

Parameters:

Name Type Description Default
max_samples int | None

Maximum number of problems to return. None means return all available problems.

None
seed int

Random seed for subsampling when max_samples < total.

42

Returns:

Type Description
list[Problem]

List of Problem instances ready for scoring.

Source code in libs/evaluation/src/evaluation/benchmarks/protocol.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load benchmark problems, optionally capped and seeded.

    Args:
        max_samples: Maximum number of problems to return.
            None means return all available problems.
        seed: Random seed for subsampling when max_samples < total.

    Returns:
        List of Problem instances ready for scoring.
    """
    ...
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a single model generation against the problem's tests.

Parameters:

Name Type Description Default
problem Problem

The Problem instance (from load_problems).

required
generation str

Raw text generated by the model. This is the model's completion of problem.prompt.

required
timeout_s int

Sandbox timeout in seconds.

30

Returns:

Type Description
PassVerdict

A PassVerdict indicating pass/fail and any error output.

Source code in libs/evaluation/src/evaluation/benchmarks/protocol.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def score(
    self, problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict:
    """Score a single model generation against the problem's tests.

    Args:
        problem: The Problem instance (from load_problems).
        generation: Raw text generated by the model. This is the
            model's completion of problem.prompt.
        timeout_s: Sandbox timeout in seconds.

    Returns:
        A PassVerdict indicating pass/fail and any error output.
    """
    ...
runner

Benchmark runner — orchestrates sampling + scoring for run_benchmark().

Uses ThreadPoolExecutor for parallel per-problem evaluation. Supports all eight benchmark adapters via a registry dict keyed by benchmark_id.

No GPU imports. All heavy lifting (model inference, sandbox execution) happens inside the provider and adapter.score() calls, which are already CPU-safe at import time.

Classes Functions
run_benchmark
run_benchmark(
    adapter_stack: AdapterStack,
    benchmark_id: str,
    problem_ids: list[str] | None = None,
    max_samples: int | None = None,
    config: BenchmarkConfig | None = None,
) -> BenchmarkResult

Run a full benchmark evaluation pass and return aggregate Pass@1.

Orchestrates: 1. Load problems from the benchmark adapter (with optional ID filter). 2. Fan out (generate + score) via ThreadPoolExecutor. 3. Aggregate verdicts into a BenchmarkResult.

Parameters:

Name Type Description Default
adapter_stack AdapterStack

AdapterStack describing base model + adapters + provider.

required
benchmark_id str

One of the registered benchmark IDs: humaneval, mbpp, apps, bigcodebench, ds_1000, livecodebench, swe_bench_lite, codecontests.

required
problem_ids list[str] | None

Optional list of problem_id strings to restrict evaluation to a subset. If None, evaluates all loaded problems.

None
max_samples int | None

Cap on total problems evaluated.

None
config BenchmarkConfig | None

BenchmarkConfig overriding defaults (timeout, workers, seed).

None

Returns:

Type Description
BenchmarkResult

BenchmarkResult with per-problem verdicts and aggregate pass_at_1.

Raises:

Type Description
ValueError

If benchmark_id is not in the known registry.

Example

result = run_benchmark(stack, "humaneval", max_samples=50) print(f"Pass@1: {result.pass_at_1:.2%}")

Source code in libs/evaluation/src/evaluation/benchmarks/runner.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def run_benchmark(
    adapter_stack: AdapterStack,
    benchmark_id: str,
    problem_ids: list[str] | None = None,
    max_samples: int | None = None,
    config: BenchmarkConfig | None = None,
) -> BenchmarkResult:
    """Run a full benchmark evaluation pass and return aggregate Pass@1.

    Orchestrates:
    1. Load problems from the benchmark adapter (with optional ID filter).
    2. Fan out (generate + score) via ThreadPoolExecutor.
    3. Aggregate verdicts into a BenchmarkResult.

    Args:
        adapter_stack: AdapterStack describing base model + adapters + provider.
        benchmark_id: One of the registered benchmark IDs:
            humaneval, mbpp, apps, bigcodebench, ds_1000,
            livecodebench, swe_bench_lite, codecontests.
        problem_ids: Optional list of problem_id strings to restrict
            evaluation to a subset. If None, evaluates all loaded problems.
        max_samples: Cap on total problems evaluated.
        config: BenchmarkConfig overriding defaults (timeout, workers, seed).

    Returns:
        BenchmarkResult with per-problem verdicts and aggregate pass_at_1.

    Raises:
        ValueError: If benchmark_id is not in the known registry.

    Example:
        >>> result = run_benchmark(stack, "humaneval", max_samples=50)
        >>> print(f"Pass@1: {result.pass_at_1:.2%}")
    """
    if benchmark_id not in _ADAPTER_REGISTRY:
        raise ValueError(
            f"Unknown benchmark_id {benchmark_id!r}. "
            f"Known benchmarks: {sorted(_ADAPTER_REGISTRY)}"
        )

    # Build effective config: merge caller's max_samples into config
    if config is None:
        cfg = BenchmarkConfig(max_samples=max_samples)
    else:
        cfg = config
    if max_samples is not None:
        cfg = BenchmarkConfig(
            timeout_s=cfg.timeout_s,
            max_workers=cfg.max_workers,
            max_samples=max_samples,
            seed=cfg.seed,
        )

    adapter = _import_adapter(_ADAPTER_REGISTRY[benchmark_id])
    problems: list[Problem] = adapter.load_problems(
        max_samples=cfg.max_samples,
        seed=cfg.seed,
    )

    # Apply problem_ids filter
    if problem_ids is not None:
        id_set = set(problem_ids)
        problems = [p for p in problems if p.problem_id in id_set]

    if not problems:
        return BenchmarkResult(benchmark_id=benchmark_id, verdicts=[])

    logger.info(
        "run_benchmark: benchmark=%s n_problems=%d max_workers=%d",
        benchmark_id,
        len(problems),
        cfg.max_workers,
    )

    verdicts: list[PassVerdict] = []
    with ThreadPoolExecutor(max_workers=cfg.max_workers) as executor:
        futures = {
            executor.submit(_evaluate_one, adapter, adapter_stack, p, cfg): p
            for p in problems
        }
        for future in as_completed(futures):
            verdict = future.result()
            verdicts.append(verdict)
            status = "PASS" if verdict.passed else "FAIL"
            logger.debug("  [%s] %s", status, verdict.problem_id)

    # Restore original problem order
    id_order = {p.problem_id: i for i, p in enumerate(problems)}
    verdicts.sort(key=lambda v: id_order.get(v.problem_id, 9999))

    return BenchmarkResult(benchmark_id=benchmark_id, verdicts=verdicts)
swe_bench

SWE-Bench-Lite benchmark adapter.

load_problems() loads the 300-problem Lite split from princeton-nlp/SWE-bench_Lite and surfaces repo/test metadata needed for scoring (FAIL_TO_PASS, PASS_TO_PASS, test_patch, environment_setup_commit).

score() implements the repo-checkout + git-apply + pytest preflight: 1. Shallow-clone metadata['repo'] into a temp dir at base_commit. 2. Apply test_patch so the oracle tests are present. 3. Apply the model's generation (unified diff) with git apply. 4. Install the checkout in editable mode (best-effort — failure is treated as an environment error, not a patch failure). 5. Run pytest on FAIL_TO_PASS and PASS_TO_PASS node ids. 6. PASS iff every FAIL_TO_PASS and PASS_TO_PASS test passes.

The score pipeline is gated behind the RUNE_SWE_BENCH_SCORE env var. When unset, score() raises NotImplementedError to preserve Plan A's CI contract (no network / Docker in CI). Set RUNE_SWE_BENCH_SCORE=1 to enable.

Classes
SWEBenchLiteAdapter

Benchmark adapter for SWE-Bench-Lite (held-out generalization set).

Attributes:

Name Type Description
benchmark_id str

"swe_bench_lite".

Note

score() performs a heavyweight preflight (git clone + pytest) when the RUNE_SWE_BENCH_SCORE env var is truthy. By default it still raises NotImplementedError so CI remains hermetic.

Functions
load_problems
load_problems(
    max_samples: int | None = None, seed: int = 42
) -> list[Problem]

Load SWE-Bench-Lite problem metadata.

Does NOT clone repositories or set up execution environments. The metadata field carries repo, base_commit, test_patch, FAIL_TO_PASS, PASS_TO_PASS, and environment_setup_commit so that score() can do its work later if enabled.

Parameters:

Name Type Description Default
max_samples int | None

Cap on returned problems.

None
seed int

Subsampling seed.

42

Returns:

Type Description
list[Problem]

List of Problem instances.

Source code in libs/evaluation/src/evaluation/benchmarks/swe_bench.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def load_problems(
    self,
    max_samples: int | None = None,
    seed: int = 42,
) -> list[Problem]:
    """Load SWE-Bench-Lite problem metadata.

    Does NOT clone repositories or set up execution environments. The
    metadata field carries repo, base_commit, test_patch, FAIL_TO_PASS,
    PASS_TO_PASS, and environment_setup_commit so that score() can do
    its work later if enabled.

    Args:
        max_samples: Cap on returned problems.
        seed: Subsampling seed.

    Returns:
        List of Problem instances.
    """
    rows = self._load_rows()
    if max_samples is not None and max_samples < len(rows):
        rng = random.Random(seed)
        rows = rng.sample(rows, max_samples)
    return [self._row_to_problem(r) for r in rows]
score
score(
    problem: Problem, generation: str, timeout_s: int = 30
) -> PassVerdict

Score a generated patch by applying it and running the oracle tests.

Gated by RUNE_SWE_BENCH_SCORE: when unset, raises NotImplementedError (Plan A CI contract). When set, performs the full clone/apply/pytest pipeline.

Parameters:

Name Type Description Default
problem Problem

Problem instance with repo/base_commit/test_patch/ FAIL_TO_PASS/PASS_TO_PASS metadata.

required
generation str

Proposed patch (unified diff format).

required
timeout_s int

Overall wall clock budget in seconds.

30

Returns:

Type Description
PassVerdict

PassVerdict. passed is True iff every FAIL_TO_PASS and

PassVerdict

PASS_TO_PASS test passes after applying the generation.

Raises:

Type Description
NotImplementedError

When the RUNE_SWE_BENCH_SCORE env var is not truthy, preserving the hermetic-CI default.

Source code in libs/evaluation/src/evaluation/benchmarks/swe_bench.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def score(
    self,
    problem: Problem,
    generation: str,
    timeout_s: int = 30,
) -> PassVerdict:
    """Score a generated patch by applying it and running the oracle tests.

    Gated by ``RUNE_SWE_BENCH_SCORE``: when unset, raises
    NotImplementedError (Plan A CI contract). When set, performs the
    full clone/apply/pytest pipeline.

    Args:
        problem: Problem instance with repo/base_commit/test_patch/
            FAIL_TO_PASS/PASS_TO_PASS metadata.
        generation: Proposed patch (unified diff format).
        timeout_s: Overall wall clock budget in seconds.

    Returns:
        PassVerdict. ``passed`` is True iff every FAIL_TO_PASS and
        PASS_TO_PASS test passes after applying the generation.

    Raises:
        NotImplementedError: When the ``RUNE_SWE_BENCH_SCORE`` env var
            is not truthy, preserving the hermetic-CI default.
    """
    if not _score_enabled():
        raise NotImplementedError(
            "preflight clone/apply not yet implemented — see follow-on plan. "
            "Set RUNE_SWE_BENCH_SCORE=1 to run clone + git-apply + pytest."
        )

    repo = str(problem.metadata.get("repo", ""))
    base_commit = str(problem.metadata.get("base_commit", ""))
    test_patch = str(problem.metadata.get("test_patch", ""))
    fail_to_pass = _decode_node_list(problem.metadata.get("FAIL_TO_PASS"))
    pass_to_pass = _decode_node_list(problem.metadata.get("PASS_TO_PASS"))

    if not repo or not base_commit:
        return PassVerdict(
            problem_id=problem.problem_id,
            passed=False,
            generation=generation,
            error="missing repo/base_commit metadata",
            timed_out=False,
        )
    if not fail_to_pass and not pass_to_pass:
        return PassVerdict(
            problem_id=problem.problem_id,
            passed=False,
            generation=generation,
            error="no FAIL_TO_PASS or PASS_TO_PASS tests declared",
            timed_out=False,
        )

    with tempfile.TemporaryDirectory(prefix="swe_bench_") as workdir:
        work_path = Path(workdir)
        clone = _run_git_clone(repo, base_commit, work_path, timeout_s)
        if clone.returncode != 0:
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=f"clone failed: {clone.stderr.strip()[:400]}",
                timed_out=clone.timed_out,
            )

        repo_dir = work_path / "repo"

        if test_patch:
            apply_tests = _apply_patch(repo_dir, test_patch, timeout_s)
            if apply_tests.returncode != 0:
                return PassVerdict(
                    problem_id=problem.problem_id,
                    passed=False,
                    generation=generation,
                    error=f"test_patch did not apply: "
                    f"{apply_tests.stderr.strip()[:400]}",
                    timed_out=apply_tests.timed_out,
                )

        apply_gen = _apply_patch(repo_dir, generation, timeout_s)
        if apply_gen.returncode != 0:
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error=f"generation did not apply: {apply_gen.stderr.strip()[:400]}",
                timed_out=apply_gen.timed_out,
            )

        # Best-effort editable install; tolerate failure so scoring still
        # runs for repos that are already importable.
        _run_pip_install_editable(repo_dir, timeout_s)

        all_tests = fail_to_pass + pass_to_pass
        pytest_res = _run_pytest(repo_dir, all_tests, timeout_s)
        if pytest_res.timed_out:
            return PassVerdict(
                problem_id=problem.problem_id,
                passed=False,
                generation=generation,
                error="pytest timed out",
                timed_out=True,
            )

        return PassVerdict(
            problem_id=problem.problem_id,
            passed=pytest_res.returncode == 0,
            generation=generation,
            error=None
            if pytest_res.returncode == 0
            else f"pytest returncode={pytest_res.returncode}: "
            f"{pytest_res.stdout.strip()[-400:]}",
            timed_out=False,
        )

metrics

Evaluation metrics for adapter benchmarking and fitness scoring.

Provides functions for running benchmarks (HumanEval), calculating metrics (Pass@k, quality scores), comparing adapters, testing generalization, and computing evolutionary fitness for the evolution operator.

Functions
calculate_pass_at_k
calculate_pass_at_k(
    n_samples: int, n_correct: int, k: int = 1
) -> float

Calculate the Pass@k metric for code generation evaluation.

Computes the probability that at least one of k sampled solutions is correct, using the unbiased estimator from the HumanEval paper (Chen et al., 2021). This avoids the high-variance naive estimator.

Formula: 1 - prod((n-c-i)/(n-i) for i in range(k))

Parameters:

Name Type Description Default
n_samples int

Total number of samples generated per problem.

required
n_correct int

Number of correct samples out of n_samples.

required
k int

Number of attempts allowed for the Pass@k metric. Defaults to 1.

1

Returns:

Type Description
float

Pass@k probability as a float between 0.0 and 1.0.

Raises:

Type Description
ValueError

If n_correct > n_samples.

Example

score = calculate_pass_at_k(n_samples=100, n_correct=85, k=1) score 0.85

Source code in libs/evaluation/src/evaluation/metrics.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def calculate_pass_at_k(n_samples: int, n_correct: int, k: int = 1) -> float:
    """Calculate the Pass@k metric for code generation evaluation.

    Computes the probability that at least one of k sampled solutions is
    correct, using the unbiased estimator from the HumanEval paper
    (Chen et al., 2021). This avoids the high-variance naive estimator.

    Formula: 1 - prod((n-c-i)/(n-i) for i in range(k))

    Args:
        n_samples: Total number of samples generated per problem.
        n_correct: Number of correct samples out of n_samples.
        k: Number of attempts allowed for the Pass@k metric. Defaults to 1.

    Returns:
        Pass@k probability as a float between 0.0 and 1.0.

    Raises:
        ValueError: If n_correct > n_samples.

    Example:
        >>> score = calculate_pass_at_k(n_samples=100, n_correct=85, k=1)
        >>> score
        0.85
    """
    if n_correct > n_samples:
        raise ValueError(
            f"n_correct ({n_correct}) cannot be greater than n_samples ({n_samples})"
        )
    if n_correct == n_samples:
        return 1.0
    if n_samples - n_correct < k:
        return 1.0
    # Unbiased estimator: 1 - prod((n-c-i)/(n-i) for i in range(k))
    product = math.prod((n_samples - n_correct - i) / (n_samples - i) for i in range(k))
    return 1.0 - product
run_kill_switch_gate
run_kill_switch_gate(
    baseline_pass1: float,
    adapter_pass1: float,
    threshold: float = 0.05,
) -> dict[str, object]

Compare baseline vs adapter Pass@1 scores and return a PASS/FAIL verdict.

Computes the relative improvement of the adapter over the baseline and returns PASS if the improvement meets the threshold, FAIL otherwise.

Parameters:

Name Type Description Default
baseline_pass1 float

Pass@1 score for the baseline model (no adapter).

required
adapter_pass1 float

Pass@1 score for the adapter model.

required
threshold float

Minimum required relative improvement (default 0.05 = 5%).

0.05

Returns:

Type Description
dict[str, object]

Dictionary with: - "baseline_pass1": float - "adapter_pass1": float - "relative_delta": float, relative improvement over baseline - "verdict": str, "PASS" or "FAIL"

Example

result = run_kill_switch_gate(0.50, 0.55) result["verdict"] 'PASS'

Source code in libs/evaluation/src/evaluation/metrics.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def run_kill_switch_gate(
    baseline_pass1: float,
    adapter_pass1: float,
    threshold: float = 0.05,
) -> dict[str, object]:
    """Compare baseline vs adapter Pass@1 scores and return a PASS/FAIL verdict.

    Computes the relative improvement of the adapter over the baseline and
    returns PASS if the improvement meets the threshold, FAIL otherwise.

    Args:
        baseline_pass1: Pass@1 score for the baseline model (no adapter).
        adapter_pass1: Pass@1 score for the adapter model.
        threshold: Minimum required relative improvement (default 0.05 = 5%).

    Returns:
        Dictionary with:
            - "baseline_pass1": float
            - "adapter_pass1": float
            - "relative_delta": float, relative improvement over baseline
            - "verdict": str, "PASS" or "FAIL"

    Example:
        >>> result = run_kill_switch_gate(0.50, 0.55)
        >>> result["verdict"]
        'PASS'
    """
    # 1e-9 prevents division-by-zero when baseline is 0.0
    relative_delta = (adapter_pass1 - baseline_pass1) / max(baseline_pass1, 1e-9)
    verdict = "PASS" if adapter_pass1 >= baseline_pass1 * (1 + threshold) else "FAIL"

    print(
        f"Kill-switch gate result: {verdict}\n"
        f"  Baseline  Pass@1: {baseline_pass1:.4f}\n"
        f"  Adapter   Pass@1: {adapter_pass1:.4f}\n"
        f"  Relative delta:   {relative_delta:+.2%} (threshold: {threshold:+.0%})"
    )

    return {
        "baseline_pass1": baseline_pass1,
        "adapter_pass1": adapter_pass1,
        "relative_delta": relative_delta,
        "verdict": verdict,
    }
run_humaneval_subset
run_humaneval_subset(
    adapter_id: Optional[str],
    subset_size: int = 20,
    model: str = "Qwen/Qwen3.5-9B",
    completions: Optional[dict[str, str]] = None,
) -> dict[str, Any]

Run a HumanEval benchmark subset to evaluate an adapter.

Loads tasks from the bundled 20-task HumanEval subset JSON and evaluates them using the provided completions. For each task, concatenates prompt + completion + test + check(entry_point), writes to a temp script, and executes via subprocess. Exit code 0 = passed.

Parameters:

Name Type Description Default
adapter_id Optional[str]

UUID of the adapter to test (None = baseline, no adapter). Currently informational; inference wiring happens at a higher level.

required
subset_size int

Ignored — always uses the fixed 20-task bundled subset.

20
model str

Base model name (informational only, not used for inference here).

'Qwen/Qwen3.5-9B'
completions Optional[dict[str, str]]

Dict mapping task_id -> completion string. Only tasks with an entry in this dict are evaluated. If None or empty, returns empty results.

None

Returns:

Type Description
dict[str, Any]

Dictionary with benchmark results including: - "pass_count": int, number of tasks passed - "fail_count": int, number of tasks failed - "pass_rate": float, fraction of tasks passed (0.0 to 1.0) - "task_results": list of per-task result dicts with task_id, passed - "summary": str, human-readable summary

Raises:

Type Description
NotImplementedError

If completions are not provided (inference not wired).

Example

completions = {"HumanEval/0": " return []"} results = run_humaneval_subset(adapter_id=None, completions=completions) results["pass_count"] 0

Source code in libs/evaluation/src/evaluation/metrics.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def run_humaneval_subset(
    adapter_id: Optional[str],
    subset_size: int = 20,
    model: str = "Qwen/Qwen3.5-9B",
    completions: Optional[dict[str, str]] = None,
) -> dict[str, Any]:
    """Run a HumanEval benchmark subset to evaluate an adapter.

    Loads tasks from the bundled 20-task HumanEval subset JSON and evaluates
    them using the provided completions. For each task, concatenates
    prompt + completion + test + check(entry_point), writes to a temp script,
    and executes via subprocess. Exit code 0 = passed.

    Args:
        adapter_id: UUID of the adapter to test (None = baseline, no adapter).
            Currently informational; inference wiring happens at a higher level.
        subset_size: Ignored — always uses the fixed 20-task bundled subset.
        model: Base model name (informational only, not used for inference here).
        completions: Dict mapping task_id -> completion string. Only tasks with
            an entry in this dict are evaluated. If None or empty, returns empty
            results.

    Returns:
        Dictionary with benchmark results including:
            - "pass_count": int, number of tasks passed
            - "fail_count": int, number of tasks failed
            - "pass_rate": float, fraction of tasks passed (0.0 to 1.0)
            - "task_results": list of per-task result dicts with task_id, passed
            - "summary": str, human-readable summary

    Raises:
        NotImplementedError: If completions are not provided (inference not wired).

    Example:
        >>> completions = {"HumanEval/0": "    return []"}
        >>> results = run_humaneval_subset(adapter_id=None, completions=completions)
        >>> results["pass_count"]
        0
    """
    if completions is None:
        raise NotImplementedError("run_humaneval_subset is not yet implemented.")

    # Load bundled task data
    subset_path = _DATA_DIR / "humaneval_subset.json"
    with subset_path.open() as f:
        all_tasks: list[dict[str, str]] = json.load(f)

    # Build lookup by task_id
    task_map = {t["task_id"]: t for t in all_tasks}

    task_results: list[dict[str, Any]] = []

    with tempfile.TemporaryDirectory() as tmpdir:
        for task_id, completion in completions.items():
            task = task_map.get(task_id)
            if task is None:
                continue

            # Build executable script: prompt + completion + test + check(entry_point)
            script = (
                task["prompt"]
                + completion
                + "\n"
                + task["test"]
                + f"\ncheck({task['entry_point']})\n"
            )

            script_path = Path(tmpdir) / f"{task_id.replace('/', '_')}.py"
            script_path.write_text(script)

            passed = safe_subprocess_run(script_path, cwd=tmpdir)
            task_results.append({"task_id": task_id, "passed": passed})

    pass_count = sum(1 for r in task_results if r["passed"])
    fail_count = len(task_results) - pass_count
    total = len(task_results)
    pass_rate = pass_count / total if total > 0 else 0.0

    summary = (
        f"HumanEval subset: {pass_count}/{total} passed "
        f"(pass_rate={pass_rate:.2%}, adapter_id={adapter_id})"
    )
    print(summary)

    return {
        "pass_count": pass_count,
        "fail_count": fail_count,
        "pass_rate": pass_rate,
        "task_results": task_results,
        "summary": summary,
    }
score_adapter_quality
score_adapter_quality(
    adapter_id: str,
    pass_rate: float,
    generalization_delta: float | None = None,
) -> float

Compute an overall quality score for an adapter.

Aggregates the adapter's benchmark pass rate with its generalization performance (if available) into a single scalar quality score. When generalization data is absent, quality is derived from pass rate alone.

Parameters:

Name Type Description Default
adapter_id str

UUID of the adapter to score.

required
pass_rate float

Fraction of benchmark tasks passed, in range 0.0 to 1.0.

required
generalization_delta float | None

Optional difference between in-distribution and out-of-distribution (OOD) performance. Positive values indicate the adapter generalizes well; negative values indicate overfitting. Defaults to None (not measured).

None

Returns:

Type Description
float

Quality score as a float between 0.0 and 1.0. Higher values indicate

float

a better overall adapter quality.

Raises:

Type Description
NotImplementedError

score_adapter_quality is not yet implemented.

Example

score = score_adapter_quality("adapter-001", pass_rate=0.85) score 0.85 score_with_gen = score_adapter_quality( ... "adapter-001", 0.85, generalization_delta=0.1, ... ) score_with_gen > score True

Source code in libs/evaluation/src/evaluation/metrics.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def score_adapter_quality(
    adapter_id: str,
    pass_rate: float,
    generalization_delta: float | None = None,
) -> float:
    """Compute an overall quality score for an adapter.

    Aggregates the adapter's benchmark pass rate with its generalization
    performance (if available) into a single scalar quality score. When
    generalization data is absent, quality is derived from pass rate alone.

    Args:
        adapter_id: UUID of the adapter to score.
        pass_rate: Fraction of benchmark tasks passed, in range 0.0 to 1.0.
        generalization_delta: Optional difference between in-distribution and
            out-of-distribution (OOD) performance. Positive values indicate
            the adapter generalizes well; negative values indicate overfitting.
            Defaults to None (not measured).

    Returns:
        Quality score as a float between 0.0 and 1.0. Higher values indicate
        a better overall adapter quality.

    Raises:
        NotImplementedError: score_adapter_quality is not yet implemented.

    Example:
        >>> score = score_adapter_quality("adapter-001", pass_rate=0.85)
        >>> score
        0.85
        >>> score_with_gen = score_adapter_quality(
        ...     "adapter-001", 0.85, generalization_delta=0.1,
        ... )
        >>> score_with_gen > score
        True
    """
    if generalization_delta is not None:
        quality = min(pass_rate + 0.1 * max(generalization_delta, 0), 1.0)
    else:
        quality = pass_rate
    return quality
compare_adapters
compare_adapters(
    adapter_ids: list[str], benchmark: str = "humaneval"
) -> dict[str, Any]

Compare multiple adapters head-to-head on a benchmark.

Evaluates each adapter in the list on the specified benchmark and produces a comparative report with per-adapter scores, rankings, and a summary of which adapter performs best.

Parameters:

Name Type Description Default
adapter_ids list[str]

List of adapter UUIDs to compare. Must contain at least two adapter IDs.

required
benchmark str

Benchmark name to use for comparison. Currently supports "humaneval". Defaults to "humaneval".

'humaneval'

Returns:

Type Description
dict[str, Any]

Dictionary with comparison results including: - "scores": dict mapping adapter_id to its benchmark score - "rankings": list of adapter_ids sorted best-to-worst - "best_adapter": str, UUID of the top-performing adapter - "summary": str, human-readable comparison summary

Raises:

Type Description
NotImplementedError

compare_adapters is not yet implemented.

Example

results = compare_adapters(["adapter-001", "adapter-002"]) results["best_adapter"] in ["adapter-001", "adapter-002"] True results["best_adapter"] in results["rankings"] True

Source code in libs/evaluation/src/evaluation/metrics.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def compare_adapters(
    adapter_ids: list[str],
    benchmark: str = "humaneval",
) -> dict[str, Any]:
    """Compare multiple adapters head-to-head on a benchmark.

    Evaluates each adapter in the list on the specified benchmark and produces
    a comparative report with per-adapter scores, rankings, and a summary of
    which adapter performs best.

    Args:
        adapter_ids: List of adapter UUIDs to compare. Must contain at least
            two adapter IDs.
        benchmark: Benchmark name to use for comparison. Currently supports
            "humaneval". Defaults to "humaneval".

    Returns:
        Dictionary with comparison results including:
            - "scores": dict mapping adapter_id to its benchmark score
            - "rankings": list of adapter_ids sorted best-to-worst
            - "best_adapter": str, UUID of the top-performing adapter
            - "summary": str, human-readable comparison summary

    Raises:
        NotImplementedError: compare_adapters is not yet implemented.

    Example:
        >>> results = compare_adapters(["adapter-001", "adapter-002"])
        >>> results["best_adapter"] in ["adapter-001", "adapter-002"]
        True
        >>> results["best_adapter"] in results["rankings"]
        True
    """
    if len(adapter_ids) < 2:
        raise ValueError("compare_adapters requires at least 2 adapter IDs")

    # Without live inference, return a stub comparison based on adapter order
    scores: dict[str, float] = {}
    for i, aid in enumerate(adapter_ids):
        scores[aid] = 1.0 / (i + 1)  # Placeholder scoring

    rankings = sorted(scores, key=lambda x: scores[x], reverse=True)
    best = rankings[0]
    summary = f"Compared {len(adapter_ids)} adapters on {benchmark}; best={best}"

    return {
        "scores": scores,
        "rankings": rankings,
        "best_adapter": best,
        "summary": summary,
    }
test_generalization
test_generalization(
    adapter_id: str,
    in_distribution_tasks: list[str] | None = None,
    ood_tasks: list[str] | None = None,
) -> dict[str, Any]

Test whether an adapter generalizes beyond its training distribution.

Evaluates the adapter on both in-distribution tasks (matching the training data distribution) and out-of-distribution (OOD) tasks to measure how well the adapter generalizes to novel problems.

Parameters:

Name Type Description Default
adapter_id str

UUID of the adapter to evaluate.

required
in_distribution_tasks list[str] | None

Optional list of task IDs matching the adapter's training distribution. If None, uses a default in-distribution set.

None
ood_tasks list[str] | None

Optional list of out-of-distribution task IDs to test generalization on. If None, uses a default OOD task set.

None

Returns:

Type Description
dict[str, Any]

Dictionary with generalization results including: - "in_distribution_score": float, performance on training-distribution tasks - "ood_score": float, performance on out-of-distribution tasks - "generalization_delta": float, difference (in_distribution - ood) - "generalizes": bool, True if generalization_delta is within threshold

Raises:

Type Description
NotImplementedError

test_generalization is not yet implemented.

Example

results = test_generalization("adapter-001") results["generalization_delta"] 0.05 results["generalizes"] True

Source code in libs/evaluation/src/evaluation/metrics.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def test_generalization(
    adapter_id: str,
    in_distribution_tasks: list[str] | None = None,
    ood_tasks: list[str] | None = None,
) -> dict[str, Any]:
    """Test whether an adapter generalizes beyond its training distribution.

    Evaluates the adapter on both in-distribution tasks (matching the training
    data distribution) and out-of-distribution (OOD) tasks to measure how well
    the adapter generalizes to novel problems.

    Args:
        adapter_id: UUID of the adapter to evaluate.
        in_distribution_tasks: Optional list of task IDs matching the adapter's
            training distribution. If None, uses a default in-distribution set.
        ood_tasks: Optional list of out-of-distribution task IDs to test
            generalization on. If None, uses a default OOD task set.

    Returns:
        Dictionary with generalization results including:
            - "in_distribution_score": float, performance on training-distribution tasks
            - "ood_score": float, performance on out-of-distribution tasks
            - "generalization_delta": float, difference (in_distribution - ood)
            - "generalizes": bool, True if generalization_delta is within threshold

    Raises:
        NotImplementedError: test_generalization is not yet implemented.

    Example:
        >>> results = test_generalization("adapter-001")
        >>> results["generalization_delta"]
        0.05
        >>> results["generalizes"]
        True
    """
    in_dist_score = 0.8  # Placeholder until live inference wired
    ood_score = 0.6
    gen_delta = in_dist_score - ood_score
    generalizes = abs(gen_delta) <= 0.2

    return {
        "adapter_id": adapter_id,
        "in_distribution_score": in_dist_score,
        "ood_score": ood_score,
        "generalization_delta": gen_delta,
        "generalizes": generalizes,
    }
evaluate_fitness
evaluate_fitness(
    adapter_id: str,
    pass_rate: float,
    diversity_score: float = 0.0,
) -> float

Calculate evolutionary fitness score for the evolution operator.

Computes a composite fitness score used by the evolutionary algorithm to rank and select adapters for mutation and crossover. Balances raw performance (pass_rate) with adapter diversity to avoid population collapse.

Parameters:

Name Type Description Default
adapter_id str

UUID of the adapter to evaluate.

required
pass_rate float

Fraction of benchmark tasks passed, in range 0.0 to 1.0.

required
diversity_score float

Adapter uniqueness metric representing how different this adapter is from others in the current population. Range 0.0 to 1.0; higher values indicate more unique adapters. Defaults to 0.0.

0.0

Returns:

Type Description
float

Fitness score as a float between 0.0 and 1.0. Higher values indicate

float

adapters more likely to be selected for the next evolutionary generation.

Raises:

Type Description
NotImplementedError

evaluate_fitness is not yet implemented.

Example

fitness = evaluate_fitness( ... "adapter-001", pass_rate=0.85, diversity_score=0.3, ... ) fitness 0.795 low_diversity = evaluate_fitness( ... "adapter-001", pass_rate=0.85, diversity_score=0.0, ... ) low_diversity < fitness True

Source code in libs/evaluation/src/evaluation/metrics.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
def evaluate_fitness(
    adapter_id: str,
    pass_rate: float,
    diversity_score: float = 0.0,
) -> float:
    """Calculate evolutionary fitness score for the evolution operator.

    Computes a composite fitness score used by the evolutionary algorithm to
    rank and select adapters for mutation and crossover. Balances raw
    performance (pass_rate) with adapter diversity to avoid population collapse.

    Args:
        adapter_id: UUID of the adapter to evaluate.
        pass_rate: Fraction of benchmark tasks passed, in range 0.0 to 1.0.
        diversity_score: Adapter uniqueness metric representing how different
            this adapter is from others in the current population. Range 0.0
            to 1.0; higher values indicate more unique adapters. Defaults to 0.0.

    Returns:
        Fitness score as a float between 0.0 and 1.0. Higher values indicate
        adapters more likely to be selected for the next evolutionary generation.

    Raises:
        NotImplementedError: evaluate_fitness is not yet implemented.

    Example:
        >>> fitness = evaluate_fitness(
        ...     "adapter-001", pass_rate=0.85, diversity_score=0.3,
        ... )
        >>> fitness
        0.795
        >>> low_diversity = evaluate_fitness(
        ...     "adapter-001", pass_rate=0.85, diversity_score=0.0,
        ... )
        >>> low_diversity < fitness
        True
    """
    fitness = 0.7 * pass_rate + 0.3 * diversity_score
    return fitness

ood_benchmark

Out-of-distribution benchmark for adapter generalization testing.

Provides functions for evaluating adapter performance on tasks outside the training distribution, measuring generalization capability.

Functions
run_ood_benchmark
run_ood_benchmark(
    adapter_id: str | None,
    completions: dict[str, str],
    benchmark_name: str = "ood_python",
) -> dict[str, Any]

Run an out-of-distribution benchmark on provided completions.

Evaluates completions against OOD tasks from the bundled task set. Each task's prompt + completion is executed in a subprocess with its test harness.

Parameters:

Name Type Description Default
adapter_id str | None

UUID of the adapter being tested (informational).

required
completions dict[str, str]

Dict mapping task_id to completion string.

required
benchmark_name str

Name of the OOD benchmark set.

'ood_python'

Returns:

Type Description
dict[str, Any]

Dictionary with ood_pass_rate and per-task results.

Source code in libs/evaluation/src/evaluation/ood_benchmark.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def run_ood_benchmark(
    adapter_id: str | None,
    completions: dict[str, str],
    benchmark_name: str = "ood_python",
) -> dict[str, Any]:
    """Run an out-of-distribution benchmark on provided completions.

    Evaluates completions against OOD tasks from the bundled task set.
    Each task's prompt + completion is executed in a subprocess with its
    test harness.

    Args:
        adapter_id: UUID of the adapter being tested (informational).
        completions: Dict mapping task_id to completion string.
        benchmark_name: Name of the OOD benchmark set.

    Returns:
        Dictionary with ood_pass_rate and per-task results.
    """
    ood_path = _OOD_DATA_DIR / "ood_tasks.json"
    with ood_path.open() as f:
        all_tasks: list[dict[str, str]] = json.load(f)

    task_map = {t["task_id"]: t for t in all_tasks}
    task_results: list[dict[str, Any]] = []

    with tempfile.TemporaryDirectory() as tmpdir:
        for task_id, completion in completions.items():
            task = task_map.get(task_id)
            if task is None:
                continue

            script = task["prompt"] + completion + "\n" + task["test"] + "\n"
            script_path = Path(tmpdir) / f"{task_id.replace('/', '_')}.py"
            script_path.write_text(script)

            passed = safe_subprocess_run(script_path, cwd=tmpdir)

            task_results.append({"task_id": task_id, "passed": passed})

    total = len(task_results)
    pass_count = sum(1 for r in task_results if r["passed"])
    ood_pass_rate = pass_count / total if total > 0 else 0.0

    return {
        "adapter_id": adapter_id,
        "benchmark_name": benchmark_name,
        "ood_pass_rate": ood_pass_rate,
        "pass_count": pass_count,
        "total": total,
        "task_results": task_results,
    }
compute_generalization_delta
compute_generalization_delta(
    in_dist_rate: float, ood_rate: float
) -> float

Compute the generalization delta between in-distribution and OOD performance.

A positive delta means the adapter does better on OOD tasks relative to in-distribution performance. A negative delta indicates overfitting.

Parameters:

Name Type Description Default
in_dist_rate float

Pass rate on in-distribution tasks (0.0 to 1.0).

required
ood_rate float

Pass rate on OOD tasks (0.0 to 1.0).

required

Returns:

Type Description
float

Generalization delta as ood_rate - in_dist_rate.

Source code in libs/evaluation/src/evaluation/ood_benchmark.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def compute_generalization_delta(
    in_dist_rate: float,
    ood_rate: float,
) -> float:
    """Compute the generalization delta between in-distribution and OOD performance.

    A positive delta means the adapter does better on OOD tasks relative to
    in-distribution performance. A negative delta indicates overfitting.

    Args:
        in_dist_rate: Pass rate on in-distribution tasks (0.0 to 1.0).
        ood_rate: Pass rate on OOD tasks (0.0 to 1.0).

    Returns:
        Generalization delta as ood_rate - in_dist_rate.
    """
    return ood_rate - in_dist_rate

utils

Shared subprocess execution utilities for evaluation benchmarks.

Functions
safe_subprocess_run
safe_subprocess_run(
    script_path: Path, cwd: str, timeout: int = 30
) -> bool

Run a Python script in a subprocess and return whether it passed.

Handles subprocess.TimeoutExpired by returning False. Used by both HumanEval and OOD benchmark runners to avoid duplicated try/except + subprocess.run boilerplate.

Parameters:

Name Type Description Default
script_path Path

Path to the Python script to execute.

required
cwd str

Working directory for the subprocess.

required
timeout int

Maximum execution time in seconds before the process is killed.

30

Returns:

Type Description
bool

True if the process exits with return code 0, False otherwise

bool

(including timeout).

Example

from pathlib import Path passed = safe_subprocess_run(Path("/tmp/test.py"), cwd="/tmp") isinstance(passed, bool) True

Source code in libs/evaluation/src/evaluation/utils.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def safe_subprocess_run(
    script_path: Path,
    cwd: str,
    timeout: int = 30,
) -> bool:
    """Run a Python script in a subprocess and return whether it passed.

    Handles ``subprocess.TimeoutExpired`` by returning ``False``.
    Used by both HumanEval and OOD benchmark runners to avoid duplicated
    try/except + subprocess.run boilerplate.

    Args:
        script_path: Path to the Python script to execute.
        cwd: Working directory for the subprocess.
        timeout: Maximum execution time in seconds before the process is killed.

    Returns:
        ``True`` if the process exits with return code 0, ``False`` otherwise
        (including timeout).

    Example:
        >>> from pathlib import Path
        >>> passed = safe_subprocess_run(Path("/tmp/test.py"), cwd="/tmp")
        >>> isinstance(passed, bool)
        True
    """
    try:
        proc = subprocess.run(
            [sys.executable, str(script_path)],
            capture_output=True,
            text=True,
            timeout=timeout,
            cwd=cwd,
        )
        return proc.returncode == 0
    except subprocess.TimeoutExpired:
        return False