File size: 22,094 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
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
283
284
285
286
287
288
289
290
291
292
293
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
341
342
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
"""Prophet v3: forecast the best-so-far train score at fixed times after a budget-fraction cut, plus the official
final score.

Design (see v3/README.md):
- Cuts are at fixed fractions (FRACS) of the run's declared answering window B, measured from the first trace unit
  (t0). B is read from the run's own prompt in its first BUDGET_SCAN_S seconds, else DEFAULT_BUDGET_S.
- A (run, fraction) is eligible iff, using only events at or before the cut T: the agent has received at least one
  valid train score and has not submitted a final. Nothing after T is consulted for eligibility or for any public
  file.
- Public files are rendered by `render_public(prefix)` from a Prefix object that holds only data at or before T
  (`make_prefix`). Labels come from `make_labels`, which reads the whole run and is never passed to the renderer.
- Targets: best-so-far at T+15, +30, +60, +120 min (only those strictly before the deadline t0+B) and at the
  deadline; plus the official final score.

Usage:
  .venv/bin/python -I v3/build_v3.py --set pilot  [--jobs 6]     # v2-pilot runs + 40 held-out runs
  .venv/bin/python -I v3/build_v3.py --set full   [--jobs 6]     # all 1,535 runs
Output: data/v3/<set>/{tasks,tasks_sched}/<task_id>/, data/v3/<set>/metadata/*.json
"""
import argparse, json, math, os, random, re, shutil, statistics, sys, traceback
from collections import Counter, defaultdict
from multiprocessing import Pool

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import v49lib as L  # noqa: E402  v2 (v49) loader, delivery and rendering rules, unchanged except local paths
import vis_v3 as VB  # noqa: E402  score-blind visibility (public side)
BT = L.BT

ROOT = L.V
FR = ROOT + 'data/hf_raw/metadata/formal-results.json'
OUT = ROOT + 'data/v3/'
V2_PILOT = ROOT + 'data/prophet_v2/results/pilot_v2/results.jsonl'

# ------------------------------------------------------------------ pre-declared configuration
FRACS = (0.25, 0.50, 0.75)
GRID_MIN = (15, 30, 60, 120)
BUDGET_SCAN_S = 900                      # the window is stated in the opening prompt
DEFAULT_BUDGET_S = 18000
TASK_DEFAULT_BUDGET_S = {'lrr': 7200}    # lrr's majority statement; used only when a run states none
BUDGET_RX = re.compile(r'answering window is \*\*([^*]{1,60})\*\*')
SECONDS_RX = re.compile(r'([\d,]+)\s*(?:seconds|s\b)')
HOURS_RX = re.compile(r'(\d+(?:\.\d+)?)\s*hours?')
MIN_BUDGET_S = 3600                      # a statement below this is not a window statement
N_HELDOUT = 40
SEED = 0

# final-score provenance -> label status (official 'score' from formal-results.json)
FINAL_MISSING = ('final verification did not complete', 'model provider refused')

TASK_TOML = '''schema_version = "1.4"
artifacts = []

[metadata]
benchmark = "frontiercs2-score-forecast"
design = "v3-best-so-far-at-fixed-times"
fcs_task = "{task}"
fcs_model = "{model}"
cut_fraction = {frac}
budget_seconds = {budget}
category = "{cat}"
n_targets = {nt}

[verifier]
timeout_sec = 120.0
environment_mode = "shared"

[agent]
timeout_sec = 1800.0
''' + BT.ENV_DOCKER

