File size: 6,322 Bytes
2e7f744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare predictors on the same audited v3 tasks -> results/v3/compare_models.json
Usage: python -I v3/della/compare_models.py <tag> [<tag> ...]   (first tag = reference, e.g. opus55-high)

Tasks: audited set (results/v3/audit/clean_tasks.txt), five-hour window, every compared predictor has a clean trial
with a readable, non-empty agent log. Errors: running-best MAE (mean over +15/+30/+60/+120 min and the window end,
a missing target counts as 100) and final MAE, forecasts clipped to [0, 100].
  matched : per cut, every tag on the tasks ALL tags forecast (n, MAE, final MAE, mean rise curve per target)
  pairs   : per cut, each pair (ref vs other, and high vs xhigh of the same model) on the tasks BOTH forecast:
            MAE of each, share where b is better, ties, paired sign-flip permutation p (running best and final),
            Spearman correlation of the two predictors' per-agent MAE (agents with >= 5 forecasts)
"""
import json, os, random, statistics as st, collections, sys, itertools
sys.path.insert(0, '/scratch/gpfs/TRIDAO/ly3223/oraclebench/v3/della')
from rank_corr import spearman
R = '/scratch/gpfs/TRIDAO/ly3223/oraclebench/'
M = R + 'data/v3/full/metadata/'
idx = {json.loads(l)['task_id']: json.loads(l) for l in open(M + 'task_index.jsonl')}
gt = json.load(open(M + 'ground_truth.json'))
keep = set(open(R + 'results/v3/audit/clean_tasks.txt').read().split())
fr = json.load(open(R + 'data/hf_raw/metadata/formal-results.json'))
agent = {r['model_id']: r['candidate_name'] for r in fr['runs']}
clip = lambda v: max(0.0, min(100.0, v))
T = ['best_+15m', 'best_+30m', 'best_+60m', 'best_+120m', 'best_deadline']
tags = sys.argv[1:] or ['opus55-high', 'sonnet55-high']

def load(tag):
    out = {}
    for l in open(R + f'results/v3/{tag}.preds.jsonl'):
        r = json.loads(l); log = r['trial'] + '/agent/claude-code.txt'
        if os.path.exists(log) and os.path.getsize(log) > 0:
            out[r['task_id']] = {p['target']: p['score'] for p in r['predictions'] if isinstance(p.get('score'), (int, float))}
    return out

P = {t: load(t) for t in tags}
five = [t for t in keep if idx[t]['budget_s'] == 18000]

def errs(tag, tid):
    p = P[tag][tid]; e, f = [], None
    for l in gt[tid]:
        if l['status'] != 'ok':
            continue
        v = p.get(l['target']); d = 100.0 if v is None else abs(clip(v) - l['truth'])
        if l['target'] == 'final':
            f = d
        else:
            e.append(d)
    return st.mean(e), f

def signflip(diffs, n=20000, seed=0):
    if not diffs:
        return None
    rng = random.Random(seed); obs = abs(sum(diffs)); hit = 0
    for _ in range(n):
        if abs(sum(d if rng.random() < .5 else -d for d in diffs)) >= obs - 1e-12:
            hit += 1
    return (hit + 1) / (n + 1)

def per_agent(tag, tids):
    by = collections.defaultdict(list)
    for t in tids:
        by[agent[idx[t]['model']]].append(errs(tag, t)[0])
    return {a: st.mean(v) for a, v in by.items() if len(v) >= 5}

res = {'tags': tags, 'clean': {t: len(P[t]) for t in tags}, 'matched': {}, 'pairs': []}
common = sorted(t for t in five if all(t in P[g] for g in tags))
res['n_common'] = len(common)
for cut in (25, 50, 75):
    tids = [t for t in common if idx[t]['cut_fraction'] == cut / 100]
    row = {'n': len(tids), 'models': {}}
    for g in tags:
        E = [errs(g, t) for t in tids]
        row['models'][g] = {'mae': round(st.mean(e for e, _ in E), 3), 'final_mae': round(st.mean(f for _, f in E if f is not None), 3)}
    curve = []
    for h in T:
        tr, pm = [], {g: [] for g in tags}
        for t in tids:
            l = next((x for x in gt[t] if x['target'] == h), None)
            if not l or l['status'] != 'ok' or any(P[g][t].get(h) is None for g in tags):
                continue
            b = idx[t]['best_at_cut']; tr.append(l['truth'] - b)
            for g in tags:
                pm[g].append(clip(P[g][t][h]) - b)
        if tr:
            curve.append({'target': h, 'n': len(tr), 'truth': round(st.mean(tr), 3), 'models': {g: round(st.mean(v), 3) for g, v in pm.items()}})
    row['curve'] = curve
    res['matched'][cut] = row

ref = tags[0]
pairs = [(ref, g) for g in tags[1:]]
for g in tags:  # high vs xhigh of the same predictor model
    if g.endswith('-high') and g[:-5] + '-xhigh' in tags and (g, g[:-5] + '-xhigh') not in pairs:
        pairs.append((g, g[:-5] + '-xhigh'))
for a, b in pairs:
    both = sorted(t for t in five if t in P[a] and t in P[b])
    pr = {'a': a, 'b': b, 'n_tasks': len(both), 'cuts': {}}
    for cut in (25, 50, 75):
        tids = [t for t in both if idx[t]['cut_fraction'] == cut / 100]
        ea = {t: errs(a, t) for t in tids}; eb = {t: errs(b, t) for t in tids}
        d = [eb[t][0] - ea[t][0] for t in tids]
        df = [eb[t][1] - ea[t][1] for t in tids if ea[t][1] is not None and eb[t][1] is not None]
        A, B = per_agent(a, tids), per_agent(b, tids); ag = sorted(set(A) & set(B))
        pr['cuts'][cut] = {'n': len(tids), 'a_mae': round(st.mean(e for e, _ in ea.values()), 3), 'b_mae': round(st.mean(e for e, _ in eb.values()), 3),
                           'a_final_mae': round(st.mean(f for _, f in ea.values() if f is not None), 3),
                           'b_final_mae': round(st.mean(f for _, f in eb.values() if f is not None), 3),
                           'b_better_share': round(sum(x < 0 for x in d) / len(d), 3), 'tie_share': round(sum(x == 0 for x in d) / len(d), 3),
                           'p_running_best': round(signflip(d), 4), 'p_final': round(signflip(df), 4),
                           'agent_rank_rho': spearman([A[x] for x in ag], [B[x] for x in ag]), 'n_agents': len(ag)}
    res['pairs'].append(pr)
json.dump(res, open(R + 'results/v3/compare_models.json', 'w'), indent=1)
print('clean', res['clean'], '| matched five-hour tasks', len(common))
for cut, r in res['matched'].items():
    print(f"== {cut}% n={r['n']}: " + ' | '.join(f"{g} MAE {m['mae']} final {m['final_mae']}" for g, m in r['models'].items()))
for pr in res['pairs']:
    for cut, c in pr['cuts'].items():
        print(f"{pr['a']} vs {pr['b']} {cut}% n={c['n']}: MAE {c['a_mae']} vs {c['b_mae']} (b better {c['b_better_share']:.0%}, p={c['p_running_best']}) final {c['a_final_mae']} vs {c['b_final_mae']} (p={c['p_final']}) rho {c['agent_rank_rho']}")