File size: 5,036 Bytes
891c713
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score v3 forecasts (or the built-in baselines) against the private labels.

Main metric: normalized absolute error |pred - truth| / scale[fcs_task], where scale is a fixed per-FrontierCS-task
constant (population std of the official scores of all runs of that task, floor 1; metadata/task_scale.json).
Aggregation: mean over a task's scored targets -> mean over the run's tasks -> mean over runs (each run weighs the
same). Best-so-far targets and the final target are reported separately; per horizon; and on the subset of
best-so-far targets where the curve actually rose after the cut ("rose").

Usage (on della):
  python -I v3/score_v3.py --set pilot --baselines
  python -I v3/score_v3.py --set pilot --job <harbor job dir>        # reads <trial>/verifier/prediction.json
  python -I v3/score_v3.py --set pilot --preds preds.jsonl           # {"task_id":..., "predictions":[{target,score}]}
"""
import argparse, glob, json, os, statistics, sys
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
ROOT = os.environ.get('PROPHET_ROOT', '/scratch/gpfs/TRIDAO/ly3223/oraclebench').rstrip('/') + '/'


def load_preds_job(job):
    out = {}
    for cfg in glob.glob(os.path.join(job, '*', 'config.json')):
        trial = os.path.dirname(cfg)
        tid = os.path.basename(json.load(open(cfg))['task']['path'].rstrip('/'))
        p = os.path.join(trial, 'verifier', 'prediction.json')
        if os.path.exists(p):
            out[tid] = {x['target']: x['score'] for x in json.load(open(p)).get('predictions', [])}
        else:
            out[tid] = {}
    return out


def load_preds_jsonl(path):
    out = {}
    for line in open(path):
        r = json.loads(line)
        out[r['task_id']] = {x['target']: x['score'] for x in r.get('predictions', [])}
    return out


def score(preds, gt, index, scale, name):
    rows = []
    for tid, labs in gt.items():
        if tid not in preds:
            continue
        meta = index[tid]
        for l in labs:
            if l['status'] != 'ok':
                continue
            v = preds[tid].get(l['target'])
            e = 100.0 if v is None else abs(max(0.0, min(100.0, float(v))) - l['truth'])
            rows.append({'task_id': tid, 'run': f"{meta['fcs_task']}/{meta['model']}", 'target': l['target'],
                         'kind': 'final' if l['target'] == 'final' else 'best', 'rose': l.get('rose'),
                         'err': e, 'nerr': e / scale[meta['fcs_task']]})

    def run_mean(rs, key):
        by_task = defaultdict(list)
        for r in rs:
            by_task[(r['run'], r['task_id'])].append(r[key])
        by_run = defaultdict(list)
        for (run, _), v in by_task.items():
            by_run[run].append(statistics.mean(v))
        return statistics.mean(statistics.mean(v) for v in by_run.values()) if by_run else float('nan'), len(by_run)

    def block(rs):
        if not rs:
            return {'n': 0}
        m, nr = run_mean(rs, 'nerr')
        return {'n_targets': len(rs), 'n_runs': nr, 'norm_mae_run_weighted': round(m, 4),
                'mae': round(statistics.mean(r['err'] for r in rs), 3),
                'reward': round(statistics.mean(max(0, 1 - r['err'] / 10) for r in rs), 4)}

    best = [r for r in rows if r['kind'] == 'best']
    rep = {'name': name, 'n_tasks': len({r['task_id'] for r in rows}),
           'best_so_far': block(best), 'final': block([r for r in rows if r['kind'] == 'final']),
           'best_rose_only': block([r for r in best if r['rose']]),
           'share_best_targets_that_rose': round(sum(bool(r['rose']) for r in best) / max(1, len(best)), 3),
           'by_target': {t: block([r for r in rows if r['target'] == t])
                         for t in sorted({r['target'] for r in rows})}}
    return rep


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--set', default='pilot')
    ap.add_argument('--job'); ap.add_argument('--preds'); ap.add_argument('--baselines', action='store_true')
    ap.add_argument('--only', help='file of task ids to restrict to')
    a = ap.parse_args()
    md = ROOT + f'data/v3/{a.set}/metadata/'
    gt = json.load(open(md + 'ground_truth.json'))
    index = {json.loads(l)['task_id']: json.loads(l) for l in open(md + 'task_index.jsonl')}
    scale = json.load(open(md + 'task_scale.json'))
    if a.only:
        keep = set(open(a.only).read().split())
        gt = {k: v for k, v in gt.items() if k in keep}
    reps = []
    if a.baselines:
        base = json.load(open(md + 'baselines.json'))
        for b in ('hold', 'extrap'):
            reps.append(score({t: v[b] for t, v in base.items()}, gt, index, scale, 'baseline_' + b))
    if a.job:
        reps.append(score(load_preds_job(a.job), gt, index, scale, 'job:' + os.path.basename(a.job.rstrip('/'))))
    if a.preds:
        reps.append(score(load_preds_jsonl(a.preds), gt, index, scale, 'preds:' + os.path.basename(a.preds)))
    print(json.dumps(reps, indent=1))


if __name__ == '__main__':
    main()