INSTRUCTION = """# Forecast how far an AI agent's best score will climb

You are watching an AI coding agent work on a research-engineering task from the **FrontierCS 2**
benchmark. The agent iterates: it edits code and submits payloads to a *train* verifier, which
returns a score on train workloads (0-100, higher is better). It has an answering window of
**{budget_h}** ({budget_s:,} seconds) from the start of the run. At the end it selects one *final*
payload, which is scored on **hidden** workloads; that is the run's official score.

The run has been cut at **{elapsed}** into the run ({pct}% of the answering window). Everything the
agent had seen by then is in `/app/context/`:

- `run_info.json` - task, category, paper, the agent (model + harness), the window, the cut.
- `transcript.md` - the agent's conversation up to the cut (model inputs/outputs, tool calls and
  tool results, in time order; long items are truncated in the middle).
- `submissions.json` - every submission made before the cut: its index, kind and when it was
  made. Any results the agent had received are in the transcript, as the agent saw them.
- `submissions/<i>/` - the files of every submission made before the cut.
- `targets.json` - the quantities you must forecast.

**Best-so-far** at a moment t is the highest score among the *passed* train results the agent has
received by t, counting the results it had already received before the cut (they are in the
transcript). It can only stay level or rise: a result counts from the moment the agent receives
it (a submission still awaiting its result at the cut counts once the result arrives), and if the
agent stops early or nothing better arrives, it stays where it was. You are not told whether,
when or how often the agent submits after the cut.

## Rules

- Use only the files in `/app/context/`. No network, no web search, and do not try to find this
  run, its dataset, or the paper's results anywhere else.
- Forecast by reading and reasoning. Think as long as you need: compare the submissions, read what
  the agent tried and what it observed, and weigh the score history. Small calculations over the
  context (diffs, greps, averages, trend fits) are fine.
- Do not solve the task end to end: do not build, install or run the submitted code or the task,
  do not re-implement or improve the solution, and do not write benchmarks or simulations to
  measure a score.
- Do not modify `/app/context/`.

## Your job

Predict:

{targets_md}

Write `/app/prediction.json` exactly in this form (numbers on the 0-100 scale):

```json
{{"predictions": [{pred_example}], "rationale": "<a few sentences>"}}
```

You are graded on absolute error per target (reward = mean over targets of max(0, 1 - |error| / 10)).
"""

SCHED_APPENDIX = """
## Schedule of the rest of the run (ablation variant)

After the cut the agent made these submissions (minutes after the cut; whether each passed is not
shown):

{lines}
"""


def fmt_h(sec):
    h = sec / 3600
    return f'{h:g} hours' if h != 1 else '1 hour'


# ------------------------------------------------------------------ run analysis (full data; detection only)
def analyze(run):
    """Load the run and compute, for every train node, the unit index from which the agent had its result (VIS).
    Same rules as v2's build.py (strict delivery + earlier echo)."""
    fam, U, N, P, _ = L.load_run(run)
    return fam, U, N, P, compute_vis(fam, U, N)


def compute_vis(fam, U, N):
    """{'pub': score-blind visibility (public side), 'lab': earliest of score-blind and v2 score-aware (labels)}."""
    pub = VB.compute_vis_blind(fam, U, N)
    v2 = compute_vis_v2(fam, U, N)
    lab = {}
    for i in set(pub) | set(v2):
        c = [x for x in (pub.get(i), v2.get(i)) if x is not None]
        lab[i] = min(c) if c else None
    return {'pub': pub, 'lab': lab}


def compute_vis_v2(fam, U, N):
    pre = L.precompute_units(U, fam) if U else None
    VIS = {}
    for n in N:
        if n['mode'] != 'train' or L.is_d3(n):
            continue
        i, _how = L.deliver_index(n, U, fam, N=N, pre=pre)
        if L.is_d4(n):
            VIS[n['idx']] = i
            continue
        e = L.echo_index(n, U, fam, N=N)
        VIS[n['idx']] = e if (e is not None and (i is None or e < i)) else i
    return VIS


