File size: 10,292 Bytes
22decf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
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
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
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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
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
"""Cross-run statistics: what, if anything, separated a good run from a bad one.

Accuracy is not comparable across benchmarks -- 0.95 on BFCL and 0.17 on AIME
are both ordinary -- so every comparison here works on `z`, the within-task
z-score of the final accuracy. A feature that "helps" is one that moves a run
up relative to the other runs on *its own* benchmark.

With 48 runs over 7 benchmarks these are descriptive, not inferential: n per
task is 4-8, so the right reading of any correlation is "worth a look", not
"established". Effect sizes are reported alongside n for that reason.
"""

from __future__ import annotations

import math
from collections import defaultdict
from typing import Any, Iterable, Sequence

from .features import RunFeatures

NUMERIC_FEATURES = [
    "wall_h",
    "turns",
    "tool_calls",
    "output_tokens",
    "cost_usd",
    "thinking_blocks",
    "thinking_chars",
    "narration_chars",
    "n_eval_calls",
    "n_scored_evals",
    "n_distinct_model_versions",
    "first_eval_h",
    "tail_idle_h",
    "last_improvement_h",
    "time_awareness_calls",
    "tool_errors",
    "bg_tasks",
    "max_parallel_bg",
    "bg_busy_s",
    "machine_busy_frac",
    "dead_air_h",
    "compactions",
    "api_retries",
    "mean_eval_limit",
    "final_message_chars",
]


def _rank(xs: Sequence[float]) -> list[float]:
    order = sorted(range(len(xs)), key=lambda i: xs[i])
    ranks = [0.0] * len(xs)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]:
            j += 1
        avg = (i + j) / 2 + 1
        for k in range(i, j + 1):
            ranks[order[k]] = avg
        i = j + 1
    return ranks


def spearman(xs: Sequence[float], ys: Sequence[float]) -> float | None:
    if len(xs) < 4:
        return None
    rx, ry = _rank(xs), _rank(ys)
    mx, my = sum(rx) / len(rx), sum(ry) / len(ry)
    num = sum((a - mx) * (b - my) for a, b in zip(rx, ry))
    den = math.sqrt(sum((a - mx) ** 2 for a in rx) * sum((b - my) ** 2 for b in ry))
    return num / den if den else None


def within_task_z(feats: Iterable[RunFeatures]) -> dict[str, float]:
    """Final accuracy, z-scored inside each benchmark.

    Tasks with a single run get z = 0: there is nothing to be better than.
    """
    by_task: defaultdict[str, list[RunFeatures]] = defaultdict(list)
    for f in feats:
        if f.accuracy is not None:
            by_task[f.task].append(f)
    z: dict[str, float] = {}
    for task, group in by_task.items():
        accs = [f.accuracy for f in group]  # type: ignore[misc]
        m = sum(accs) / len(accs)
        sd = math.sqrt(sum((a - m) ** 2 for a in accs) / len(accs)) if len(accs) > 1 else 0.0
        for f in group:
            z[f.run_id] = ((f.accuracy - m) / sd) if sd else 0.0  # type: ignore[operator]
    return z


def feature_correlations(feats: list[RunFeatures]) -> list[dict[str, Any]]:
    z = within_task_z(feats)
    rows = []
    for name in NUMERIC_FEATURES:
        pairs = [
            (getattr(f, name), z[f.run_id])
            for f in feats
            if f.run_id in z and getattr(f, name, None) is not None
        ]
        if len(pairs) < 8:
            continue
        rho = spearman([p[0] for p in pairs], [p[1] for p in pairs])
        if rho is None:
            continue
        rows.append({"feature": name, "rho_vs_within_task_z": round(rho, 3), "n": len(pairs)})
    return sorted(rows, key=lambda r: -abs(r["rho_vs_within_task_z"]))


def technique_effects(feats: list[RunFeatures], min_each: int = 4) -> list[dict[str, Any]]:
    """Mean within-task z for runs that used a technique vs runs that did not."""
    z = within_task_z(feats)
    names: set[str] = set()
    for f in feats:
        names.update(f.techniques)
    rows = []
    for name in sorted(names):
        with_, without = [], []
        for f in feats:
            if f.run_id not in z:
                continue
            (with_ if name in f.techniques else without).append(z[f.run_id])
        if len(with_) < min_each or len(without) < min_each:
            continue
        rows.append(
            {
                "technique": name,
                "n_with": len(with_),
                "n_without": len(without),
                "mean_z_with": round(sum(with_) / len(with_), 3),
                "mean_z_without": round(sum(without) / len(without), 3),
                "delta_z": round(sum(with_) / len(with_) - sum(without) / len(without), 3),
            }
        )
    return sorted(rows, key=lambda r: -r["delta_z"])


