Download code/builder/summarize.py from wchai/prophet-v2: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/wchai/prophet-v2/resolve/main/code/builder/summarize.py
- Command line
-
hf download hf://datasets/wchai/prophet-v2/code/builder/summarize.py
-
curl -L -o summarize.py https://huggingface.co/datasets/wchai/prophet-v2/resolve/main/code/builder/summarize.py
10.6 kB
| """Checks and metadata over out_v49/work/*.json.zst (written by v49/build.py). | |
| Writes out_v49/metadata/{ground_truth.json, task_index.json, mlsys_task_ids.txt, leak_audit.txt}, | |
| out_v49/work/{summary.json, leak_hits_d12.jsonl, leak_hits_d34.json} and prints the numbers for the report. | |
| """ | |
| import glob, json, os, statistics | |
| from collections import Counter, defaultdict | |
| import zstandard | |
| V = '<ROOT>/' | |
| OUT = V + 'build_v2/out_v49/' | |
| os.makedirs(OUT + 'metadata', exist_ok=True) | |
| works = [] | |
| for p in sorted(glob.glob(OUT + 'work/*.json.zst')): | |
| works.append(json.loads(zstandard.ZstdDecompressor().decompress(open(p, 'rb').read(), max_output_size=2 ** 32))) | |
| S = {} | |
| P = lambda *a: print(*a, flush=True) | |
| # ---------------------------------------------------------------- 1. v1 rebuild | |
| gt1 = json.load(open(V + 'data/metadata/ground_truth.json')) | |
| v1_seen_p = OUT + 'work/v1_seen.json' | |
| if not os.path.exists(v1_seen_p) and os.path.exists(V + 'build_v2/out_v48/work/v1_seen.json'): | |
| v1_seen_p = V + 'build_v2/out_v48/work/v1_seen.json' | |
| seen1 = json.load(open(v1_seen_p)) if os.path.exists(v1_seen_p) else None | |
| mine = {} | |
| for w in works: | |
| for r in w['runs']: | |
| for tid, d in r.get('v1', {}).items(): | |
| mine[tid] = d | |
| c = Counter(); ex = defaultdict(list) | |
| for tid, g in gt1.items(): | |
| if tid not in mine: | |
| c['released_not_rebuilt'] += 1; ex['released_not_rebuilt'].append(tid); continue | |
| m = mine[tid]['gt'] | |
| same = len(m) == len(g) and all(a['index'] == b['index'] and a['kind'] == b['kind'] and a['status'] == b['status'] | |
| and abs(a['score'] - b['score']) < 1e-9 for a, b in zip(m, g)) | |
| c['gt_match' if same else 'gt_mismatch'] += 1 | |
| if not same: | |
| ex['gt_mismatch'].append(tid) | |
| if seen1 is not None: | |
| if tid in seen1: | |
| ok = sorted(seen1[tid]) == sorted(mine[tid]['seen']) | |
| c['seen_match' if ok else 'seen_mismatch'] += 1 | |
| if not ok: | |
| ex['seen_mismatch'].append((tid, seen1[tid], mine[tid]['seen'])) | |
| else: | |
| c['seen_missing_in_v1_shards'] += 1 | |
| c['rebuilt_not_released'] = sum(1 for t in mine if t not in gt1) | |
| S['v1_rebuild'] = dict(c); S['v1_rebuild_examples'] = {k: v[:10] for k, v in ex.items()} | |
| P('V1 REBUILD', dict(c)); [P(' ', k, v[:5]) for k, v in ex.items()] | |
| # ---------------------------------------------------------------- delivery stats | |
| dc = Counter(); dts = defaultdict(list); runs_total = 0; runs_nodes = 0; runs_tasks = 0; errs = [] | |
| notes = Counter(); fams = Counter(); srcs = Counter(); never_seen_runs = [] | |
| run_drops = Counter(); cut_drops = Counter() | |
| for w in works: | |
| for r in w['runs']: | |
| runs_total += 1 | |
| if 'error' in r: | |
| errs.append((r['task'], r['model'])); continue | |
| fams[r['family']] += 1; srcs[r['source']] += 1 | |
| runs_nodes += r['n_nodes'] > 0; runs_tasks += len(r['tasks']) > 0 | |
| if r.get('run_drop_reason'): | |
| run_drops[r['run_drop_reason']] += 1 | |
| for dc_item in r.get('dropped_cuts', []): | |
| cut_drops[dc_item['reason']] += 1 | |
| if r['n_nodes'] > 0 and not r['tasks']: | |
| never_seen_runs.append(f"{r['task']}/{r['model']} ({r['n_nodes']} nodes, drop={r.get('run_drop_reason')})") | |
| for n in r['notes']: | |
| notes[n.split(' at ')[0].split(' (')[0]] += 1 | |
| for d in r['deliver']: | |
| k = (r['family'], d['how'], d['rel_src'] or 'no_released_time') | |
| dc[k] += 1 | |
| if d['dt_vs_released_ms'] is not None: | |
| dts[r['family']].append(d['dt_vs_released_ms'] / 1000) | |
| S['delivery'] = {' / '.join(k): v for k, v in sorted(dc.items())} | |
| S['delivery_dt_s'] = {f: {'n': len(v), 'same_time': sum(x == 0 for x in v), 'later': sum(x > 0 for x in v), | |
| 'earlier': sum(x < 0 for x in v), 'median_later_s': statistics.median([x for x in v if x > 0]) if any(x > 0 for x in v) else 0, | |
| 'max_s': max(v) if v else 0} for f, v in dts.items()} | |
| S['runs'] = {'total': runs_total, 'errors': errs, 'with_nodes': runs_nodes, 'with_v2_tasks': runs_tasks, 'families': dict(fams), | |
| 'sources': dict(srcs), 'run_drops': dict(run_drops), 'cut_drops': dict(cut_drops), | |
| 'runs_with_nodes_but_no_task': never_seen_runs, 'notes': dict(notes)} | |
| P('RUNS', S['runs']['total'], 'errors', errs, 'with nodes', runs_nodes, 'with tasks', runs_tasks, dict(fams), dict(srcs)) | |
| P('RUN_DROPS', dict(run_drops), 'CUT_DROPS', dict(cut_drops)) | |
| P('NOTES', dict(notes)); P('DELIVERY'); [P(' ', k, v) for k, v in S['delivery'].items()] | |
| # ---------------------------------------------------------------- metadata, counts | |
| tasks = sorted([t for w in works for r in w['runs'] for t in r.get('tasks', [])], key=lambda t: t['task_id']) | |
| gt = {t['task_id']: t['gt'] for t in tasks} | |
| index = [t['index_row'] for t in tasks] | |
| json.dump(gt, open(OUT + 'metadata/ground_truth.json', 'w')) | |
| json.dump(index, open(OUT + 'metadata/task_index.json', 'w'), indent=0) | |
| ml_tasks = sorted({l.strip().split('--')[0] for l in open(V + 'data/metadata/mlsys_task_ids.txt') if l.strip()}) | |
| ml_ids = sorted(t['task_id'] for t in tasks if t['index_row']['fcs_task'].replace('_', '-') in ml_tasks) | |
| open(OUT + 'metadata/mlsys_task_ids.txt', 'w').write('\n'.join(ml_ids) + '\n') | |
| nt = [len(t['gt']) for t in tasks] | |
| per_task = Counter(t['index_row']['fcs_task'] for t in tasks) | |
| S['counts'] = {'tasks': len(tasks), 'targets': sum(nt), 'targets_per_task': {'min': min(nt), 'median': statistics.median(nt), | |
| 'mean': round(sum(nt) / len(nt), 2), 'max': max(nt)}, | |
| 'pending_targets': sum(g['state_at_cut'] == 'pending' for t in tasks for g in t['gt']), | |
| 'final_targets': sum(g['kind'] == 'final' for t in tasks for g in t['gt']), | |
| 'tasks_with_final_target': sum(any(g['kind'] == 'final' for g in t['gt']) for t in tasks), | |
| 'multi_result_cuts': sum(len(t['index_row']['received_indices']) > 1 for t in tasks), | |
| 'tasks_per_fcs_task': dict(sorted(per_task.items())), 'n_fcs_tasks': len(per_task), | |
| 'tasks_per_fcs_task_minmax': [min(per_task.values()), statistics.median(per_task.values()), max(per_task.values())], | |
| 'mlsys_fcs_tasks': ml_tasks, 'mlsys_tasks': len(ml_ids), | |
| 'mlsys_targets': sum(len(gt[i]) for i in ml_ids), | |
| 'transcript_chars_median': statistics.median(t['index_row']['transcript_chars'] for t in tasks)} | |
| P('COUNTS', json.dumps({k: v for k, v in S['counts'].items() if k != 'tasks_per_fcs_task'})) | |
| # ---------------------------------------------------------------- 2. cut end checks | |
| lk = Counter(t['last_unit_kind'] for t in tasks) | |
| shows = Counter('all' if len(t['last_unit_shows']) == len(t['index_row']['received_indices']) else | |
| ('some' if t['last_unit_shows'] else 'none') for t in tasks) | |
| guard = [(t['task_id'], t['guard']) for t in tasks if t['guard']] | |
| S['cut_end'] = {'last_unit_kind': dict(lk), 'last_unit_shows_received_result': dict(shows), 'leak_guard_hits': guard} | |
| P('CUT END', dict(lk), dict(shows), 'guard', guard[:10]) | |
| # ---------------------------------------------------------------- 3. leak audit | |
| lc = Counter(); dec = Counter(); rows34 = []; f12 = open(OUT + 'work/leak_hits_d12.jsonl', 'w') | |
| nontriv = 0 | |
| for t in tasks: | |
| for lr in t['leaks']: | |
| if lr.get('trivial'): | |
| lc['trivial_0_or_100'] += 1; continue | |
| nontriv += 1 | |
| for d in lr['decoy_d']: | |
| dec[d] += 1 | |
| cats = {h[0]: h[3] for h in lr['hits']} | |
| for d in (1, 2, 3, 4): | |
| if d in cats: | |
| lc[f'd{d}_{cats[d]}'] += 1 | |
| if not lr['hits']: | |
| lc['clean_all_decimals'] += 1 | |
| un = [h for h in lr['hits'] if h[3] == 'unexplained'] | |
| if any(h[0] >= 3 for h in un): | |
| rows34.append((t['task_id'], lr, [h for h in un if h[0] >= 3])) | |
| elif un: | |
| f12.write(json.dumps({'task_id': t['task_id'], 'index': lr['index'], 'score': lr['score'], 'state': lr['state'], | |
| 'hits': un}) + '\n') | |
| f12.close() | |
| S['leak'] = {'nontrivial_targets': nontriv, 'counts': dict(sorted(lc.items())), 'decoy_hit_counts_by_d': dict(sorted(dec.items())), | |
| 'unexplained_d34_targets': len(rows34)} | |
| P('LEAK', json.dumps(S['leak'])) | |
| json.dump([(a, b, c) for a, b, c in rows34], open(OUT + 'work/leak_hits_d34.json', 'w'), indent=0) | |
| # Write leak_audit.txt summary | |
| audit_lines = [ | |
| f"v49 leak audit over {len(tasks)} tasks, {sum(nt)} targets ({nontriv} nontrivial):", | |
| f"Decoy hit counts (score +- 0.37): {dict(sorted(dec.items()))}", | |
| f"Hit counts by decimal & category: {dict(sorted(lc.items()))}", | |
| f"Unexplained 3d/4d target hits: {len(rows34)}", | |
| "" | |
| ] | |
| seen_pairs = set() | |
| for tid, lr, un in rows34: | |
| rk_t = (tid.rsplit('--r', 1)[0], lr['index']) | |
| if rk_t in seen_pairs: | |
| continue | |
| seen_pairs.add(rk_t) | |
| loc = lr.get('loc', {}) | |
| lk_k = sorted(loc.keys())[-1] if loc else '?' | |
| snip = (loc.get(lk_k) or {}).get('snippet', '') | |
| f_tag = (loc.get(lk_k) or {}).get('file', '') | |
| audit_lines.append(f"- {tid} target#{lr['index']} score={lr['score']:.6f} ({lr['state']}) hits={un} in {f_tag}: {snip[:200]}") | |
| open(OUT + 'metadata/leak_audit.txt', 'w').write('\n'.join(audit_lines) + '\n') | |
| # ---------------------------------------------------------------- 6. baselines | |
| def rw(e): return max(0.0, 1 - e / 10) | |
| B = defaultdict(lambda: defaultdict(list)) | |
| for t in tasks: | |
| b = t['baselines'] | |
| for k, g in enumerate(t['gt']): | |
| grp = ['all', 'next' if k == 0 else 'later', 'final' if g['kind'] == 'final' else 'train'] | |
| grp.append('pending' if g['state_at_cut'] == 'pending' else 'not_yet_submitted') | |
| for name in ('last_seen', 'best_seen'): | |
| e = abs(b[name] - g['score']) | |
| for gg in grp: | |
| B[name][gg].append(e) | |
| TR = defaultdict(list) | |
| for t in tasks: | |
| for name in ('last_seen', 'best_seen'): | |
| es = [abs(t['baselines'][name] - g['score']) for g in t['gt']] | |
| TR[name].append(sum(rw(e) for e in es) / len(es)) | |
| S['baselines'] = {name: {gg: {'n': len(es), 'reward': round(sum(rw(e) for e in es) / len(es), 4), 'mae': round(sum(es) / len(es), 3), | |
| 'within_0.5': round(sum(e <= 0.5 for e in es) / len(es), 4)} | |
| for gg, es in B[name].items()} for name in B} | |
| for name in TR: | |
| S['baselines'][name]['task_mean_reward'] = round(sum(TR[name]) / len(TR[name]), 4) | |
| P('BASELINES', json.dumps(S['baselines'], indent=1)) | |
| json.dump(S, open(OUT + 'work/summary.json', 'w'), indent=1) | |