#!/usr/bin/env python3 """Build paper-aligned aggregate tables from prose-28 + Paloma-11 evaluation JSONs. Produces: - Per-task table with correct metric extraction (POST+UP vs PRE, with SE / Z) - Five paper-aligned aggregates: FineWeb-8, DCLM-Core-18, Dolma-Headline, Nemotron-CC, Paloma-BPB-11 - Three hypothesis-aligned diagnostic aggregates: Knowledge, Fluency, Narrative-Tax """ from __future__ import annotations import json import glob import math import statistics import sys BASE = './eval_results' PROSE_DIR = f'{BASE}/prose' PALOMA_DIR = f'{BASE}/paloma' # ---- Per-task metric & random-baseline map --------------------------------- # (primary_key, fallback_key_or_None, scale_to_01, random_baseline_for_centered_acc) TASK_SPEC = { 'hellaswag': ('acc_norm,none', None, 1.0, 0.25), 'piqa': ('acc_norm,none', None, 1.0, 0.50), 'winogrande': ('acc,none', None, 1.0, 0.50), 'commonsense_qa': ('acc,none', None, 1.0, 0.20), 'social_iqa': ('acc,none', None, 1.0, 1/3), 'openbookqa': ('acc_norm,none', None, 1.0, 0.25), 'sciq': ('acc_norm,none', None, 1.0, 0.25), 'arc_easy': ('acc_norm,none', None, 1.0, 0.25), 'arc_challenge': ('acc_norm,none', None, 1.0, 0.25), 'logiqa': ('acc,none', None, 1.0, 0.25), 'pubmedqa': ('acc,none', None, 1.0, 1/3), 'boolq': ('acc,none', None, 1.0, 0.50), 'race': ('acc,none', None, 1.0, 0.25), 'squadv2': ('best_f1,none', None, 0.01, 0.0), # already 0-100 'coqa': ('f1,none', None, 1.0, 0.0), 'copa': ('acc,none', None, 1.0, 0.50), 'cb': ('acc,none', None, 1.0, 1/3), 'rte': ('acc,none', None, 1.0, 0.50), 'anli_r1': ('acc,none', None, 1.0, 1/3), 'anli_r2': ('acc,none', None, 1.0, 1/3), 'anli_r3': ('acc,none', None, 1.0, 1/3), 'truthfulqa_mc2': ('acc,none', None, 1.0, 0.50), 'triviaqa': ('exact_match,remove_whitespace', None, 1.0, 0.0), 'nq_open': ('exact_match,remove_whitespace', None, 1.0, 0.0), 'lambada_openai': ('acc,none', None, 1.0, 0.0), 'wikitext': ('word_perplexity,none', None, 1.0, None), # ppl, no centered # MMLU sub-tasks (57) — handled as group # BLiMP sub-tasks (67) — handled as group } STDERR_SUFFIX = '_stderr' # Paper aggregates — list of task IDs (mmlu = mean of mmlu_*; arc_mean = mean of E/C) FINEWEB_8 = ['commonsense_qa','hellaswag','openbookqa','piqa','social_iqa','winogrande', '__arc_mean__','__mmlu_mean__'] DCLM_CORE_PROSE_18 = ['arc_easy','arc_challenge','hellaswag','piqa','winogrande','openbookqa', 'commonsense_qa','social_iqa','boolq','sciq','race','lambada_openai', 'truthfulqa_mc2','copa','cb','rte','logiqa','pubmedqa'] DOLMA_HEADLINE_8 = ['hellaswag','piqa','winogrande','openbookqa','arc_easy','arc_challenge', 'sciq','boolq'] # + paloma_bpb_11 as separate column NEMOTRON_CC = FINEWEB_8 + ['race','boolq','__anli_mean__'] KNOWLEDGE_AGG = ['__mmlu_mean__','triviaqa','nq_open','arc_challenge','openbookqa'] FLUENCY_TASKS = ['lambada_openai'] # plus -wikitext_bpb and -paloma_bpb (handled separately) NARRATIVE_TAX = ['hellaswag','piqa','winogrande','__blimp_mean__'] # ---- Load ------------------------------------------------------------------- def load_results(d, label): f = glob.glob(f'{d}/{label}_results/results_*.json') if not f: sys.exit(f"No results file in {d}/{label}_results/") return json.load(open(f[0]))['results'] def get_metric(task_results, key, scale=1.0): if key in task_results: return task_results[key] * scale return None def get_stderr(task_results, key, scale=1.0): se_key = key.replace(',', '_stderr,', 1) if se_key in task_results: v = task_results[se_key] if isinstance(v, (int, float)): return v * scale return None def extract(results, task): """Return (value_in_0_1, stderr_in_0_1) for the named task, or (None, None).""" if task == '__mmlu_mean__': sub = [k for k in results if k.startswith('mmlu_') and k != 'mmlu'] if not sub: return (None, None) accs = [results[k].get('acc,none') for k in sub] accs = [a for a in accs if isinstance(a,(int,float))] if not accs: return (None, None) return (statistics.mean(accs), statistics.pstdev(accs)/math.sqrt(len(accs))) if task == '__blimp_mean__': sub = [k for k in results if k.startswith('blimp_') and k != 'blimp'] if not sub: return (None, None) accs = [results[k].get('acc,none') for k in sub] accs = [a for a in accs if isinstance(a,(int,float))] return (statistics.mean(accs), statistics.pstdev(accs)/math.sqrt(len(accs))) if task == '__arc_mean__': a = results.get('arc_easy',{}).get('acc_norm,none') b = results.get('arc_challenge',{}).get('acc_norm,none') if a is None or b is None: return (None, None) return ((a+b)/2, None) if task == '__anli_mean__': accs=[results.get(t,{}).get('acc,none') for t in ['anli_r1','anli_r2','anli_r3']] accs=[a for a in accs if isinstance(a,(int,float))] if not accs: return (None,None) return (statistics.mean(accs), None) spec = TASK_SPEC.get(task) if spec is None: return (None, None) key, _, scale, _ = spec return get_metric(results.get(task,{}), key, scale), get_stderr(results.get(task,{}), key, scale) # ---- Load all three variants ---- labels = ['clusterA_mq_new', 'clusterA_mq_new_repaired', 'clusterA_mq_new_repaired_upsampled'] display = {'clusterA_mq_new':'PRE', 'clusterA_mq_new_repaired':'POST', 'clusterA_mq_new_repaired_upsampled':'POST+UP'} prose = {lab: load_results(PROSE_DIR, lab) for lab in labels} paloma = {lab: load_results(PALOMA_DIR, lab) for lab in labels} # ---- Per-task table (POST+UP vs PRE, with significance) --------------------- print("="*86) print("Table 1: Per-task results — POST+UP vs PRE (Qwen3-1.7B, 1 epoch, iter 16 406)") print("="*86) print(f"{'task':<22} {'PRE':>9} {'POST':>9} {'POST+UP':>9} {'Δ+UP':>9} {'SE':>7} {'Z':>6} {'sig':>4}") print('-'*86) all_single = list(TASK_SPEC.keys()) total_pre, total_ups, n_acc = 0.0, 0.0, 0 deltas_pp = [] sig_count = {'***':0,'**':0,'*':0,'-':0} for t in all_single: if t == 'wikitext': continue # PPL handled separately p_pre, se_pre = extract(prose['clusterA_mq_new'], t) p_post, _ = extract(prose['clusterA_mq_new_repaired'], t) p_ups, se_ups = extract(prose['clusterA_mq_new_repaired_upsampled'], t) if p_pre is None or p_ups is None: continue d_pp = (p_ups - p_pre) * 100 se_p = (se_pre or 0)*100 se_u = (se_ups or 0)*100 combined_se = math.sqrt(se_p**2 + se_u**2) if (se_pre or se_ups) else 0.0 z = d_pp/combined_se if combined_se>0 else 0.0 sig = '***' if abs(z)>=2.58 else '**' if abs(z)>=1.96 else '*' if abs(z)>=1.65 else '-' sig_count[sig] = sig_count.get(sig,0)+1 print(f"{t:<22} {p_pre*100:>8.2f}% {p_post*100:>8.2f}% {p_ups*100:>8.2f}% {d_pp:>+8.2f}pp {combined_se:>6.2f} {z:>+6.2f} {sig:>4}") deltas_pp.append((t, d_pp, p_pre, p_ups)) total_pre += p_pre; total_ups += p_ups; n_acc += 1 # MMLU & BLiMP aggregate rows for agg in ['__mmlu_mean__','__blimp_mean__']: p_pre,_=extract(prose['clusterA_mq_new'],agg); p_post,_=extract(prose['clusterA_mq_new_repaired'],agg); p_ups,_=extract(prose['clusterA_mq_new_repaired_upsampled'],agg) if p_pre is None: continue d_pp = (p_ups-p_pre)*100 name = 'mmlu-57 (mean)' if agg=='__mmlu_mean__' else 'blimp-67 (mean)' print(f"{name:<22} {p_pre*100:>8.2f}% {p_post*100:>8.2f}% {p_ups*100:>8.2f}% {d_pp:>+8.2f}pp") # Wikitext PPL wp_pre = prose['clusterA_mq_new']['wikitext']['word_perplexity,none'] wp_post = prose['clusterA_mq_new_repaired']['wikitext']['word_perplexity,none'] wp_ups = prose['clusterA_mq_new_repaired_upsampled']['wikitext']['word_perplexity,none'] print(f"{'wikitext (ppl ↓)':<22} {wp_pre:>9.2f} {wp_post:>9.2f} {wp_ups:>9.2f} {wp_pre-wp_ups:>+9.2f} (lower=better)") # WikiText BPB for cleaner aggregation wb_pre = prose['clusterA_mq_new']['wikitext']['bits_per_byte,none'] wb_post = prose['clusterA_mq_new_repaired']['wikitext']['bits_per_byte,none'] wb_ups = prose['clusterA_mq_new_repaired_upsampled']['wikitext']['bits_per_byte,none'] print(f"{'wikitext (bpb ↓)':<22} {wb_pre:>9.4f} {wb_post:>9.4f} {wb_ups:>9.4f} {wb_pre-wb_ups:>+9.4f} (lower=better)") print('-'*86) print(f"\nSignificance tally (z-test, two-sided): *** p<0.01: {sig_count['***']}, ** p<0.05: {sig_count['**']}, * p<0.10: {sig_count['*']}, ns: {sig_count['-']}") # ---- Paloma-11 BPB table ---- print(f"\n{'='*86}") print("Table 2: Paloma-11 bits-per-byte (lower=better) — POST+UP vs PRE") print(f"{'='*86}") print(f"{'corpus':<32} {'PRE':>9} {'POST':>9} {'POST+UP':>9} {'Δ+UP':>9}") print('-'*86) ptasks = sorted(paloma['clusterA_mq_new'].keys()) bpb = {lab: [] for lab in labels} for pt in ptasks: name = paloma['clusterA_mq_new'][pt].get('alias', pt) pre_b = paloma['clusterA_mq_new'][pt]['bits_per_byte,none'] pos_b = paloma['clusterA_mq_new_repaired'][pt]['bits_per_byte,none'] ups_b = paloma['clusterA_mq_new_repaired_upsampled'][pt]['bits_per_byte,none'] bpb['clusterA_mq_new'].append(pre_b); bpb['clusterA_mq_new_repaired'].append(pos_b); bpb['clusterA_mq_new_repaired_upsampled'].append(ups_b) print(f"{name:<32} {pre_b:>9.4f} {pos_b:>9.4f} {ups_b:>9.4f} {pre_b-ups_b:>+9.4f}") print('-'*86) for lab in labels: bpb[lab+'_mean'] = statistics.mean(bpb[lab]) print(f"{'Paloma-BPB-11 (mean)':<32} {bpb['clusterA_mq_new_mean']:>9.4f} {bpb['clusterA_mq_new_repaired_mean']:>9.4f} {bpb['clusterA_mq_new_repaired_upsampled_mean']:>9.4f} {bpb['clusterA_mq_new_mean']-bpb['clusterA_mq_new_repaired_upsampled_mean']:>+9.4f}") # ---- Paper-aligned aggregates ---- def mean_acc(results, tasks): vs=[] for t in tasks: v,_=extract(results,t) if v is not None: vs.append(v) return statistics.mean(vs) if vs else None def centered_mean(results, tasks_with_rand): vs=[] for t, rand in tasks_with_rand: v,_=extract(results,t) if v is None: continue if rand is None or rand>=1.0: continue cv = (v - rand) / (1.0 - rand) vs.append(cv) return statistics.mean(vs) if vs else None print(f"\n{'='*86}") print("Table 3: Paper-aligned aggregates") print(f"{'='*86}") print(f"{'aggregate':<36} {'PRE':>9} {'POST':>9} {'POST+UP':>9} {'Δ+UP':>9}") print('-'*86) # FineWeb-8 (unweighted mean of acc) fw8 = {lab: mean_acc(prose[lab], FINEWEB_8) for lab in labels} print(f"{'(a) FineWeb-Aggregate-8 (acc)':<36} {fw8['clusterA_mq_new']*100:>8.2f}% {fw8['clusterA_mq_new_repaired']*100:>8.2f}% {fw8['clusterA_mq_new_repaired_upsampled']*100:>8.2f}% {(fw8['clusterA_mq_new_repaired_upsampled']-fw8['clusterA_mq_new'])*100:>+8.2f}pp") # DCLM-Core-prose-18 (centered) def rand_for(t): return TASK_SPEC[t][3] if t in TASK_SPEC and TASK_SPEC[t][3] is not None else 0.0 dclm_set = [(t, rand_for(t)) for t in DCLM_CORE_PROSE_18] dclm = {lab: centered_mean(prose[lab], dclm_set) for lab in labels} print(f"{'(b) DCLM-Core-prose-18 (centered)':<36} {dclm['clusterA_mq_new']*100:>8.2f}% {dclm['clusterA_mq_new_repaired']*100:>8.2f}% {dclm['clusterA_mq_new_repaired_upsampled']*100:>8.2f}% {(dclm['clusterA_mq_new_repaired_upsampled']-dclm['clusterA_mq_new'])*100:>+8.2f}pp") # Dolma-Headline-8 do8 = {lab: mean_acc(prose[lab], DOLMA_HEADLINE_8) for lab in labels} print(f"{'(c) Dolma-Headline-8 (acc)':<36} {do8['clusterA_mq_new']*100:>8.2f}% {do8['clusterA_mq_new_repaired']*100:>8.2f}% {do8['clusterA_mq_new_repaired_upsampled']*100:>8.2f}% {(do8['clusterA_mq_new_repaired_upsampled']-do8['clusterA_mq_new'])*100:>+8.2f}pp") # Nemotron-CC nem = {lab: mean_acc(prose[lab], NEMOTRON_CC) for lab in labels} print(f"{'(d) Nemotron-CC-Headline (acc)':<36} {nem['clusterA_mq_new']*100:>8.2f}% {nem['clusterA_mq_new_repaired']*100:>8.2f}% {nem['clusterA_mq_new_repaired_upsampled']*100:>8.2f}% {(nem['clusterA_mq_new_repaired_upsampled']-nem['clusterA_mq_new'])*100:>+8.2f}pp") # Paloma-BPB-11 (lower=better) print(f"{'(e) Paloma-BPB-11 (bpb ↓)':<36} {bpb['clusterA_mq_new_mean']:>9.4f} {bpb['clusterA_mq_new_repaired_mean']:>9.4f} {bpb['clusterA_mq_new_repaired_upsampled_mean']:>9.4f} {bpb['clusterA_mq_new_mean']-bpb['clusterA_mq_new_repaired_upsampled_mean']:>+9.4f}") # Diagnostic aggregates print(f"\n{'='*86}") print("Table 4: Hypothesis-aligned diagnostic aggregates") print(f"{'='*86}") print(f"{'aggregate':<36} {'PRE':>9} {'POST':>9} {'POST+UP':>9} {'Δ+UP':>9}") print('-'*86) kn = {lab: mean_acc(prose[lab], KNOWLEDGE_AGG) for lab in labels} print(f"{'(f) Knowledge-Agg (acc)':<36} {kn['clusterA_mq_new']*100:>8.2f}% {kn['clusterA_mq_new_repaired']*100:>8.2f}% {kn['clusterA_mq_new_repaired_upsampled']*100:>8.2f}% {(kn['clusterA_mq_new_repaired_upsampled']-kn['clusterA_mq_new'])*100:>+8.2f}pp") # Fluency: LAMBADA acc (higher=better) + −WikiText-BPB + −Paloma-BPB-mean (both lower=better, so we invert) def fluency(lab, prose_d, paloma_bpb_mean): lam,_ = extract(prose_d, 'lambada_openai') wb = prose_d['wikitext']['bits_per_byte,none'] pb = paloma_bpb_mean # Construct as 3-component: lam (0-1) + (1-wb_normed) + (1-pb_normed) # For an interpretable single number, just print all three. return lam, wb, pb print() print(f"(g) Fluency-Agg diagnostic (3 numbers): LAMBADA-acc (↑), WikiText-BPB (↓), Paloma-BPB (↓)") for lab in labels: l, wb, pb = fluency(lab, prose[lab], bpb[lab+'_mean']) print(f" {display[lab]:<10} LAMBADA={l*100:.2f}% WikiText-BPB={wb:.4f} Paloma-BPB={pb:.4f}") print() nt = {lab: mean_acc(prose[lab], NARRATIVE_TAX) for lab in labels} print(f"{'(h) Narrative-Tax-Canary (acc)':<36} {nt['clusterA_mq_new']*100:>8.2f}% {nt['clusterA_mq_new_repaired']*100:>8.2f}% {nt['clusterA_mq_new_repaired_upsampled']*100:>8.2f}% {(nt['clusterA_mq_new_repaired_upsampled']-nt['clusterA_mq_new'])*100:>+8.2f}pp") # Top deltas deltas_pp.sort(key=lambda r:-r[1]) print(f"\n=== Top-10 task gains (POST+UP vs PRE) ===") for t,d,vp,vq in deltas_pp[:10]: print(f" {t:<24} {vp*100:>6.2f}% → {vq*100:>6.2f}% {d:>+6.2f}pp") print(f"\n=== Top-10 task losses ===") for t,d,vp,vq in deltas_pp[-10:][::-1]: print(f" {t:<24} {vp*100:>6.2f}% → {vq*100:>6.2f}% {d:>+6.2f}pp")