def per_task_table(feats: list[RunFeatures]) -> list[dict[str, Any]]:
    by: defaultdict[str, list[RunFeatures]] = defaultdict(list)
    for f in feats:
        by[f.task].append(f)

    def avg(xs):
        xs = [x for x in xs if x is not None]
        return round(sum(xs) / len(xs), 3) if xs else None

    rows = []
    for task, g in sorted(by.items()):
        rows.append(
            {
                "task": task,
                "n_runs": len(g),
                "mean_accuracy": avg([f.accuracy for f in g]),
                "mean_turns": avg([f.turns for f in g]),
                "mean_eval_calls": avg([f.n_eval_calls for f in g]),
                "mean_model_versions": avg([f.n_distinct_model_versions for f in g]),
                "mean_train_hours": avg([f.action_time_s.get("train", 0) / 3600 for f in g]),
                "mean_eval_hours": avg([f.action_time_s.get("eval_official", 0) / 3600 for f in g]),
                "mean_wait_hours": avg([f.action_time_s.get("wait_poll", 0) / 3600 for f in g]),
                "mean_dead_air_h": avg([f.dead_air_h for f in g]),
                "mean_busy_frac": avg([f.machine_busy_frac for f in g]),
                "mean_tail_idle_h": avg([f.tail_idle_h for f in g]),
                "mean_cost_usd": avg([f.cost_usd for f in g]),
                "mean_oom_hits": avg([f.error_signals.get("oom", 0) for f in g]),
            }
        )
    return rows


def rerun_variance(feats: list[RunFeatures]) -> list[dict[str, Any]]:
    """Spread between repeated runs of the same (task, base model) cell.

    This is the noise floor. Any claimed improvement smaller than it is not
    an improvement, and it bounds what a single-seed sweep can conclude.
    """
    by: defaultdict[tuple[str, str], list[RunFeatures]] = defaultdict(list)
    for f in feats:
        if f.accuracy is not None:
            by[(f.task, f.base_model)].append(f)
    rows = []
    for (task, model), g in sorted(by.items()):
        if len(g) < 2:
            continue
        accs = sorted(f.accuracy for f in g)  # type: ignore[misc]
        rows.append(
            {
                "task": task,
                "base_model": model,
                "n": len(g),
                "min": round(accs[0], 4),
                "max": round(accs[-1], 4),
                "spread": round(accs[-1] - accs[0], 4),
                "rel_spread": round((accs[-1] - accs[0]) / accs[-1], 3) if accs[-1] else None,
            }
        )
    return sorted(rows, key=lambda r: -r["spread"])


def final_verification(feats: list[RunFeatures]) -> dict[str, Any]:
    """Did the run end by grading its own submission the way the harness will?

    The deliverable is `final_model`, and the harness scores it with
    `evaluate.py` at full sample count. A run that never does that itself is
    shipping something it has not checked -- a cheap habit with a large
    downside, so it is worth knowing how often it happens.
    """
    verified, partial, none = [], [], []
    for f in feats:
        late = [
            e
            for e in f.evals
            if e.model_path
            and "final_model" in e.model_path
            and f.wall_h
            and e.t_rel / 3600 > 0.6 * f.wall_h
        ]
        if any(e.limit is None or e.limit >= 150 for e in late):
            verified.append(f.run_id)
        elif late:
            partial.append(f.run_id)
        else:
            none.append(f.run_id)
    n = len(feats)
    return {
        "n": n,
        "verified_at_full_scale": len(verified),
        "verified_but_subsampled": len(partial),
        "never_graded_own_submission": len(none),
        "pct_verified": round(100 * len(verified) / n, 1) if n else None,
        "never_graded_examples": none[:8],
    }


def dev_to_harness_drop(feats: list[RunFeatures]) -> dict[str, Any]:
    """Best score the agent measured itself vs the score the harness gave it.

    A systematic positive drop is selection on the development signal: the
    agent picked whichever checkpoint happened to look best, and a fresh
    grading pass gives some of that back.
    """
    rows = []
    for f in feats:
        if f.best_observed is None or f.accuracy is None:
            continue
        rows.append(
            {
                "run_id": f.run_id,
                "task": f.task,
                "best_self_measured": round(f.best_observed, 4),
                "harness": round(f.accuracy, 4),
                "drop": round(f.best_observed - f.accuracy, 4),
            }
        )
    drops = [r["drop"] for r in rows]
    return {
        "n": len(rows),
        "mean_drop": round(sum(drops) / len(drops), 4) if drops else None,
        "median_drop": round(sorted(drops)[len(drops) // 2], 4) if drops else None,
        "n_overstated": sum(1 for d in drops if d > 0.02),
        "n_understated": sum(1 for d in drops if d < -0.02),
        "worst": sorted(rows, key=lambda r: -r["drop"])[:6],
    }


def oom_recovery(feats: list[RunFeatures]) -> dict[str, Any]:
    """How often an out-of-memory failure appears, and whether it ended the run.

    OOM is the signature failure of this task: one H100, a 4B model, and an
    agent that has to guess batch size and sequence length. Recovering from
    it without human help is a capability in its own right.
    """
    hit = [f for f in feats if f.error_signals.get("oom")]
    return {
        "runs_with_oom": len(hit),
        "of": len(feats),
        "pct": round(100 * len(hit) / len(feats), 1) if feats else None,
        "mean_oom_events_when_hit": round(sum(f.error_signals["oom"] for f in hit) / len(hit), 2) if hit else None,
        "all_still_produced_a_model": all(f.accuracy is not None for f in hit),
    }