def budget_of(run, U):
    t0 = U[0]['t']
    for u in U:
        if u['t'] - t0 > BUDGET_SCAN_S * 1000:
            break
        if u['kind'] in ('assistant', 'response'):
            continue
        for m in BUDGET_RX.finditer(u['text']):
            g = m.group(1)
            sm, hm = SECONDS_RX.search(g), HOURS_RX.search(g)
            sec = int(sm.group(1).replace(',', '')) if sm else (int(float(hm.group(1)) * 3600) if hm else None)
            if sec is not None and sec >= MIN_BUDGET_S:
                return sec, 'stated'
    return TASK_DEFAULT_BUDGET_S.get(run['task'], DEFAULT_BUDGET_S), 'default'


def valid_score(n):
    """A train result that enters best-so-far: passed with a numeric score."""
    if n['mode'] != 'train' or L.is_d3(n) or L.is_d4(n) or n.get('status') != 'passed':
        return None
    s = n.get('raw_score')
    return float(s) if isinstance(s, (int, float)) and not isinstance(s, bool) else None


# ------------------------------------------------------------------ prefix (public side)
def make_prefix(run, fam, U, N, P, VIS, frac):
    """Everything the predictor may see, built only from events at or before the cut T.
    Returns (prefix or None, exclusion reason)."""
    if not U:
        return None, 'no_trace_units'
    t0 = U[0]['t']
    B, bsrc = budget_of(run, U)
    T = t0 + int(frac * B * 1000)
    K = max(i for i, u in enumerate(U) if u['t'] <= T) if U[0]['t'] <= T else -1
    made = [n for n in N if n['t_submit'] <= T]
    if any(n['mode'] == 'final' for n in made):
        return None, 'final_submitted_before_cut'
    pub = VIS['pub']
    # eligibility: a passed, scored train result delivered (score-blind rule) at or before the cut
    if not any(pub.get(n['idx']) is not None and pub[n['idx']] <= K and valid_score(n) is not None for n in made):
        return None, 'no_valid_score_received_by_cut'
    subs = [{'index': n['idx'], 'kind': n['mode'], 'submitted_at': BT.fmt_dt(n['t_submit'] - t0),
             'files': f"submissions/{n['idx']}/" if P.get(n['idx']) else None} for n in made]
    D = t0 + B * 1000
    grid = [(f'best_+{m}m', T + m * 60000) for m in GRID_MIN if T + m * 60000 < D] + [('best_deadline', D)]
    return {
        'run': {k: run.get(k) for k in ('task', 'model_id', 'candidate_name')},
        'fam': fam, 't0': t0, 'T': T, 'K': K, 'B': B, 'budget_source': bsrc, 'D': D, 'frac': frac,
        'units': U[:K + 1], 'made': made, 'subs': subs, 'payloads': {n['idx']: P.get(n['idx'], {}) for n in made},
        'grid': grid,
    }, None


def task_id(task, model, frac):
    return f'{task}--{model}--p{int(round(frac * 100)):02d}'.replace('_', '-').lower()


