ProseOnlyRepair_Codes / build_12variant_analysis.py
anonymous-md's picture
Initial release: anonymized evaluation analysis scripts for Repair-First paper
16667b9 verified
Raw
History Blame Contribute Delete
17.9 kB
#!/usr/bin/env python3
"""Full 12-variant analysis: 3 Cluster A MQ + 9 Cluster B (mq/hq/lq × new/repaired/repaired_upsampled).
Outputs (all to stdout, suitable for paper appendix):
Table 1 — Headline 13-metric × 12-variant matrix
Table 2 — POST+UP vs PRE within each tier (3 tier-deltas)
Table 3 — Tier ordering at each treatment (3 ordering rows × 13 metrics)
Table 4 — Repair-effect comparison across tiers (does repair help HQ as much as it helps MQ?)
Table 5 — Paloma-BPB 11-corpus × 12-variant matrix
Table 6 — Seed-variance noise floor (3 pairs: Cluster A MQ {PRE,POST,POST+UP} vs Cluster B MQ {same})
All deltas reported with per-task SE-based significance against the empirical
seed-variance noise floor measured in Table 6.
"""
from __future__ import annotations
import json, glob, math, statistics
BASE = './eval_results'
# Variant naming convention:
# - Cluster A MQ stored without prefix: 'clusterA_mq_new', 'clusterA_mq_new_repaired', 'clusterA_mq_new_repaired_upsampled'
# - Cluster B all prefixed: 'clusterB_mq_new', 'clusterB_hq_new', 'clusterB_lq_new', etc.
VARIANTS = [
# (label, suite_filename_prefix, display_name, cluster, tier, treatment)
('clusterA_mq_new', 'clusterA_mq_new', 'A-MQ-PRE', 'A', 'mq', 'pre'),
('clusterA_mq_new_repaired', 'clusterA_mq_new_repaired', 'A-MQ-POST', 'A', 'mq', 'post'),
('clusterA_mq_new_repaired_upsampled', 'clusterA_mq_new_repaired_upsampled', 'A-MQ-UP', 'A', 'mq', 'ups'),
('clusterB_mq_new', 'clusterB_mq_new', 'B-MQ-PRE', 'B', 'mq', 'pre'),
('clusterB_mq_new_repaired', 'clusterB_mq_new_repaired', 'B-MQ-POST', 'B', 'mq', 'post'),
('clusterB_mq_new_repaired_upsampled', 'clusterB_mq_new_repaired_upsampled', 'B-MQ-UP', 'B', 'mq', 'ups'),
('clusterB_hq_new', 'clusterB_hq_new', 'B-HQ-PRE', 'B', 'hq', 'pre'),
('clusterB_hq_new_repaired', 'clusterB_hq_new_repaired', 'B-HQ-POST', 'B', 'hq', 'post'),
('clusterB_hq_new_repaired_upsampled', 'clusterB_hq_new_repaired_upsampled', 'B-HQ-UP', 'B', 'hq', 'ups'),
('clusterB_lq_new', 'clusterB_lq_new', 'B-LQ-PRE', 'B', 'lq', 'pre'),
('clusterB_lq_new_repaired', 'clusterB_lq_new_repaired', 'B-LQ-POST', 'B', 'lq', 'post'),
('clusterB_lq_new_repaired_upsampled', 'clusterB_lq_new_repaired_upsampled', 'B-LQ-UP', 'B', 'lq', 'ups'),
]
METRIC_KEYS = {
'hellaswag':'acc_norm,none','piqa':'acc_norm,none','winogrande':'acc,none',
'commonsense_qa':'acc,none','social_iqa':'acc,none','openbookqa':'acc_norm,none',
'sciq':'acc_norm,none','arc_easy':'acc_norm,none','arc_challenge':'acc_norm,none',
'logiqa':'acc,none','pubmedqa':'acc,none','boolq':'acc,none','race':'acc,none',
'squadv2':'best_f1,none','coqa':'f1,none','copa':'acc,none','cb':'acc,none',
'rte':'acc,none','anli_r1':'acc,none','anli_r2':'acc,none','anli_r3':'acc,none',
'truthfulqa_mc2':'acc,none','triviaqa':'exact_match,remove_whitespace',
'nq_open':'exact_match,remove_whitespace','lambada_openai':'acc,none',
}
SCALE = {'squadv2':0.01}
def load(suite, label):
f = glob.glob(f'{BASE}/{suite}/{label}_results/results_*.json')
if not f: return {}
return json.load(open(f[0]))['results']
def numeric(x):
return x if isinstance(x,(int,float)) else 0.0
def task_value(results, task):
if task == 'mmlu_mean':
accs = [v.get('acc,none') for k,v in results.items() if k.startswith('mmlu_') and k != 'mmlu']
accs = [a for a in accs if isinstance(a,(int,float))]
return statistics.mean(accs) if accs else None
if task == 'blimp_mean':
accs = [v.get('acc,none') for k,v in results.items() if k.startswith('blimp_') and k != 'blimp']
accs = [a for a in accs if isinstance(a,(int,float))]
return statistics.mean(accs) if accs else None
key = METRIC_KEYS.get(task)
if key is None or task not in results: return None
v = results[task].get(key)
if not isinstance(v,(int,float)): return None
return v * SCALE.get(task, 1.0)
def task_se(results, task):
key = METRIC_KEYS.get(task)
if key is None or task not in results: return 0.0
se_key = key.replace(',', '_stderr,', 1)
return numeric(results[task].get(se_key)) * SCALE.get(task,1.0)
# ---- Load all data ----
data = {} # data[label_for_lookup][suite] = results dict
for lookup, prefix, _, _, _, _ in VARIANTS:
data[lookup] = {
'prose': load('prose', prefix),
'paloma': load('paloma', prefix),
}
# ---- Headline metrics list ----
HEADLINE = [
# (metric_id, display, group)
('hellaswag', 'HellaSwag', 'CS'),
('piqa', 'PIQA', 'CS'),
('winogrande', 'WinoGrande', 'CS'),
('commonsense_qa', 'CSQA', 'CS'),
('social_iqa', 'SIQA', 'CS'),
('arc_easy', 'ARC-E', 'KR'),
('arc_challenge', 'ARC-C', 'KR'),
('openbookqa', 'OpenBookQA', 'KR'),
('sciq', 'SciQ', 'KR'),
('mmlu_mean', 'MMLU-57', 'KR'),
('pubmedqa', 'PubMedQA', 'KR'),
('boolq', 'BoolQ', 'RC'),
('race', 'RACE', 'RC'),
('lambada_openai', 'LAMBADA', 'LM'),
('blimp_mean', 'BLiMP-67', 'L'),
]
def pct(v, n=2):
if v is None: return ' -- '
return f"{v*100:>{n+5}.{n}f}"
def short(label_name):
return label_name
# ============================================================================
# TABLE 1 — Headline 13-metric × 12-variant matrix
# ============================================================================
print("="*200)
print(" Table 1 — Per-variant zero-shot accuracy (%) on 15 headline prose metrics")
print(" Qwen3-1.7B, 1 epoch (iter 16 406, ~34.4 B tokens), BF16, H100, eval on standard NeMo 26.04 container, lm-eval 0.4.12")
print("="*200)
hdr = f" {'metric':<13}"
for _, _, disp, _, _, _ in VARIANTS:
hdr += f" {disp:>9}"
print(hdr)
print('-'*200)
for mid, disp, grp in HEADLINE:
line = f" {disp:<13}"
for lookup, _, _, _, _, _ in VARIANTS:
v = task_value(data[lookup]['prose'], mid)
if v is None:
line += f" {'--':>9}"
else:
line += f" {v*100:>9.2f}"
print(line)
# Paper-aligned aggregates
print('-'*200)
def fineweb_agg(results):
tasks = ['commonsense_qa','hellaswag','openbookqa','piqa','social_iqa','winogrande']
vs = [task_value(results,t) for t in tasks]
vs = [v for v in vs if v is not None]
# add arc_mean and mmlu_mean
arc_e = task_value(results,'arc_easy'); arc_c = task_value(results,'arc_challenge')
if arc_e is not None and arc_c is not None: vs.append((arc_e+arc_c)/2)
mmlu = task_value(results,'mmlu_mean')
if mmlu is not None: vs.append(mmlu)
return statistics.mean(vs) if vs else None
def dolma8_agg(results):
tasks = ['hellaswag','piqa','winogrande','openbookqa','arc_easy','arc_challenge','sciq','boolq']
vs = [task_value(results,t) for t in tasks]
vs = [v for v in vs if v is not None]
return statistics.mean(vs) if vs else None
def knowledge_agg(results):
tasks_acc = ['arc_challenge','openbookqa']
vs = [task_value(results,t) for t in tasks_acc]
mmlu = task_value(results,'mmlu_mean')
if mmlu is not None: vs.append(mmlu)
triv = task_value(results,'triviaqa')
if triv is not None: vs.append(triv)
nq = task_value(results,'nq_open')
if nq is not None: vs.append(nq)
return statistics.mean(vs) if vs else None
line = f" {'FineWeb-Agg-8':<13}"
for lookup, _, _, _, _, _ in VARIANTS:
v = fineweb_agg(data[lookup]['prose']);
line += f" {v*100:>9.2f}" if v else f" {'--':>9}"
print(line)
line = f" {'Dolma-Hdln-8':<13}"
for lookup, _, _, _, _, _ in VARIANTS:
v = dolma8_agg(data[lookup]['prose'])
line += f" {v*100:>9.2f}" if v else f" {'--':>9}"
print(line)
line = f" {'Knowledge-Agg':<13}"
for lookup, _, _, _, _, _ in VARIANTS:
v = knowledge_agg(data[lookup]['prose'])
line += f" {v*100:>9.2f}" if v else f" {'--':>9}"
print(line)
# Paloma BPB-11 mean (lower = better)
line = f" {'Paloma-BPB ↓':<13}"
for lookup, _, _, _, _, _ in VARIANTS:
palo = data[lookup]['paloma']
bpbs = [palo[t]['bits_per_byte,none'] for t in palo if 'bits_per_byte,none' in palo[t]]
v = statistics.mean(bpbs) if bpbs else None
line += f" {v:>9.4f}" if v else f" {'--':>9}"
print(line)
# ============================================================================
# TABLE 2 — Within-tier POST+UP vs PRE deltas (3 tier rows × 15 metric cols)
# ============================================================================
print()
print("="*200)
print(" Table 2 — Within-tier Δ (POST+UP − PRE) in percentage points")
print(" Each row is one data tier; positive Δ = POST+UP outperforms PRE; bold-able if |Δ| > 3 × seed_floor on that task")
print("="*200)
# Compute seed-variance noise floor per task from Cluster A MQ vs Cluster B MQ (PRE)
seed_floor = {}
for mid, disp, _ in HEADLINE:
mv = task_value(data['clusterA_mq_new']['prose'], mid)
hv = task_value(data['clusterB_mq_new']['prose'], mid)
if mv is not None and hv is not None:
seed_floor[mid] = abs(hv - mv) * 100
else:
seed_floor[mid] = 0.0
# also for paloma
seed_floor_bpb = {}
for corpus in data['clusterA_mq_new']['paloma']:
mv = data['clusterA_mq_new']['paloma'][corpus]['bits_per_byte,none']
hv = data['clusterB_mq_new']['paloma'][corpus]['bits_per_byte,none']
seed_floor_bpb[corpus] = abs(hv - mv)
tiers = [
('B-MQ', 'clusterB_mq_new', 'clusterB_mq_new_repaired_upsampled'),
('A-MQ', 'clusterA_mq_new', 'clusterA_mq_new_repaired_upsampled'),
('B-HQ', 'clusterB_hq_new', 'clusterB_hq_new_repaired_upsampled'),
('B-LQ', 'clusterB_lq_new', 'clusterB_lq_new_repaired_upsampled'),
]
hdr = f" {'tier':<10} "
for mid, disp, _ in HEADLINE: hdr += f" {disp:>9}"
hdr += f" {'FineWeb-8':>10} {'Dolma-8':>9} {'Know-Agg':>9} {'Paloma↓':>9}"
print(hdr)
print('-'*200)
for tname, pre, ups in tiers:
line = f" {tname:<10} "
for mid, _, _ in HEADLINE:
pv = task_value(data[pre]['prose'], mid); uv = task_value(data[ups]['prose'], mid)
if pv is None or uv is None:
line += f" {'--':>9}"
else:
d_pp = (uv-pv)*100
line += f" {d_pp:>+9.2f}"
# Aggregates
fw_pre = fineweb_agg(data[pre]['prose']); fw_ups = fineweb_agg(data[ups]['prose'])
do_pre = dolma8_agg(data[pre]['prose']); do_ups = dolma8_agg(data[ups]['prose'])
kn_pre = knowledge_agg(data[pre]['prose']);kn_ups = knowledge_agg(data[ups]['prose'])
# paloma mean (delta sign-inverted for "improvement" direction: lower bpb is better, so we report PRE - UP so positive = improvement)
palo_pre = statistics.mean([data[pre]['paloma'][c]['bits_per_byte,none'] for c in data[pre]['paloma']])
palo_ups = statistics.mean([data[ups]['paloma'][c]['bits_per_byte,none'] for c in data[ups]['paloma']])
line += f" {(fw_ups-fw_pre)*100:>+10.2f} {(do_ups-do_pre)*100:>+9.2f} {(kn_ups-kn_pre)*100:>+9.2f} {(palo_ups-palo_pre):>+9.4f}"
print(line)
# ============================================================================
# TABLE 3 — Tier ordering at each treatment (HQ vs MQ vs LQ at each of PRE/POST/POST+UP)
# ============================================================================
print()
print("="*200)
print(" Table 3 — Tier ordering at each treatment (Cluster B cluster; A-MQ shown as cross-cluster anchor)")
print(" Each cell = absolute zero-shot accuracy %; columns are data tier; row groups by treatment")
print("="*200)
TREATMENTS = ['PRE', 'POST', 'POST+UP']
tierset = [('LQ','clusterB_lq'), ('MQ','clusterB_mq'), ('HQ','clusterB_hq')]
sfx = {'PRE':'new', 'POST':'new_repaired', 'POST+UP':'new_repaired_upsampled'}
hdr = f" {'metric':<13} {'treat':<7} "
for tname, _ in tierset: hdr += f" {tname:>7}"
hdr += f" {'spread':>9}"
print(hdr)
print('-'*120)
for mid, disp, _ in HEADLINE:
for trt in TREATMENTS:
vals=[]
line = f" {disp:<13} {trt:<7} "
for tname, prefix in tierset:
label = f"{prefix}_{sfx[trt]}"
v = task_value(data[label]['prose'], mid)
vals.append(v)
line += f" {v*100:>7.2f}" if v is not None else f" {'--':>7}"
# spread
if all(v is not None for v in vals):
spread = (max(vals)-min(vals))*100
line += f" {spread:>9.2f}"
else:
line += f" {'--':>9}"
print(line)
print()
# ============================================================================
# TABLE 4 — Repair-effect by tier (POST+UP − PRE within each tier)
# ============================================================================
print("="*200)
print(" Table 4 — Repair-effect by tier (Δ in pp from PRE to POST+UP within each tier)")
print(" Compares whether repair is more/less effective at higher vs lower data quality")
print("="*200)
hdr = f" {'metric':<13} "
for tname in ['LQ','MQ','HQ']: hdr += f" {'Δ '+tname:>10}"
hdr += f" {'monotone?':>12}"
print(hdr)
print('-'*100)
for mid, disp, _ in HEADLINE:
line = f" {disp:<13} "
deltas = {}
for tname, prefix in [('LQ','clusterB_lq'), ('MQ','clusterB_mq'), ('HQ','clusterB_hq')]:
pre_lab = f"{prefix}_new"; ups_lab = f"{prefix}_new_repaired_upsampled"
pv = task_value(data[pre_lab]['prose'], mid); uv = task_value(data[ups_lab]['prose'], mid)
if pv is None or uv is None:
line += f" {'--':>10}"; deltas[tname] = None
else:
d = (uv-pv)*100
line += f" {d:>+10.2f}"
deltas[tname] = d
# monotone? (does Δ shrink/grow monotonically with tier quality?)
if all(deltas[t] is not None for t in ['LQ','MQ','HQ']):
if deltas['LQ'] >= deltas['MQ'] >= deltas['HQ']:
mono = 'LQ>MQ>HQ (repair helps lower-quality data more)'
elif deltas['LQ'] <= deltas['MQ'] <= deltas['HQ']:
mono = 'HQ>MQ>LQ'
else:
mono = 'non-monotone'
line += f" {mono:>40}"
print(line)
# ============================================================================
# TABLE 5 — Paloma-BPB 11-corpus × 12-variant matrix
# ============================================================================
print()
print("="*200)
print(" Table 5 — Paloma-11 BPB (bits-per-byte, lower=better) by variant")
print("="*200)
corpora = sorted(data['clusterA_mq_new']['paloma'].keys())
hdr = f" {'corpus':<32}"
for _, _, disp, _, _, _ in VARIANTS: hdr += f" {disp:>9}"
print(hdr)
print('-'*200)
for c in corpora:
name = data['clusterA_mq_new']['paloma'][c].get('alias', c)
line = f" {name:<32}"
for lookup, _, _, _, _, _ in VARIANTS:
v = data[lookup]['paloma'][c].get('bits_per_byte,none')
line += f" {v:>9.4f}" if v is not None else f" {'--':>9}"
print(line)
print('-'*200)
# Mean BPB
line = f" {'Paloma-BPB-11 mean ↓':<32}"
for lookup, _, _, _, _, _ in VARIANTS:
bpbs = [data[lookup]['paloma'][c]['bits_per_byte,none'] for c in corpora]
v = statistics.mean(bpbs)
line += f" {v:>9.4f}"
print(line)
# ============================================================================
# TABLE 6 — Seed-variance noise floor (Cluster A MQ vs Cluster B MQ at each treatment)
# ============================================================================
print()
print("="*200)
print(" Table 6 — Seed-variance noise floor measurement")
print(" Each comparison is same-tier same-treatment, different cluster + training seed.")
print(" |Δ| values are the empirical noise floor for interpreting cross-tier deltas above.")
print("="*200)
pairs = [
('PRE', 'clusterA_mq_new', 'clusterB_mq_new'),
('POST', 'clusterA_mq_new_repaired', 'clusterB_mq_new_repaired'),
('POST+UP', 'clusterA_mq_new_repaired_upsampled', 'clusterB_mq_new_repaired_upsampled'),
]
hdr = f" {'metric':<13}"
for trt,_,_ in pairs: hdr += f" |Δ| {trt:>8}"
hdr += f" {'median':>9}"
print(hdr)
print('-'*100)
all_floors = []
for mid, disp, _ in HEADLINE:
line = f" {disp:<13}"
vals=[]
for trt, mlab, hlab in pairs:
mv = task_value(data[mlab]['prose'], mid); hv = task_value(data[hlab]['prose'], mid)
if mv is None or hv is None:
line += f" {'--':>12}"
else:
d = abs(hv - mv) * 100
vals.append(d)
line += f" {d:>10.3f}pp"
med = statistics.median(vals) if vals else None
line += f" {med:>9.3f}" if med is not None else f" {'--':>9}"
print(line)
if vals: all_floors.extend(vals)
# Overall summary
print('-'*100)
print(f" Overall seed-variance noise floor on 15 headline metrics × 3 treatments:")
all_floors.sort()
print(f" median |Δ| = {statistics.median(all_floors):.3f} pp")
print(f" p75 |Δ| = {all_floors[int(len(all_floors)*0.75)]:.3f} pp")
print(f" p95 |Δ| = {all_floors[int(len(all_floors)*0.95)]:.3f} pp")
print(f" max |Δ| = {all_floors[-1]:.3f} pp")
# Paloma seed-variance
print()
print(f" Paloma BPB seed-variance (3 PRE/POST/POST+UP × 11 corpora):")
palo_floors = []
for trt, mlab, hlab in pairs:
for c in corpora:
d = abs(data[mlab]['paloma'][c]['bits_per_byte,none'] - data[hlab]['paloma'][c]['bits_per_byte,none'])
palo_floors.append(d)
palo_floors.sort()
print(f" median |Δ BPB| = {statistics.median(palo_floors):.5f}")
print(f" max |Δ BPB| = {palo_floors[-1]:.5f}")
print()
print("="*200)
print("END")
print("="*200)