Download code/builder/sample_v2.py from wchai/prophet-v2: direct link, hf CLI and curl.
- Browser
- Download file 7.58 kB
-
https://huggingface.co/datasets/wchai/prophet-v2/resolve/main/code/builder/sample_v2.py
- Command line
-
hf download hf://datasets/wchai/prophet-v2/code/builder/sample_v2.py
-
curl -L -o sample_v2.py https://huggingface.co/datasets/wchai/prophet-v2/resolve/main/code/builder/sample_v2.py
7.58 kB
| """Draw the v2 run sample and post-process it (owner decisions in docs/STATUS.md, 2026-12-02/03). | |
| Sample: one FrontierCS task per category (the task with the most runs; ties broken by random seed 0), every run of | |
| it, 3 cuts per run: the received scores at positions round(q * (n - 1)) for q = 1/6, 1/2, 5/6 of the run's n v2 tasks | |
| (all of them when n < 3). | |
| Post-process each sampled task: | |
| - train targets: keep only submissions whose status is "passed"; the instruction says every listed train | |
| submission passed; | |
| - the final is always a target, truth = the run's official score (0 if it failed or was never made); the | |
| instruction says only that it is scored on hidden workloads and that a failure scores 0. A task whose run made | |
| no final submission is dropped: any wording for a final that was never made reveals its truth 0 (v2 audit S_post). | |
| Output: build_v2/sample/tasks/<task_id>/ (extracted), build_v2/sample/{ids.txt,ground_truth.json,sample.json}. | |
| python3 -I build_v2/sample_v2.py [--build build_v2/out_v48] | |
| """ | |
| import argparse, collections as C, io, json, math, os, random, re, shutil, tarfile, sys | |
| import subprocess | |
| V = '<SCRATCH>' | |
| NOTE = ('Every train submission listed below passed verification. The final submission is scored on hidden ' | |
| 'workloads; a final that fails scores 0.') | |
| def zread(path): | |
| return io.BytesIO(subprocess.run(['zstd', '-dc', path], capture_output=True, check=True).stdout) | |
| def choose(index): | |
| runs = C.defaultdict(set) | |
| cat = {} | |
| for r in index: | |
| runs[r['fcs_task']].add(r['model']) | |
| cat[r['fcs_task']] = r['category'] | |
| rng = random.Random(0) | |
| picks = {} | |
| for c in sorted(set(cat.values())): | |
| ts = sorted(t for t in cat if cat[t] == c) | |
| best = max(len(runs[t]) for t in ts) | |
| top = [t for t in ts if len(runs[t]) == best] | |
| picks[c] = rng.choice(top) if len(top) > 1 else top[0] | |
| return picks | |
| def cuts(rows): | |
| rows = sorted(rows, key=lambda r: r['cut_result_index']) | |
| n = len(rows) | |
| if n < 3: | |
| return rows | |
| pos = sorted({int(math.floor(q * (n - 1) + 0.5)) for q in (1 / 6, 1 / 2, 5 / 6)}) # half up (audit G) | |
| return [rows[p] for p in pos] | |
| class NoFinal(Exception): | |
| pass | |
| def post(files, tid): | |
| """Rewrite targets.json, tests/ground_truth.json and instruction.md of one task (dict path -> bytes).""" | |
| gt = json.loads(files[f'{tid}/tests/ground_truth.json']) | |
| tj = json.loads(files[f'{tid}/environment/context/targets.json']) | |
| ins = files[f'{tid}/instruction.md'].decode() | |
| keep, added = [], None | |
| for t in gt['targets']: | |
| if t['kind'] == 'final' or t.get('status') == 'passed': | |
| keep.append(t) | |
| if not any(t['kind'] == 'final' for t in keep): | |
| raise NoFinal(tid) | |
| idx = max([t['index'] for t in gt['targets']] + [-1]) + 1 | |
| added = {'index': idx, 'kind': 'final', 'score': 0.0, 'status': 'not_made', | |
| 'state_at_cut': 'not_yet_submitted', 'submitted_min_after_cut': None} | |
| keep.append(added) | |
| ki = {t['index'] for t in keep} | |
| gt['targets'] = keep | |
| tj = [t for t in tj if t['index'] in ki] | |
| if added: | |
| tj.append({'index': added['index'], 'kind': 'final', 'state_at_cut': 'not_yet_submitted', | |
| 'submitted_min_after_cut': None, 'submitted_at_elapsed': 'at the end of the run'}) | |
| lines = ins.split('\n') | |
| out = [] | |
| for ln in lines: | |
| m = re.match(r'- Submission (\d+) ', ln) | |
| if m and int(m.group(1)) not in ki: | |
| continue | |
| out.append(ln) | |
| ins = '\n'.join(out) | |
| if added: | |
| tail = f'- Submission {added["index"]} (final, hidden workloads), at the end of the run: score?' | |
| last = max(i for i, l in enumerate(ins.split('\n')) if l.startswith('- Submission ')) if '- Submission ' in ins else None | |
| L = ins.split('\n') | |
| if last is None: | |
| raise ValueError(f'{tid}: no target lines') | |
| L.insert(last + 1, tail) | |
| ins = '\n'.join(L) | |
| # the note goes right before the first target line | |
| L = ins.split('\n') | |
| first = next(i for i, l in enumerate(L) if l.startswith('- Submission ')) | |
| L.insert(first, NOTE + '\n') | |
| ins = '\n'.join(L) | |
| ex = ', '.join(f'{{"index": {t["index"]}, "score": <number>}}' for t in sorted(keep, key=lambda t: t['index'])) | |
| ins, n = re.subn(r'\{"predictions": \[.*?\], "rationale"', '{"predictions": [' + ex + '], "rationale"', ins) | |
| if n != 1: | |
| raise ValueError(f'{tid}: JSON example not found') | |
| files[f'{tid}/tests/ground_truth.json'] = json.dumps(gt, indent=1).encode() | |
| oracle = {'predictions': [{'index': t['index'], 'score': t['score']} for t in sorted(keep, key=lambda t: t['index'])], | |
| 'rationale': 'oracle'} | |
| files[f'{tid}/solution/solve.sh'] = ("#!/bin/bash\ncat > /app/prediction.json <<'EOF'\n" + json.dumps(oracle) | |
| + "\nEOF\n").encode() | |
| files[f'{tid}/environment/context/targets.json'] = json.dumps(tj, indent=1).encode() | |
| files[f'{tid}/instruction.md'] = ins.encode() | |
| tt = files[f'{tid}/task.toml'].decode() | |
| tt, k = re.subn(r'(?m)^n_targets\s*=\s*\d+', f'n_targets = {len(keep)}', tt) | |
| files[f'{tid}/task.toml'] = tt.encode() | |
| return gt | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument('--build', default=f'{V}/build_v2/out_v48') | |
| ap.add_argument('--out', default=f'{V}/build_v2/sample') | |
| a = ap.parse_args() | |
| index = json.load(open(f'{a.build}/metadata/task_index.json')) | |
| picks = choose(index) | |
| by_run = C.defaultdict(list) | |
| for r in index: | |
| if r['fcs_task'] in picks.values(): | |
| by_run[(r['fcs_task'], r['model'])].append(r) | |
| chosen = {r['task_id']: r for rows in by_run.values() for r in cuts(rows)} | |
| os.makedirs(f'{a.out}/tasks', exist_ok=True) | |
| GT, n_files, nofinal = {}, 0, [] | |
| for fcs in sorted(picks.values()): | |
| shard = f'{a.build}/tasks/{fcs}.tar.zst' | |
| want = {t for t, r in chosen.items() if r['fcs_task'] == fcs} | |
| files = {} | |
| with tarfile.open(fileobj=zread(shard)) as tf: | |
| for m in tf: | |
| top = m.name.split('/', 1)[0] | |
| if top in want and m.isfile(): | |
| files[m.name] = tf.extractfile(m).read() | |
| for tid in sorted(want): | |
| try: | |
| gt = post(files, tid) | |
| except NoFinal: | |
| nofinal.append(tid) | |
| for k in [k for k in files if k.split('/', 1)[0] == tid]: | |
| del files[k] | |
| continue | |
| GT[tid] = gt['targets'] | |
| for name, data in files.items(): | |
| p = os.path.join(a.out, 'tasks', name) | |
| os.makedirs(os.path.dirname(p), exist_ok=True) | |
| open(p, 'wb').write(data) | |
| n_files += 1 | |
| missing = want - {n.split('/', 1)[0] for n in files} - set(nofinal) | |
| if missing: | |
| print('MISSING in shard', fcs, sorted(missing)[:5], file=sys.stderr) | |
| ids = sorted(GT) | |
| open(f'{a.out}/ids.txt', 'w').write('\n'.join(ids) + '\n') | |
| json.dump(GT, open(f'{a.out}/ground_truth.json', 'w')) | |
| nt = [len(v) for v in GT.values()] | |
| summary = {'picks': picks, 'runs': len(by_run), 'tasks': len(ids), 'targets': sum(nt), | |
| 'targets_per_task': {'min': min(nt), 'median': sorted(nt)[len(nt) // 2], 'max': max(nt)}, | |
| 'files_written': n_files, 'dropped_no_final': nofinal} | |
| json.dump(summary, open(f'{a.out}/sample.json', 'w'), indent=1) | |
| print(json.dumps(summary, indent=1)) | |
| if __name__ == '__main__': | |
| main() | |