def render_public(pf, tmeta, sched_lines=None):
    """{relative path: bytes} of every file the predictor or its harness receives. Reads only `pf`."""
    run, t0, T = pf['run'], pf['t0'], pf['T']
    targets = []
    for name, g in pf['grid']:
        targets.append({'target': name, 'kind': 'best_so_far', 'at_minutes_after_cut': L.minutes(g - T),
                        'at_elapsed': L.fmt_hm(g - t0),
                        'at': 'end of the answering window' if name == 'best_deadline' else f'{L.minutes(g - T)} min after the cut'})
    targets.append({'target': 'final', 'kind': 'official_final_score'})
    lines = []
    for t in targets:
        if t['kind'] == 'best_so_far':
            lines.append(f"- `{t['target']}`: best-so-far at {t['at']} ({t['at_elapsed']} into the run)")
        else:
            lines.append('- `final`: the official score of the run: its selected final payload scored on the '
                         'hidden workloads (0 if the agent never submits a final)')
    ex = ', '.join(f'{{"target": "{t["target"]}", "score": <number>}}' for t in targets)
    instr = INSTRUCTION.format(budget_h=fmt_h(pf['B']), budget_s=pf['B'], elapsed=L.fmt_hm(T - t0),
                               pct=int(round(pf['frac'] * 100)), targets_md='\n'.join(lines),
                               pred_example=ex)
    if sched_lines is not None:
        instr += SCHED_APPENDIX.format(lines='\n'.join(sched_lines) if sched_lines else '- (none)')
    info = {'benchmark': 'FrontierCS 2', 'task': run['task'],
            'task_display_name': tmeta.get('display_name'), 'category': tmeta.get('category'),
            'paper_title': tmeta.get('paper_title'), 'agent': run['candidate_name'], 'model_id': run['model_id'],
            'answering_window_seconds': pf['B'], 'elapsed_at_cut': BT.fmt_dt(T - t0),
            'cut_fraction_of_window': pf['frac'], 'submissions_so_far': len(pf['made'])}
    files = {
        'instruction.md': instr.encode(),
        'task.toml': TASK_TOML.format(task=run['task'], model=run['model_id'], frac=pf['frac'], budget=pf['B'],
                                      cat=tmeta.get('category', ''), nt=len(targets)).encode(),
        'environment/Dockerfile': BT.DOCKERFILE.encode(),
        'environment/context/transcript.md': L.render_upto(pf['units'], len(pf['units']) - 1, t0).encode(),
        'environment/context/submissions.json': json.dumps(pf['subs'], indent=1).encode(),
        'environment/context/run_info.json': json.dumps(info, indent=1).encode(),
        'environment/context/targets.json': json.dumps(targets, indent=1).encode(),
    }
    for n in pf['made']:
        for name, data in sorted(pf['payloads'][n['idx']].items()):
            files[f'environment/context/submissions/{n["idx"]}/{name}'] = data
    return files, targets


# ------------------------------------------------------------------ labels (private side; full run)
def receive_log(U, N, VIS):
    """(time received, score, index) of every passed, scored train result, from the label-side visibility."""
    lab = VIS['lab']
    return sorted((U[lab[n['idx']]]['t'], valid_score(n), n['idx']) for n in N
                  if lab.get(n['idx']) is not None and valid_score(n) is not None)


def make_labels(run, fam, U, N, VIS, pf):
    """Truth for every target, from the full run (private side).
    best-so-far(g) = max score among passed train results the agent received at or before g (score-aware v2 rule
    or score-blind rule, whichever is earlier); 0 if none. A grid time after the log's last event is known only
    when the agent's stop is known (it submitted a final, or the platform says it ended without one); otherwise
    the label is missing."""
    recv = receive_log(U, N, VIS)
    log_end = U[-1]['t']
    rs = run.get('result_source') or ''
    stop_known = L.has_trace_final(N) or (rs.startswith('no final submission') and 'provider refused' not in rs)
    best_cut = max([s for t, s, _ in recv if t <= pf['T']], default=0.0)
    out = []
    for name, g in pf['grid']:
        lab = {'target': name, 'truth': max([s for t, s, _ in recv if t <= g], default=0.0), 'status': 'ok'}
        if g > log_end and not stop_known:
            lab.update(status='missing', reason='log_ends_before_target_time')
        lab['rose'] = lab['truth'] > best_cut + 1e-9
        out.append(lab)
    fin = {'target': 'final', 'truth': float(run.get('score') or 0.0), 'status': 'ok', 'result_source': rs}
    if any(k in rs for k in FINAL_MISSING):
        fin.update(status='missing', reason=rs)
    out.append(fin)
    return out, best_cut


def baselines(U, N, VIS, pf):
    """Grader-side baselines from what the agent had received by the cut (label-side visibility, times <= T).
    hold: best-so-far stays at its cut value. extrap: best-so-far modeled as a + b*ln(elapsed), fitted through the
    first received score and the best at the cut, continued to each target time and capped at 100 (concave, so
    it slows down like most runs do). Both predict final = their deadline value."""
    T, t0 = pf['T'], pf['t0']
    hist = [(t, s) for t, s, _ in receive_log(U, N, VIS) if t <= T]
    best = max([s for _, s in hist], default=0.0)
    hold = {name: best for name, _ in pf['grid']}
    if hist and hist[0][0] > t0 and T > hist[0][0]:
        t1, s1 = hist[0]
        b = (best - s1) / math.log((T - t0) / (t1 - t0))
    else:
        b = 0.0
    ext = {name: min(100.0, best + b * math.log((g - t0) / (T - t0))) for name, g in pf['grid']}
    hold['final'], ext['final'] = best, ext['best_deadline']
    return {'hold': hold, 'extrap': ext}


def schedule_lines(N, pf):
    """Ablation only: the post-cut submission schedule (what v2's target list exposed)."""
    T = pf['T']
    return [f"- submission {n['idx']} ({'final' if n['mode'] == 'final' else 'train'}): "
            f"{L.minutes(n['t_submit'] - T)} min after the cut" for n in N if n['t_submit'] > T]


# ------------------------------------------------------------------ one run
def one(args):
    run, tmeta, want_sched = args
    res = {'task': run['task'], 'model': run['model_id'], 'tasks': [], 'excluded': []}
    try:
        fam, U, N, P, VIS = analyze(run)
    except Exception:
        res['error'] = traceback.format_exc()[-1500:]
        return res
    for frac in FRACS:
        pf, why = make_prefix(run, fam, U, N, P, VIS, frac)
        tid = task_id(run['task'], run['model_id'], frac)
        if pf is None:
            res['excluded'].append({'task_id': tid, 'reason': why})
            continue
        files, targets = render_public(pf, tmeta)
        labels, best_cut = make_labels(run, fam, U, N, VIS, pf)
        sched = render_public(pf, tmeta, schedule_lines(N, pf))[0] if want_sched else None
        res['tasks'].append({
            'task_id': tid, 'files': files, 'files_sched': sched, 'labels': labels, 'baselines': baselines(U, N, VIS, pf),
            'index_row': {'task_id': tid, 'fcs_task': run['task'], 'model': run['model_id'],
                          'category': tmeta.get('category'), 'cut_fraction': frac, 'budget_s': pf['B'],
                          'budget_source': pf['budget_source'], 'elapsed_at_cut_s': (pf['T'] - pf['t0']) // 1000,
                          'n_submissions_at_cut': len(pf['made']), 'best_at_cut': best_cut,
                          'n_targets': len(targets), 'family': fam,
                          'transcript_chars': len(files['environment/context/transcript.md'])},
        })
    return res


# ------------------------------------------------------------------ grader, oracle and writing
def write_task(base, t, files):
    d = os.path.join(base, t['task_id'])
    for rel, data in files.items():
        p = os.path.join(d, rel)
        os.makedirs(os.path.dirname(p), exist_ok=True)
        open(p, 'wb').write(data)
    os.makedirs(os.path.join(d, 'tests'), exist_ok=True); os.makedirs(os.path.join(d, 'solution'), exist_ok=True)
    shutil.copy(os.path.join(HERE, 'grade_v3.py'), os.path.join(d, 'tests', 'grade.py'))
    shutil.copy(os.path.join(HERE, 'test.sh'), os.path.join(d, 'tests', 'test.sh'))
    os.chmod(os.path.join(d, 'tests', 'test.sh'), 0o755)
    json.dump({'targets': t['labels']}, open(os.path.join(d, 'tests', 'ground_truth.json'), 'w'), indent=1)
    sol = {'predictions': [{'target': l['target'], 'score': l['truth']} for l in t['labels']], 'rationale': 'oracle'}
    p = os.path.join(d, 'solution', 'solve.sh')
    open(p, 'w').write("#!/bin/bash\ncat > /app/prediction.json <<'EOF'\n" + json.dumps(sol) + "\nEOF\n")
    os.chmod(p, 0o755)


def pick_runs(runs, which):
    if which == 'full':
        return runs, {r['record_id']: 'full' for r in runs}
    pilot = set()
    for line in open(V2_PILOT):
        tid = json.loads(line)['task_id']
        task, model, _ = tid.split('--')
        pilot.add((task, model))
    by = {(r['task'].replace('_', '-'), r['model_id']): r for r in runs}
    a = [by[k] for k in sorted(pilot)]
    rest = sorted((r for r in runs if (r['task'].replace('_', '-'), r['model_id']) not in pilot),
                  key=lambda r: r['record_id'])
    b = random.Random(SEED).sample(rest, N_HELDOUT)
    role = {r['record_id']: 'v2_pilot_run' for r in a}
    role.update({r['record_id']: 'heldout' for r in b})
    return a + b, role


def task_scales(fr):
    by = defaultdict(list)
    for r in fr['runs']:
        by[r['task']].append(float(r.get('score') or 0.0))
    return {t: max(1.0, statistics.pstdev(v)) for t, v in by.items()}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--set', default='pilot', choices=['pilot', 'full'])
    ap.add_argument('--jobs', type=int, default=6)
    a = ap.parse_args()
    fr = json.load(open(FR))
    tm = {t['task']: t for t in fr['tasks']}
    runs, role = pick_runs(fr['runs'], a.set)
    out = OUT + a.set + '/'
    for sub in ('tasks', 'tasks_sched', 'metadata'):
        shutil.rmtree(out + sub, ignore_errors=True)
        os.makedirs(out + sub)
    want_sched = a.set == 'pilot'
    work = [(r, tm.get(r['task'], {}), want_sched) for r in sorted(runs, key=lambda r: -(r.get('trace_size_bytes') or 0))]
    index, gt, base, excl, errs = [], {}, {}, [], []
    with Pool(a.jobs, maxtasksperchild=8) as p:
        for k, res in enumerate(p.imap_unordered(one, work)):
            if 'error' in res:
                errs.append(res); print('ERR', res['task'], res['model'], res['error'][-300:], flush=True)
            rid = f"{res['task']}/{res['model']}"
            for e in res['excluded']:
                excl.append(dict(e, record_id=rid, role=role.get(rid)))
            for t in res['tasks']:
                write_task(out + 'tasks', t, t['files'])
                if t['files_sched'] is not None:
                    write_task(out + 'tasks_sched', t, t['files_sched'])
                index.append(dict(t['index_row'], role=role.get(rid)))
                gt[t['task_id']] = t['labels']
                base[t['task_id']] = t['baselines']
            if k % 50 == 0:
                print(f'{k + 1}/{len(work)} runs, {len(index)} tasks', flush=True)
    index.sort(key=lambda r: r['task_id'])
    md = out + 'metadata/'
    with open(md + 'task_index.jsonl', 'w') as f:
        for r in index:
            f.write(json.dumps(r) + '\n')
    json.dump(gt, open(md + 'ground_truth.json', 'w'), indent=1, sort_keys=True)
    json.dump(base, open(md + 'baselines.json', 'w'), indent=1, sort_keys=True)
    json.dump(task_scales(fr), open(md + 'task_scale.json', 'w'), indent=1, sort_keys=True)
    json.dump({'excluded': sorted(excl, key=lambda e: e['task_id']), 'errors': errs,
               'counts': Counter(e['reason'] for e in excl)}, open(md + 'exclusions.json', 'w'), indent=1)
    json.dump({'set': a.set, 'fracs': FRACS, 'grid_min': GRID_MIN, 'seed': SEED, 'n_heldout': N_HELDOUT,
               'runs': sorted(role.items())}, open(md + 'sample.json', 'w'), indent=1)
    print('runs', len(runs), 'tasks', len(index), 'excluded', dict(Counter(e['reason'] for e in excl)),
          'errors', len(errs))


if __name__ == '__main__':
    main()