anonymous-md commited on
Commit
16667b9
·
verified ·
1 Parent(s): 75eddc9

Initial release: anonymized evaluation analysis scripts for Repair-First paper

Browse files
README.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - pretraining
7
+ - data-curation
8
+ - evaluation
9
+ - llm
10
+ - common-crawl
11
+ pretty_name: ProseOnlyRepair — Evaluation Analysis Scripts
12
+ ---
13
+
14
+ # ProseOnlyRepair — Evaluation Analysis Scripts
15
+
16
+ Anonymized evaluation/analysis scripts that reproduce the tables and
17
+ figures in the *Repair-First* paper (under double-blind review).
18
+
19
+ ## Contents
20
+
21
+ | File | Purpose |
22
+ |------|---------|
23
+ | `build_paper_tables.py` | Headline tables (per-task accuracy, Paloma BPB, repair deltas) |
24
+ | `build_8variant_analysis.py` | 8-variant repair-effect-by-tier analysis (POST-only excluded) |
25
+ | `build_12variant_analysis.py` | 12-variant superset including POST-only (used in appendix) |
26
+ | `make_paper_figures.py` | Regenerates Figures 1 and 2 from eval JSONs |
27
+ | `requirements.txt` | Python dependencies (lm-evaluation-harness 0.4.12, datasets <4.0, etc.) |
28
+
29
+ ## Variant naming
30
+
31
+ Each evaluation result directory follows
32
+ `{cluster}_{tier}_new[_repaired[_upsampled]]_results`:
33
+
34
+ | Token | Meaning |
35
+ |---|---|
36
+ | `clusterA_` | Pretrained on Cluster A (anonymous identifier) |
37
+ | `clusterB_` | Pretrained on Cluster B (anonymous identifier) |
38
+ | `_lq` / `_mq` / `_hq` | Low / Medium / High quality CommonCrawl tier |
39
+ | `_new` | PRE: pre-repair baseline |
40
+ | `_new_repaired` | POST: post-repair, token budget held by truncation |
41
+ | `_new_repaired_upsampled` | POST+UP: post-repair + upsampled to original token budget |
42
+
43
+ ## How to use
44
+
45
+ ```bash
46
+ pip install -r requirements.txt
47
+ # Place evaluation result JSONs under ./eval_results/{prose,paloma}/
48
+ python3 build_paper_tables.py
49
+ python3 build_8variant_analysis.py
50
+ python3 build_12variant_analysis.py
51
+ python3 make_paper_figures.py
52
+ ```
53
+
54
+ The accompanying evaluation result JSONs (12 variants × prose + paloma
55
+ suites) are released in the paper's supplementary materials zip.
56
+
57
+ ## Notes
58
+
59
+ - All scripts are CPU-only Python and require no GPU.
60
+ - Scripts are deterministic: identical inputs → identical outputs.
61
+ - The 28-task prose suite + 11-corpus Paloma BPB panel are evaluated
62
+ with `lm-evaluation-harness==0.4.12` (vLLM backend).
63
+ - Decoding: greedy, max-len 256 except CoQA/SQuADv2 (512).
64
+
65
+ This release is anonymous for double-blind review and will be
66
+ re-released with author and affiliation metadata after the review
67
+ period.
build_12variant_analysis.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Full 12-variant analysis: 3 Cluster A MQ + 9 Cluster B (mq/hq/lq × new/repaired/repaired_upsampled).
3
+
4
+ Outputs (all to stdout, suitable for paper appendix):
5
+ Table 1 — Headline 13-metric × 12-variant matrix
6
+ Table 2 — POST+UP vs PRE within each tier (3 tier-deltas)
7
+ Table 3 — Tier ordering at each treatment (3 ordering rows × 13 metrics)
8
+ Table 4 — Repair-effect comparison across tiers (does repair help HQ as much as it helps MQ?)
9
+ Table 5 — Paloma-BPB 11-corpus × 12-variant matrix
10
+ Table 6 — Seed-variance noise floor (3 pairs: Cluster A MQ {PRE,POST,POST+UP} vs Cluster B MQ {same})
11
+
12
+ All deltas reported with per-task SE-based significance against the empirical
13
+ seed-variance noise floor measured in Table 6.
14
+ """
15
+ from __future__ import annotations
16
+ import json, glob, math, statistics
17
+
18
+ BASE = './eval_results'
19
+
20
+ # Variant naming convention:
21
+ # - Cluster A MQ stored without prefix: 'clusterA_mq_new', 'clusterA_mq_new_repaired', 'clusterA_mq_new_repaired_upsampled'
22
+ # - Cluster B all prefixed: 'clusterB_mq_new', 'clusterB_hq_new', 'clusterB_lq_new', etc.
23
+ VARIANTS = [
24
+ # (label, suite_filename_prefix, display_name, cluster, tier, treatment)
25
+ ('clusterA_mq_new', 'clusterA_mq_new', 'A-MQ-PRE', 'A', 'mq', 'pre'),
26
+ ('clusterA_mq_new_repaired', 'clusterA_mq_new_repaired', 'A-MQ-POST', 'A', 'mq', 'post'),
27
+ ('clusterA_mq_new_repaired_upsampled', 'clusterA_mq_new_repaired_upsampled', 'A-MQ-UP', 'A', 'mq', 'ups'),
28
+ ('clusterB_mq_new', 'clusterB_mq_new', 'B-MQ-PRE', 'B', 'mq', 'pre'),
29
+ ('clusterB_mq_new_repaired', 'clusterB_mq_new_repaired', 'B-MQ-POST', 'B', 'mq', 'post'),
30
+ ('clusterB_mq_new_repaired_upsampled', 'clusterB_mq_new_repaired_upsampled', 'B-MQ-UP', 'B', 'mq', 'ups'),
31
+ ('clusterB_hq_new', 'clusterB_hq_new', 'B-HQ-PRE', 'B', 'hq', 'pre'),
32
+ ('clusterB_hq_new_repaired', 'clusterB_hq_new_repaired', 'B-HQ-POST', 'B', 'hq', 'post'),
33
+ ('clusterB_hq_new_repaired_upsampled', 'clusterB_hq_new_repaired_upsampled', 'B-HQ-UP', 'B', 'hq', 'ups'),
34
+ ('clusterB_lq_new', 'clusterB_lq_new', 'B-LQ-PRE', 'B', 'lq', 'pre'),
35
+ ('clusterB_lq_new_repaired', 'clusterB_lq_new_repaired', 'B-LQ-POST', 'B', 'lq', 'post'),
36
+ ('clusterB_lq_new_repaired_upsampled', 'clusterB_lq_new_repaired_upsampled', 'B-LQ-UP', 'B', 'lq', 'ups'),
37
+ ]
38
+
39
+ METRIC_KEYS = {
40
+ 'hellaswag':'acc_norm,none','piqa':'acc_norm,none','winogrande':'acc,none',
41
+ 'commonsense_qa':'acc,none','social_iqa':'acc,none','openbookqa':'acc_norm,none',
42
+ 'sciq':'acc_norm,none','arc_easy':'acc_norm,none','arc_challenge':'acc_norm,none',
43
+ 'logiqa':'acc,none','pubmedqa':'acc,none','boolq':'acc,none','race':'acc,none',
44
+ 'squadv2':'best_f1,none','coqa':'f1,none','copa':'acc,none','cb':'acc,none',
45
+ 'rte':'acc,none','anli_r1':'acc,none','anli_r2':'acc,none','anli_r3':'acc,none',
46
+ 'truthfulqa_mc2':'acc,none','triviaqa':'exact_match,remove_whitespace',
47
+ 'nq_open':'exact_match,remove_whitespace','lambada_openai':'acc,none',
48
+ }
49
+ SCALE = {'squadv2':0.01}
50
+
51
+ def load(suite, label):
52
+ f = glob.glob(f'{BASE}/{suite}/{label}_results/results_*.json')
53
+ if not f: return {}
54
+ return json.load(open(f[0]))['results']
55
+
56
+ def numeric(x):
57
+ return x if isinstance(x,(int,float)) else 0.0
58
+
59
+ def task_value(results, task):
60
+ if task == 'mmlu_mean':
61
+ accs = [v.get('acc,none') for k,v in results.items() if k.startswith('mmlu_') and k != 'mmlu']
62
+ accs = [a for a in accs if isinstance(a,(int,float))]
63
+ return statistics.mean(accs) if accs else None
64
+ if task == 'blimp_mean':
65
+ accs = [v.get('acc,none') for k,v in results.items() if k.startswith('blimp_') and k != 'blimp']
66
+ accs = [a for a in accs if isinstance(a,(int,float))]
67
+ return statistics.mean(accs) if accs else None
68
+ key = METRIC_KEYS.get(task)
69
+ if key is None or task not in results: return None
70
+ v = results[task].get(key)
71
+ if not isinstance(v,(int,float)): return None
72
+ return v * SCALE.get(task, 1.0)
73
+
74
+ def task_se(results, task):
75
+ key = METRIC_KEYS.get(task)
76
+ if key is None or task not in results: return 0.0
77
+ se_key = key.replace(',', '_stderr,', 1)
78
+ return numeric(results[task].get(se_key)) * SCALE.get(task,1.0)
79
+
80
+ # ---- Load all data ----
81
+ data = {} # data[label_for_lookup][suite] = results dict
82
+ for lookup, prefix, _, _, _, _ in VARIANTS:
83
+ data[lookup] = {
84
+ 'prose': load('prose', prefix),
85
+ 'paloma': load('paloma', prefix),
86
+ }
87
+
88
+ # ---- Headline metrics list ----
89
+ HEADLINE = [
90
+ # (metric_id, display, group)
91
+ ('hellaswag', 'HellaSwag', 'CS'),
92
+ ('piqa', 'PIQA', 'CS'),
93
+ ('winogrande', 'WinoGrande', 'CS'),
94
+ ('commonsense_qa', 'CSQA', 'CS'),
95
+ ('social_iqa', 'SIQA', 'CS'),
96
+ ('arc_easy', 'ARC-E', 'KR'),
97
+ ('arc_challenge', 'ARC-C', 'KR'),
98
+ ('openbookqa', 'OpenBookQA', 'KR'),
99
+ ('sciq', 'SciQ', 'KR'),
100
+ ('mmlu_mean', 'MMLU-57', 'KR'),
101
+ ('pubmedqa', 'PubMedQA', 'KR'),
102
+ ('boolq', 'BoolQ', 'RC'),
103
+ ('race', 'RACE', 'RC'),
104
+ ('lambada_openai', 'LAMBADA', 'LM'),
105
+ ('blimp_mean', 'BLiMP-67', 'L'),
106
+ ]
107
+
108
+ def pct(v, n=2):
109
+ if v is None: return ' -- '
110
+ return f"{v*100:>{n+5}.{n}f}"
111
+
112
+ def short(label_name):
113
+ return label_name
114
+
115
+ # ============================================================================
116
+ # TABLE 1 — Headline 13-metric × 12-variant matrix
117
+ # ============================================================================
118
+ print("="*200)
119
+ print(" Table 1 — Per-variant zero-shot accuracy (%) on 15 headline prose metrics")
120
+ 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")
121
+ print("="*200)
122
+ hdr = f" {'metric':<13}"
123
+ for _, _, disp, _, _, _ in VARIANTS:
124
+ hdr += f" {disp:>9}"
125
+ print(hdr)
126
+ print('-'*200)
127
+ for mid, disp, grp in HEADLINE:
128
+ line = f" {disp:<13}"
129
+ for lookup, _, _, _, _, _ in VARIANTS:
130
+ v = task_value(data[lookup]['prose'], mid)
131
+ if v is None:
132
+ line += f" {'--':>9}"
133
+ else:
134
+ line += f" {v*100:>9.2f}"
135
+ print(line)
136
+
137
+ # Paper-aligned aggregates
138
+ print('-'*200)
139
+ def fineweb_agg(results):
140
+ tasks = ['commonsense_qa','hellaswag','openbookqa','piqa','social_iqa','winogrande']
141
+ vs = [task_value(results,t) for t in tasks]
142
+ vs = [v for v in vs if v is not None]
143
+ # add arc_mean and mmlu_mean
144
+ arc_e = task_value(results,'arc_easy'); arc_c = task_value(results,'arc_challenge')
145
+ if arc_e is not None and arc_c is not None: vs.append((arc_e+arc_c)/2)
146
+ mmlu = task_value(results,'mmlu_mean')
147
+ if mmlu is not None: vs.append(mmlu)
148
+ return statistics.mean(vs) if vs else None
149
+
150
+ def dolma8_agg(results):
151
+ tasks = ['hellaswag','piqa','winogrande','openbookqa','arc_easy','arc_challenge','sciq','boolq']
152
+ vs = [task_value(results,t) for t in tasks]
153
+ vs = [v for v in vs if v is not None]
154
+ return statistics.mean(vs) if vs else None
155
+
156
+ def knowledge_agg(results):
157
+ tasks_acc = ['arc_challenge','openbookqa']
158
+ vs = [task_value(results,t) for t in tasks_acc]
159
+ mmlu = task_value(results,'mmlu_mean')
160
+ if mmlu is not None: vs.append(mmlu)
161
+ triv = task_value(results,'triviaqa')
162
+ if triv is not None: vs.append(triv)
163
+ nq = task_value(results,'nq_open')
164
+ if nq is not None: vs.append(nq)
165
+ return statistics.mean(vs) if vs else None
166
+
167
+ line = f" {'FineWeb-Agg-8':<13}"
168
+ for lookup, _, _, _, _, _ in VARIANTS:
169
+ v = fineweb_agg(data[lookup]['prose']);
170
+ line += f" {v*100:>9.2f}" if v else f" {'--':>9}"
171
+ print(line)
172
+ line = f" {'Dolma-Hdln-8':<13}"
173
+ for lookup, _, _, _, _, _ in VARIANTS:
174
+ v = dolma8_agg(data[lookup]['prose'])
175
+ line += f" {v*100:>9.2f}" if v else f" {'--':>9}"
176
+ print(line)
177
+ line = f" {'Knowledge-Agg':<13}"
178
+ for lookup, _, _, _, _, _ in VARIANTS:
179
+ v = knowledge_agg(data[lookup]['prose'])
180
+ line += f" {v*100:>9.2f}" if v else f" {'--':>9}"
181
+ print(line)
182
+ # Paloma BPB-11 mean (lower = better)
183
+ line = f" {'Paloma-BPB ↓':<13}"
184
+ for lookup, _, _, _, _, _ in VARIANTS:
185
+ palo = data[lookup]['paloma']
186
+ bpbs = [palo[t]['bits_per_byte,none'] for t in palo if 'bits_per_byte,none' in palo[t]]
187
+ v = statistics.mean(bpbs) if bpbs else None
188
+ line += f" {v:>9.4f}" if v else f" {'--':>9}"
189
+ print(line)
190
+
191
+ # ============================================================================
192
+ # TABLE 2 — Within-tier POST+UP vs PRE deltas (3 tier rows × 15 metric cols)
193
+ # ============================================================================
194
+ print()
195
+ print("="*200)
196
+ print(" Table 2 — Within-tier Δ (POST+UP − PRE) in percentage points")
197
+ print(" Each row is one data tier; positive Δ = POST+UP outperforms PRE; bold-able if |Δ| > 3 × seed_floor on that task")
198
+ print("="*200)
199
+ # Compute seed-variance noise floor per task from Cluster A MQ vs Cluster B MQ (PRE)
200
+ seed_floor = {}
201
+ for mid, disp, _ in HEADLINE:
202
+ mv = task_value(data['clusterA_mq_new']['prose'], mid)
203
+ hv = task_value(data['clusterB_mq_new']['prose'], mid)
204
+ if mv is not None and hv is not None:
205
+ seed_floor[mid] = abs(hv - mv) * 100
206
+ else:
207
+ seed_floor[mid] = 0.0
208
+ # also for paloma
209
+ seed_floor_bpb = {}
210
+ for corpus in data['clusterA_mq_new']['paloma']:
211
+ mv = data['clusterA_mq_new']['paloma'][corpus]['bits_per_byte,none']
212
+ hv = data['clusterB_mq_new']['paloma'][corpus]['bits_per_byte,none']
213
+ seed_floor_bpb[corpus] = abs(hv - mv)
214
+
215
+ tiers = [
216
+ ('B-MQ', 'clusterB_mq_new', 'clusterB_mq_new_repaired_upsampled'),
217
+ ('A-MQ', 'clusterA_mq_new', 'clusterA_mq_new_repaired_upsampled'),
218
+ ('B-HQ', 'clusterB_hq_new', 'clusterB_hq_new_repaired_upsampled'),
219
+ ('B-LQ', 'clusterB_lq_new', 'clusterB_lq_new_repaired_upsampled'),
220
+ ]
221
+ hdr = f" {'tier':<10} "
222
+ for mid, disp, _ in HEADLINE: hdr += f" {disp:>9}"
223
+ hdr += f" {'FineWeb-8':>10} {'Dolma-8':>9} {'Know-Agg':>9} {'Paloma↓':>9}"
224
+ print(hdr)
225
+ print('-'*200)
226
+ for tname, pre, ups in tiers:
227
+ line = f" {tname:<10} "
228
+ for mid, _, _ in HEADLINE:
229
+ pv = task_value(data[pre]['prose'], mid); uv = task_value(data[ups]['prose'], mid)
230
+ if pv is None or uv is None:
231
+ line += f" {'--':>9}"
232
+ else:
233
+ d_pp = (uv-pv)*100
234
+ line += f" {d_pp:>+9.2f}"
235
+ # Aggregates
236
+ fw_pre = fineweb_agg(data[pre]['prose']); fw_ups = fineweb_agg(data[ups]['prose'])
237
+ do_pre = dolma8_agg(data[pre]['prose']); do_ups = dolma8_agg(data[ups]['prose'])
238
+ kn_pre = knowledge_agg(data[pre]['prose']);kn_ups = knowledge_agg(data[ups]['prose'])
239
+ # paloma mean (delta sign-inverted for "improvement" direction: lower bpb is better, so we report PRE - UP so positive = improvement)
240
+ palo_pre = statistics.mean([data[pre]['paloma'][c]['bits_per_byte,none'] for c in data[pre]['paloma']])
241
+ palo_ups = statistics.mean([data[ups]['paloma'][c]['bits_per_byte,none'] for c in data[ups]['paloma']])
242
+ 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}"
243
+ print(line)
244
+
245
+ # ============================================================================
246
+ # TABLE 3 — Tier ordering at each treatment (HQ vs MQ vs LQ at each of PRE/POST/POST+UP)
247
+ # ============================================================================
248
+ print()
249
+ print("="*200)
250
+ print(" Table 3 — Tier ordering at each treatment (Cluster B cluster; A-MQ shown as cross-cluster anchor)")
251
+ print(" Each cell = absolute zero-shot accuracy %; columns are data tier; row groups by treatment")
252
+ print("="*200)
253
+ TREATMENTS = ['PRE', 'POST', 'POST+UP']
254
+ tierset = [('LQ','clusterB_lq'), ('MQ','clusterB_mq'), ('HQ','clusterB_hq')]
255
+ sfx = {'PRE':'new', 'POST':'new_repaired', 'POST+UP':'new_repaired_upsampled'}
256
+ hdr = f" {'metric':<13} {'treat':<7} "
257
+ for tname, _ in tierset: hdr += f" {tname:>7}"
258
+ hdr += f" {'spread':>9}"
259
+ print(hdr)
260
+ print('-'*120)
261
+ for mid, disp, _ in HEADLINE:
262
+ for trt in TREATMENTS:
263
+ vals=[]
264
+ line = f" {disp:<13} {trt:<7} "
265
+ for tname, prefix in tierset:
266
+ label = f"{prefix}_{sfx[trt]}"
267
+ v = task_value(data[label]['prose'], mid)
268
+ vals.append(v)
269
+ line += f" {v*100:>7.2f}" if v is not None else f" {'--':>7}"
270
+ # spread
271
+ if all(v is not None for v in vals):
272
+ spread = (max(vals)-min(vals))*100
273
+ line += f" {spread:>9.2f}"
274
+ else:
275
+ line += f" {'--':>9}"
276
+ print(line)
277
+ print()
278
+
279
+ # ============================================================================
280
+ # TABLE 4 — Repair-effect by tier (POST+UP − PRE within each tier)
281
+ # ============================================================================
282
+ print("="*200)
283
+ print(" Table 4 — Repair-effect by tier (Δ in pp from PRE to POST+UP within each tier)")
284
+ print(" Compares whether repair is more/less effective at higher vs lower data quality")
285
+ print("="*200)
286
+ hdr = f" {'metric':<13} "
287
+ for tname in ['LQ','MQ','HQ']: hdr += f" {'Δ '+tname:>10}"
288
+ hdr += f" {'monotone?':>12}"
289
+ print(hdr)
290
+ print('-'*100)
291
+ for mid, disp, _ in HEADLINE:
292
+ line = f" {disp:<13} "
293
+ deltas = {}
294
+ for tname, prefix in [('LQ','clusterB_lq'), ('MQ','clusterB_mq'), ('HQ','clusterB_hq')]:
295
+ pre_lab = f"{prefix}_new"; ups_lab = f"{prefix}_new_repaired_upsampled"
296
+ pv = task_value(data[pre_lab]['prose'], mid); uv = task_value(data[ups_lab]['prose'], mid)
297
+ if pv is None or uv is None:
298
+ line += f" {'--':>10}"; deltas[tname] = None
299
+ else:
300
+ d = (uv-pv)*100
301
+ line += f" {d:>+10.2f}"
302
+ deltas[tname] = d
303
+ # monotone? (does Δ shrink/grow monotonically with tier quality?)
304
+ if all(deltas[t] is not None for t in ['LQ','MQ','HQ']):
305
+ if deltas['LQ'] >= deltas['MQ'] >= deltas['HQ']:
306
+ mono = 'LQ>MQ>HQ (repair helps lower-quality data more)'
307
+ elif deltas['LQ'] <= deltas['MQ'] <= deltas['HQ']:
308
+ mono = 'HQ>MQ>LQ'
309
+ else:
310
+ mono = 'non-monotone'
311
+ line += f" {mono:>40}"
312
+ print(line)
313
+
314
+ # ============================================================================
315
+ # TABLE 5 — Paloma-BPB 11-corpus × 12-variant matrix
316
+ # ============================================================================
317
+ print()
318
+ print("="*200)
319
+ print(" Table 5 — Paloma-11 BPB (bits-per-byte, lower=better) by variant")
320
+ print("="*200)
321
+ corpora = sorted(data['clusterA_mq_new']['paloma'].keys())
322
+ hdr = f" {'corpus':<32}"
323
+ for _, _, disp, _, _, _ in VARIANTS: hdr += f" {disp:>9}"
324
+ print(hdr)
325
+ print('-'*200)
326
+ for c in corpora:
327
+ name = data['clusterA_mq_new']['paloma'][c].get('alias', c)
328
+ line = f" {name:<32}"
329
+ for lookup, _, _, _, _, _ in VARIANTS:
330
+ v = data[lookup]['paloma'][c].get('bits_per_byte,none')
331
+ line += f" {v:>9.4f}" if v is not None else f" {'--':>9}"
332
+ print(line)
333
+ print('-'*200)
334
+ # Mean BPB
335
+ line = f" {'Paloma-BPB-11 mean ↓':<32}"
336
+ for lookup, _, _, _, _, _ in VARIANTS:
337
+ bpbs = [data[lookup]['paloma'][c]['bits_per_byte,none'] for c in corpora]
338
+ v = statistics.mean(bpbs)
339
+ line += f" {v:>9.4f}"
340
+ print(line)
341
+
342
+ # ============================================================================
343
+ # TABLE 6 — Seed-variance noise floor (Cluster A MQ vs Cluster B MQ at each treatment)
344
+ # ============================================================================
345
+ print()
346
+ print("="*200)
347
+ print(" Table 6 — Seed-variance noise floor measurement")
348
+ print(" Each comparison is same-tier same-treatment, different cluster + training seed.")
349
+ print(" |Δ| values are the empirical noise floor for interpreting cross-tier deltas above.")
350
+ print("="*200)
351
+ pairs = [
352
+ ('PRE', 'clusterA_mq_new', 'clusterB_mq_new'),
353
+ ('POST', 'clusterA_mq_new_repaired', 'clusterB_mq_new_repaired'),
354
+ ('POST+UP', 'clusterA_mq_new_repaired_upsampled', 'clusterB_mq_new_repaired_upsampled'),
355
+ ]
356
+ hdr = f" {'metric':<13}"
357
+ for trt,_,_ in pairs: hdr += f" |Δ| {trt:>8}"
358
+ hdr += f" {'median':>9}"
359
+ print(hdr)
360
+ print('-'*100)
361
+ all_floors = []
362
+ for mid, disp, _ in HEADLINE:
363
+ line = f" {disp:<13}"
364
+ vals=[]
365
+ for trt, mlab, hlab in pairs:
366
+ mv = task_value(data[mlab]['prose'], mid); hv = task_value(data[hlab]['prose'], mid)
367
+ if mv is None or hv is None:
368
+ line += f" {'--':>12}"
369
+ else:
370
+ d = abs(hv - mv) * 100
371
+ vals.append(d)
372
+ line += f" {d:>10.3f}pp"
373
+ med = statistics.median(vals) if vals else None
374
+ line += f" {med:>9.3f}" if med is not None else f" {'--':>9}"
375
+ print(line)
376
+ if vals: all_floors.extend(vals)
377
+
378
+ # Overall summary
379
+ print('-'*100)
380
+ print(f" Overall seed-variance noise floor on 15 headline metrics × 3 treatments:")
381
+ all_floors.sort()
382
+ print(f" median |Δ| = {statistics.median(all_floors):.3f} pp")
383
+ print(f" p75 |Δ| = {all_floors[int(len(all_floors)*0.75)]:.3f} pp")
384
+ print(f" p95 |Δ| = {all_floors[int(len(all_floors)*0.95)]:.3f} pp")
385
+ print(f" max |Δ| = {all_floors[-1]:.3f} pp")
386
+
387
+ # Paloma seed-variance
388
+ print()
389
+ print(f" Paloma BPB seed-variance (3 PRE/POST/POST+UP × 11 corpora):")
390
+ palo_floors = []
391
+ for trt, mlab, hlab in pairs:
392
+ for c in corpora:
393
+ d = abs(data[mlab]['paloma'][c]['bits_per_byte,none'] - data[hlab]['paloma'][c]['bits_per_byte,none'])
394
+ palo_floors.append(d)
395
+ palo_floors.sort()
396
+ print(f" median |Δ BPB| = {statistics.median(palo_floors):.5f}")
397
+ print(f" max |Δ BPB| = {palo_floors[-1]:.5f}")
398
+
399
+ print()
400
+ print("="*200)
401
+ print("END")
402
+ print("="*200)
build_8variant_analysis.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """8-variant analysis (POST-only EXCLUDED): focus on PRE vs POST+UP across tiers.
3
+
4
+ Variants:
5
+ - Cluster A MQ-PRE, Cluster A MQ-POST+UP
6
+ - Cluster B MQ-PRE, Cluster B MQ-POST+UP, Cluster B HQ-PRE, Cluster B HQ-POST+UP, Cluster B LQ-PRE, Cluster B LQ-POST+UP
7
+
8
+ Tables produced:
9
+ Table 1 — 8-variant headline accuracy matrix (15 metrics + 4 aggregates)
10
+ Table 2 — Tier ordering at PRE and at POST+UP, with HQ-vs-LQ spread
11
+ Table 3 — Repair effect (POST+UP - PRE) by tier, with seed-variance floor
12
+ Table 4 — Cross-cluster seed-variance noise floor (Cluster A MQ vs Cluster B MQ, PRE and POST+UP only)
13
+ Table 5 — Paloma-11 BPB by variant + distributional split
14
+ """
15
+ from __future__ import annotations
16
+ import json, glob, math, statistics
17
+
18
+ BASE = './eval_results'
19
+
20
+ VARIANTS = [
21
+ # (lookup_label, display_name, cluster, tier, treatment)
22
+ ('clusterA_mq_new', 'A-MQ-PRE', 'A', 'mq', 'pre'),
23
+ ('clusterA_mq_new_repaired_upsampled', 'A-MQ-UP', 'A', 'mq', 'ups'),
24
+ ('clusterB_mq_new', 'B-MQ-PRE', 'B', 'mq', 'pre'),
25
+ ('clusterB_mq_new_repaired_upsampled', 'B-MQ-UP', 'B', 'mq', 'ups'),
26
+ ('clusterB_hq_new', 'B-HQ-PRE', 'B', 'hq', 'pre'),
27
+ ('clusterB_hq_new_repaired_upsampled', 'B-HQ-UP', 'B', 'hq', 'ups'),
28
+ ('clusterB_lq_new', 'B-LQ-PRE', 'B', 'lq', 'pre'),
29
+ ('clusterB_lq_new_repaired_upsampled', 'B-LQ-UP', 'B', 'lq', 'ups'),
30
+ ]
31
+
32
+ METRIC_KEYS = {
33
+ 'hellaswag':'acc_norm,none','piqa':'acc_norm,none','winogrande':'acc,none',
34
+ 'commonsense_qa':'acc,none','social_iqa':'acc,none','openbookqa':'acc_norm,none',
35
+ 'sciq':'acc_norm,none','arc_easy':'acc_norm,none','arc_challenge':'acc_norm,none',
36
+ 'logiqa':'acc,none','pubmedqa':'acc,none','boolq':'acc,none','race':'acc,none',
37
+ 'squadv2':'best_f1,none','coqa':'f1,none','copa':'acc,none','cb':'acc,none',
38
+ 'rte':'acc,none','anli_r1':'acc,none','anli_r2':'acc,none','anli_r3':'acc,none',
39
+ 'truthfulqa_mc2':'acc,none','triviaqa':'exact_match,remove_whitespace',
40
+ 'nq_open':'exact_match,remove_whitespace','lambada_openai':'acc,none',
41
+ }
42
+ SCALE = {'squadv2':0.01}
43
+
44
+ HEADLINE = [
45
+ ('hellaswag','HellaSwag','CS'),
46
+ ('piqa','PIQA','CS'),
47
+ ('winogrande','WinoGrande','CS'),
48
+ ('commonsense_qa','CSQA','CS'),
49
+ ('social_iqa','SIQA','CS'),
50
+ ('arc_easy','ARC-E','KR'),
51
+ ('arc_challenge','ARC-C','KR'),
52
+ ('openbookqa','OpenBookQA','KR'),
53
+ ('sciq','SciQ','KR'),
54
+ ('mmlu_mean','MMLU-57','KR'),
55
+ ('pubmedqa','PubMedQA','KR'),
56
+ ('boolq','BoolQ','RC'),
57
+ ('race','RACE','RC'),
58
+ ('lambada_openai','LAMBADA','LM'),
59
+ ('blimp_mean','BLiMP-67','L'),
60
+ ]
61
+
62
+ def load(suite, label):
63
+ f = glob.glob(f'{BASE}/{suite}/{label}_results/results_*.json')
64
+ return json.load(open(f[0]))['results'] if f else {}
65
+
66
+ def task_value(results, task):
67
+ if task == 'mmlu_mean':
68
+ accs = [v.get('acc,none') for k,v in results.items() if k.startswith('mmlu_') and k != 'mmlu']
69
+ accs = [a for a in accs if isinstance(a,(int,float))]
70
+ return statistics.mean(accs) if accs else None
71
+ if task == 'blimp_mean':
72
+ accs = [v.get('acc,none') for k,v in results.items() if k.startswith('blimp_') and k != 'blimp']
73
+ accs = [a for a in accs if isinstance(a,(int,float))]
74
+ return statistics.mean(accs) if accs else None
75
+ key = METRIC_KEYS.get(task)
76
+ if key is None or task not in results: return None
77
+ v = results[task].get(key)
78
+ return v * SCALE.get(task,1.0) if isinstance(v,(int,float)) else None
79
+
80
+ # Load
81
+ data = {}
82
+ for lookup, *_ in VARIANTS:
83
+ data[lookup] = {'prose': load('prose', lookup), 'paloma': load('paloma', lookup)}
84
+
85
+ def fineweb_agg(results):
86
+ vs = [task_value(results,t) for t in ['commonsense_qa','hellaswag','openbookqa','piqa','social_iqa','winogrande']]
87
+ vs = [v for v in vs if v is not None]
88
+ arc_e = task_value(results,'arc_easy'); arc_c = task_value(results,'arc_challenge')
89
+ if arc_e is not None and arc_c is not None: vs.append((arc_e+arc_c)/2)
90
+ mmlu = task_value(results,'mmlu_mean')
91
+ if mmlu is not None: vs.append(mmlu)
92
+ return statistics.mean(vs) if vs else None
93
+
94
+ def dolma8_agg(results):
95
+ vs = [task_value(results,t) for t in ['hellaswag','piqa','winogrande','openbookqa','arc_easy','arc_challenge','sciq','boolq']]
96
+ vs = [v for v in vs if v is not None]
97
+ return statistics.mean(vs) if vs else None
98
+
99
+ def knowledge_agg(results):
100
+ vs = [task_value(results,t) for t in ['arc_challenge','openbookqa']]
101
+ for t in ['mmlu_mean','triviaqa','nq_open']:
102
+ v = task_value(results,t)
103
+ if v is not None: vs.append(v)
104
+ vs = [v for v in vs if v is not None]
105
+ return statistics.mean(vs) if vs else None
106
+
107
+ # ============================================================================
108
+ # TABLE 1 — 8-variant accuracy matrix
109
+ # ============================================================================
110
+ print("="*150)
111
+ print(" Table 1 — Per-variant zero-shot accuracy (%) — POST-only EXCLUDED (PRE vs POST+UP only)")
112
+ print(" Qwen3-1.7B, 1 epoch (≈ 34.4 B tokens), BF16, all eval on Cluster A H100 + NeMo 26.04 + lm-eval 0.4.12")
113
+ print("="*150)
114
+ hdr = f" {'metric':<14}"
115
+ for _, disp, *_ in VARIANTS:
116
+ hdr += f" {disp:>10}"
117
+ print(hdr)
118
+ print('-'*150)
119
+ for mid, disp, grp in HEADLINE:
120
+ line = f" {disp:<14}"
121
+ for lookup, *_ in VARIANTS:
122
+ v = task_value(data[lookup]['prose'], mid)
123
+ line += f" {v*100:>10.2f}" if v is not None else f" {'--':>10}"
124
+ print(line)
125
+ print('-'*150)
126
+ for agg_name, agg_fn in [('FineWeb-Agg-8', fineweb_agg), ('Dolma-Hdln-8', dolma8_agg), ('Knowledge-Agg', knowledge_agg)]:
127
+ line = f" {agg_name:<14}"
128
+ for lookup, *_ in VARIANTS:
129
+ v = agg_fn(data[lookup]['prose'])
130
+ line += f" {v*100:>10.2f}" if v is not None else f" {'--':>10}"
131
+ print(line)
132
+ # Paloma BPB
133
+ line = f" {'Paloma-BPB ↓':<14}"
134
+ for lookup, *_ in VARIANTS:
135
+ palo = data[lookup]['paloma']
136
+ bpbs = [palo[t]['bits_per_byte,none'] for t in palo if 'bits_per_byte,none' in palo[t]]
137
+ v = statistics.mean(bpbs)
138
+ line += f" {v:>10.4f}"
139
+ print(line)
140
+
141
+ # ============================================================================
142
+ # TABLE 2 — Tier ordering at PRE and at POST+UP
143
+ # ============================================================================
144
+ print()
145
+ print("="*150)
146
+ print(" Table 2 — Tier ordering at each treatment (Cluster B cluster; A-MQ is cross-cluster anchor)")
147
+ print(" Spread = HQ − LQ (positive = expected HQ-best ordering; negative = inverted)")
148
+ print("="*150)
149
+ hdr = f" {'metric':<14} {'treat':<8} {'LQ':>7} {'MQ':>7} {'HQ':>7} {'spread':>8} {'order':<12}"
150
+ print(hdr)
151
+ print('-'*100)
152
+ for mid, disp, _ in HEADLINE:
153
+ for trt, sfx in [('PRE','new'), ('POST+UP','new_repaired_upsampled')]:
154
+ lq = task_value(data[f'clusterB_lq_{sfx}']['prose'], mid)
155
+ mq = task_value(data[f'clusterB_mq_{sfx}']['prose'], mid)
156
+ hq = task_value(data[f'clusterB_hq_{sfx}']['prose'], mid)
157
+ if lq is None or mq is None or hq is None: continue
158
+ spread = (hq - lq) * 100
159
+ # Determine ordering
160
+ triple = [('LQ',lq),('MQ',mq),('HQ',hq)]
161
+ triple_sorted = sorted(triple, key=lambda r:-r[1])
162
+ order = '>'.join(t[0] for t in triple_sorted)
163
+ line = f" {disp:<14} {trt:<8} {lq*100:>7.2f} {mq*100:>7.2f} {hq*100:>7.2f} {spread:>+7.2f} {order:<12}"
164
+ print(line)
165
+ print()
166
+
167
+ # ============================================================================
168
+ # TABLE 3 — Repair effect (POST+UP − PRE) by tier + seed-variance noise floor
169
+ # ============================================================================
170
+ print("="*150)
171
+ print(" Table 3 — Repair effect Δ (POST+UP − PRE) by tier + cross-cluster seed-variance floor")
172
+ print(" Floor is |Cluster B MQ - Cluster A MQ| paired delta at the same treatment.")
173
+ print(" S/N column = |best tier delta| / floor.")
174
+ print("="*150)
175
+ hdr = f" {'metric':<14} {'Δ LQ':>9} {'Δ MQ-A':>9} {'Δ MQ-B':>9} {'Δ HQ':>9} {'seed-floor':>11} {'best-S/N':>10}"
176
+ print(hdr)
177
+ print('-'*120)
178
+ def delta(lab_pre, lab_ups, mid):
179
+ pv = task_value(data[lab_pre]['prose'], mid)
180
+ uv = task_value(data[lab_ups]['prose'], mid)
181
+ return (uv-pv)*100 if (pv is not None and uv is not None) else None
182
+
183
+ floor_results = {}
184
+ for mid, disp, _ in HEADLINE:
185
+ d_lq = delta('clusterB_lq_new','clusterB_lq_new_repaired_upsampled', mid)
186
+ d_mq_a = delta('clusterA_mq_new','clusterA_mq_new_repaired_upsampled', mid)
187
+ d_mq_b = delta('clusterB_mq_new','clusterB_mq_new_repaired_upsampled', mid)
188
+ d_hq = delta('clusterB_hq_new','clusterB_hq_new_repaired_upsampled', mid)
189
+ # Seed-variance floor = median of |Cluster A MQ vs Cluster B MQ| at PRE and POST+UP
190
+ a_pre = task_value(data['clusterA_mq_new']['prose'], mid)
191
+ b_pre = task_value(data['clusterB_mq_new']['prose'], mid)
192
+ a_ups = task_value(data['clusterA_mq_new_repaired_upsampled']['prose'], mid)
193
+ b_ups = task_value(data['clusterB_mq_new_repaired_upsampled']['prose'], mid)
194
+ floor_vals = []
195
+ if a_pre is not None and b_pre is not None:
196
+ floor_vals.append(abs(b_pre - a_pre) * 100)
197
+ if a_ups is not None and b_ups is not None:
198
+ floor_vals.append(abs(b_ups - a_ups) * 100)
199
+ floor = statistics.median(floor_vals) if floor_vals else 0.0
200
+ floor_results[mid] = floor
201
+ # Best tier signal
202
+ deltas_pp = [d for d in [d_lq, d_mq_a, d_mq_b, d_hq] if d is not None]
203
+ best = max(deltas_pp, key=abs) if deltas_pp else 0.0
204
+ sn = abs(best)/floor if floor > 0.001 else float('inf')
205
+ sn_str = f"{sn:>6.1f}×" if sn != float('inf') else " ∞"
206
+ def fmt(d):
207
+ return f"{d:>+8.2f}pp" if d is not None else f" {'--':>7}"
208
+ print(f" {disp:<14} {fmt(d_lq):>9} {fmt(d_mq_a):>9} {fmt(d_mq_b):>9} {fmt(d_hq):>9} {floor:>9.3f}pp {sn_str:>10}")
209
+
210
+ # Aggregate deltas
211
+ print('-'*120)
212
+ def agg_delta(agg_fn, pre, ups):
213
+ p = agg_fn(data[pre]['prose']); u = agg_fn(data[ups]['prose'])
214
+ return (u-p)*100 if (p is not None and u is not None) else None
215
+ for name, agg_fn in [('FineWeb-Agg-8', fineweb_agg), ('Dolma-Hdln-8', dolma8_agg), ('Knowledge-Agg', knowledge_agg)]:
216
+ d_lq = agg_delta(agg_fn,'clusterB_lq_new','clusterB_lq_new_repaired_upsampled')
217
+ d_mq_a = agg_delta(agg_fn,'clusterA_mq_new','clusterA_mq_new_repaired_upsampled')
218
+ d_mq_b = agg_delta(agg_fn,'clusterB_mq_new','clusterB_mq_new_repaired_upsampled')
219
+ d_hq = agg_delta(agg_fn,'clusterB_hq_new','clusterB_hq_new_repaired_upsampled')
220
+ def fmt(d):
221
+ return f"{d:>+8.2f}pp" if d is not None else f" {'--':>7}"
222
+ print(f" {name:<14} {fmt(d_lq):>9} {fmt(d_mq_a):>9} {fmt(d_mq_b):>9} {fmt(d_hq):>9}")
223
+
224
+ # Paloma BPB Δ
225
+ def palo_mean_delta(pre, ups):
226
+ p = statistics.mean([data[pre]['paloma'][c]['bits_per_byte,none'] for c in data[pre]['paloma']])
227
+ u = statistics.mean([data[ups]['paloma'][c]['bits_per_byte,none'] for c in data[ups]['paloma']])
228
+ return u - p
229
+ d_lq = palo_mean_delta('clusterB_lq_new','clusterB_lq_new_repaired_upsampled')
230
+ d_mq_a = palo_mean_delta('clusterA_mq_new','clusterA_mq_new_repaired_upsampled')
231
+ d_mq_b = palo_mean_delta('clusterB_mq_new','clusterB_mq_new_repaired_upsampled')
232
+ d_hq = palo_mean_delta('clusterB_hq_new','clusterB_hq_new_repaired_upsampled')
233
+ print(f" {'Paloma-BPB Δ ↓':<14} {d_lq:>+8.4f} {d_mq_a:>+8.4f} {d_mq_b:>+8.4f} {d_hq:>+8.4f} (lower = improvement)")
234
+
235
+ # ============================================================================
236
+ # TABLE 4 — Cross-cluster seed-variance noise floor (PRE and POST+UP only)
237
+ # ============================================================================
238
+ print()
239
+ print("="*150)
240
+ print(" Table 4 — Seed-variance noise floor (Cluster A MQ vs Cluster B MQ, same treatment)")
241
+ print(" Excludes POST-only (Cluster B MQ-POST was anomalous: BoolQ +7.6pp, PubMedQA +15.2pp)")
242
+ print("="*150)
243
+ print(f" {'metric':<14} {'|Δ| PRE':>10} {'|Δ| POST+UP':>14} {'median':>9}")
244
+ print('-'*60)
245
+ floors = []
246
+ for mid, disp, _ in HEADLINE:
247
+ mp = task_value(data['clusterA_mq_new']['prose'], mid)
248
+ hp = task_value(data['clusterB_mq_new']['prose'], mid)
249
+ mu = task_value(data['clusterA_mq_new_repaired_upsampled']['prose'], mid)
250
+ hu = task_value(data['clusterB_mq_new_repaired_upsampled']['prose'], mid)
251
+ vs = []
252
+ if mp is not None and hp is not None: vs.append(abs(hp-mp)*100)
253
+ if mu is not None and hu is not None: vs.append(abs(hu-mu)*100)
254
+ med = statistics.median(vs) if vs else 0
255
+ print(f" {disp:<14} {vs[0]:>10.3f}pp {vs[1]:>13.3f}pp {med:>8.3f}pp")
256
+ floors.extend(vs)
257
+ print('-'*60)
258
+ floors.sort()
259
+ print(f"\n Overall noise floor (15 metrics × 2 treatments = 30 deltas):")
260
+ print(f" median = {statistics.median(floors):.3f} pp")
261
+ print(f" p75 = {floors[int(len(floors)*0.75)]:.3f} pp")
262
+ print(f" p95 = {floors[int(len(floors)*0.95)]:.3f} pp")
263
+ print(f" max = {floors[-1]:.3f} pp")
264
+
265
+ # Paloma seed floor
266
+ palo_floors = []
267
+ for trt_label, mlab, hlab in [('PRE','clusterA_mq_new','clusterB_mq_new'),('POST+UP','clusterA_mq_new_repaired_upsampled','clusterB_mq_new_repaired_upsampled')]:
268
+ for c in data[mlab]['paloma']:
269
+ m = data[mlab]['paloma'][c]['bits_per_byte,none']
270
+ h = data[hlab]['paloma'][c]['bits_per_byte,none']
271
+ palo_floors.append(abs(h-m))
272
+ palo_floors.sort()
273
+ print(f"\n Paloma seed floor (22 deltas): median = {statistics.median(palo_floors):.5f} max = {palo_floors[-1]:.5f}")
274
+
275
+ # ============================================================================
276
+ # TABLE 5 — Paloma per-corpus 8-variant matrix + distributional split
277
+ # ============================================================================
278
+ print()
279
+ print("="*150)
280
+ print(" Table 5 — Paloma-11 bits-per-byte per corpus (lower=better)")
281
+ print("="*150)
282
+ corpora = sorted(data['clusterA_mq_new']['paloma'].keys())
283
+ hdr = f" {'corpus':<32}"
284
+ for _, disp, *_ in VARIANTS: hdr += f" {disp:>10}"
285
+ print(hdr)
286
+ print('-'*150)
287
+ for c in corpora:
288
+ name = data['clusterA_mq_new']['paloma'][c].get('alias', c)
289
+ line = f" {name:<32}"
290
+ for lookup, *_ in VARIANTS:
291
+ v = data[lookup]['paloma'][c]['bits_per_byte,none']
292
+ line += f" {v:>10.4f}"
293
+ print(line)
294
+ print('-'*150)
295
+ line = f" {'Paloma-BPB-11 mean ↓':<32}"
296
+ for lookup, *_ in VARIANTS:
297
+ v = statistics.mean([data[lookup]['paloma'][c]['bits_per_byte,none'] for c in corpora])
298
+ line += f" {v:>10.4f}"
299
+ print(line)
300
+
301
+ # Per-corpus repair delta by tier (POST+UP - PRE)
302
+ print()
303
+ print(" Repair Δ on Paloma BPB (POST+UP − PRE), by tier")
304
+ print(" Negative = repair improves on that corpus; positive = repair regresses")
305
+ print(" Distributional-specialization signature: web-y corpora improve, literary corpora regress")
306
+ print('-'*100)
307
+ print(f" {'corpus':<32} {'Δ LQ':>9} {'Δ MQ-A':>9} {'Δ MQ-B':>9} {'Δ HQ':>9}")
308
+ for c in corpora:
309
+ name = data['clusterA_mq_new']['paloma'][c].get('alias', c)
310
+ def palo_d(pre, ups):
311
+ return data[ups]['paloma'][c]['bits_per_byte,none'] - data[pre]['paloma'][c]['bits_per_byte,none']
312
+ d_lq = palo_d('clusterB_lq_new','clusterB_lq_new_repaired_upsampled')
313
+ d_mq_a = palo_d('clusterA_mq_new','clusterA_mq_new_repaired_upsampled')
314
+ d_mq_b = palo_d('clusterB_mq_new','clusterB_mq_new_repaired_upsampled')
315
+ d_hq = palo_d('clusterB_hq_new','clusterB_hq_new_repaired_upsampled')
316
+ print(f" {name:<32} {d_lq:>+9.4f} {d_mq_a:>+9.4f} {d_mq_b:>+9.4f} {d_hq:>+9.4f}")
317
+
318
+ print()
319
+ print("="*150)
320
+ print("END")
321
+ print("="*150)
build_paper_tables.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build paper-aligned aggregate tables from prose-28 + Paloma-11 evaluation JSONs.
3
+
4
+ Produces:
5
+ - Per-task table with correct metric extraction (POST+UP vs PRE, with SE / Z)
6
+ - Five paper-aligned aggregates: FineWeb-8, DCLM-Core-18, Dolma-Headline,
7
+ Nemotron-CC, Paloma-BPB-11
8
+ - Three hypothesis-aligned diagnostic aggregates: Knowledge, Fluency,
9
+ Narrative-Tax
10
+ """
11
+ from __future__ import annotations
12
+ import json
13
+ import glob
14
+ import math
15
+ import statistics
16
+ import sys
17
+
18
+ BASE = './eval_results'
19
+ PROSE_DIR = f'{BASE}/prose'
20
+ PALOMA_DIR = f'{BASE}/paloma'
21
+
22
+ # ---- Per-task metric & random-baseline map ---------------------------------
23
+ # (primary_key, fallback_key_or_None, scale_to_01, random_baseline_for_centered_acc)
24
+ TASK_SPEC = {
25
+ 'hellaswag': ('acc_norm,none', None, 1.0, 0.25),
26
+ 'piqa': ('acc_norm,none', None, 1.0, 0.50),
27
+ 'winogrande': ('acc,none', None, 1.0, 0.50),
28
+ 'commonsense_qa': ('acc,none', None, 1.0, 0.20),
29
+ 'social_iqa': ('acc,none', None, 1.0, 1/3),
30
+ 'openbookqa': ('acc_norm,none', None, 1.0, 0.25),
31
+ 'sciq': ('acc_norm,none', None, 1.0, 0.25),
32
+ 'arc_easy': ('acc_norm,none', None, 1.0, 0.25),
33
+ 'arc_challenge': ('acc_norm,none', None, 1.0, 0.25),
34
+ 'logiqa': ('acc,none', None, 1.0, 0.25),
35
+ 'pubmedqa': ('acc,none', None, 1.0, 1/3),
36
+ 'boolq': ('acc,none', None, 1.0, 0.50),
37
+ 'race': ('acc,none', None, 1.0, 0.25),
38
+ 'squadv2': ('best_f1,none', None, 0.01, 0.0), # already 0-100
39
+ 'coqa': ('f1,none', None, 1.0, 0.0),
40
+ 'copa': ('acc,none', None, 1.0, 0.50),
41
+ 'cb': ('acc,none', None, 1.0, 1/3),
42
+ 'rte': ('acc,none', None, 1.0, 0.50),
43
+ 'anli_r1': ('acc,none', None, 1.0, 1/3),
44
+ 'anli_r2': ('acc,none', None, 1.0, 1/3),
45
+ 'anli_r3': ('acc,none', None, 1.0, 1/3),
46
+ 'truthfulqa_mc2': ('acc,none', None, 1.0, 0.50),
47
+ 'triviaqa': ('exact_match,remove_whitespace', None, 1.0, 0.0),
48
+ 'nq_open': ('exact_match,remove_whitespace', None, 1.0, 0.0),
49
+ 'lambada_openai': ('acc,none', None, 1.0, 0.0),
50
+ 'wikitext': ('word_perplexity,none', None, 1.0, None), # ppl, no centered
51
+ # MMLU sub-tasks (57) — handled as group
52
+ # BLiMP sub-tasks (67) — handled as group
53
+ }
54
+ STDERR_SUFFIX = '_stderr'
55
+
56
+ # Paper aggregates — list of task IDs (mmlu = mean of mmlu_*; arc_mean = mean of E/C)
57
+ FINEWEB_8 = ['commonsense_qa','hellaswag','openbookqa','piqa','social_iqa','winogrande',
58
+ '__arc_mean__','__mmlu_mean__']
59
+ DCLM_CORE_PROSE_18 = ['arc_easy','arc_challenge','hellaswag','piqa','winogrande','openbookqa',
60
+ 'commonsense_qa','social_iqa','boolq','sciq','race','lambada_openai',
61
+ 'truthfulqa_mc2','copa','cb','rte','logiqa','pubmedqa']
62
+ DOLMA_HEADLINE_8 = ['hellaswag','piqa','winogrande','openbookqa','arc_easy','arc_challenge',
63
+ 'sciq','boolq'] # + paloma_bpb_11 as separate column
64
+ NEMOTRON_CC = FINEWEB_8 + ['race','boolq','__anli_mean__']
65
+
66
+ KNOWLEDGE_AGG = ['__mmlu_mean__','triviaqa','nq_open','arc_challenge','openbookqa']
67
+ FLUENCY_TASKS = ['lambada_openai'] # plus -wikitext_bpb and -paloma_bpb (handled separately)
68
+ NARRATIVE_TAX = ['hellaswag','piqa','winogrande','__blimp_mean__']
69
+
70
+
71
+ # ---- Load -------------------------------------------------------------------
72
+ def load_results(d, label):
73
+ f = glob.glob(f'{d}/{label}_results/results_*.json')
74
+ if not f:
75
+ sys.exit(f"No results file in {d}/{label}_results/")
76
+ return json.load(open(f[0]))['results']
77
+
78
+ def get_metric(task_results, key, scale=1.0):
79
+ if key in task_results:
80
+ return task_results[key] * scale
81
+ return None
82
+
83
+ def get_stderr(task_results, key, scale=1.0):
84
+ se_key = key.replace(',', '_stderr,', 1)
85
+ if se_key in task_results:
86
+ v = task_results[se_key]
87
+ if isinstance(v, (int, float)):
88
+ return v * scale
89
+ return None
90
+
91
+ def extract(results, task):
92
+ """Return (value_in_0_1, stderr_in_0_1) for the named task, or (None, None)."""
93
+ if task == '__mmlu_mean__':
94
+ sub = [k for k in results if k.startswith('mmlu_') and k != 'mmlu']
95
+ if not sub: return (None, None)
96
+ accs = [results[k].get('acc,none') for k in sub]
97
+ accs = [a for a in accs if isinstance(a,(int,float))]
98
+ if not accs: return (None, None)
99
+ return (statistics.mean(accs), statistics.pstdev(accs)/math.sqrt(len(accs)))
100
+ if task == '__blimp_mean__':
101
+ sub = [k for k in results if k.startswith('blimp_') and k != 'blimp']
102
+ if not sub: return (None, None)
103
+ accs = [results[k].get('acc,none') for k in sub]
104
+ accs = [a for a in accs if isinstance(a,(int,float))]
105
+ return (statistics.mean(accs), statistics.pstdev(accs)/math.sqrt(len(accs)))
106
+ if task == '__arc_mean__':
107
+ a = results.get('arc_easy',{}).get('acc_norm,none')
108
+ b = results.get('arc_challenge',{}).get('acc_norm,none')
109
+ if a is None or b is None: return (None, None)
110
+ return ((a+b)/2, None)
111
+ if task == '__anli_mean__':
112
+ accs=[results.get(t,{}).get('acc,none') for t in ['anli_r1','anli_r2','anli_r3']]
113
+ accs=[a for a in accs if isinstance(a,(int,float))]
114
+ if not accs: return (None,None)
115
+ return (statistics.mean(accs), None)
116
+ spec = TASK_SPEC.get(task)
117
+ if spec is None: return (None, None)
118
+ key, _, scale, _ = spec
119
+ return get_metric(results.get(task,{}), key, scale), get_stderr(results.get(task,{}), key, scale)
120
+
121
+
122
+ # ---- Load all three variants ----
123
+ labels = ['clusterA_mq_new', 'clusterA_mq_new_repaired', 'clusterA_mq_new_repaired_upsampled']
124
+ display = {'clusterA_mq_new':'PRE', 'clusterA_mq_new_repaired':'POST', 'clusterA_mq_new_repaired_upsampled':'POST+UP'}
125
+
126
+ prose = {lab: load_results(PROSE_DIR, lab) for lab in labels}
127
+ paloma = {lab: load_results(PALOMA_DIR, lab) for lab in labels}
128
+
129
+ # ---- Per-task table (POST+UP vs PRE, with significance) ---------------------
130
+ print("="*86)
131
+ print("Table 1: Per-task results — POST+UP vs PRE (Qwen3-1.7B, 1 epoch, iter 16 406)")
132
+ print("="*86)
133
+ print(f"{'task':<22} {'PRE':>9} {'POST':>9} {'POST+UP':>9} {'Δ+UP':>9} {'SE':>7} {'Z':>6} {'sig':>4}")
134
+ print('-'*86)
135
+
136
+ all_single = list(TASK_SPEC.keys())
137
+ total_pre, total_ups, n_acc = 0.0, 0.0, 0
138
+ deltas_pp = []
139
+ sig_count = {'***':0,'**':0,'*':0,'-':0}
140
+
141
+ for t in all_single:
142
+ if t == 'wikitext': continue # PPL handled separately
143
+ p_pre, se_pre = extract(prose['clusterA_mq_new'], t)
144
+ p_post, _ = extract(prose['clusterA_mq_new_repaired'], t)
145
+ p_ups, se_ups = extract(prose['clusterA_mq_new_repaired_upsampled'], t)
146
+ if p_pre is None or p_ups is None: continue
147
+ d_pp = (p_ups - p_pre) * 100
148
+ se_p = (se_pre or 0)*100
149
+ se_u = (se_ups or 0)*100
150
+ combined_se = math.sqrt(se_p**2 + se_u**2) if (se_pre or se_ups) else 0.0
151
+ z = d_pp/combined_se if combined_se>0 else 0.0
152
+ sig = '***' if abs(z)>=2.58 else '**' if abs(z)>=1.96 else '*' if abs(z)>=1.65 else '-'
153
+ sig_count[sig] = sig_count.get(sig,0)+1
154
+ 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}")
155
+ deltas_pp.append((t, d_pp, p_pre, p_ups))
156
+ total_pre += p_pre; total_ups += p_ups; n_acc += 1
157
+
158
+ # MMLU & BLiMP aggregate rows
159
+ for agg in ['__mmlu_mean__','__blimp_mean__']:
160
+ 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)
161
+ if p_pre is None: continue
162
+ d_pp = (p_ups-p_pre)*100
163
+ name = 'mmlu-57 (mean)' if agg=='__mmlu_mean__' else 'blimp-67 (mean)'
164
+ print(f"{name:<22} {p_pre*100:>8.2f}% {p_post*100:>8.2f}% {p_ups*100:>8.2f}% {d_pp:>+8.2f}pp")
165
+
166
+ # Wikitext PPL
167
+ wp_pre = prose['clusterA_mq_new']['wikitext']['word_perplexity,none']
168
+ wp_post = prose['clusterA_mq_new_repaired']['wikitext']['word_perplexity,none']
169
+ wp_ups = prose['clusterA_mq_new_repaired_upsampled']['wikitext']['word_perplexity,none']
170
+ 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)")
171
+
172
+ # WikiText BPB for cleaner aggregation
173
+ wb_pre = prose['clusterA_mq_new']['wikitext']['bits_per_byte,none']
174
+ wb_post = prose['clusterA_mq_new_repaired']['wikitext']['bits_per_byte,none']
175
+ wb_ups = prose['clusterA_mq_new_repaired_upsampled']['wikitext']['bits_per_byte,none']
176
+ 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)")
177
+
178
+ print('-'*86)
179
+ 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['-']}")
180
+
181
+ # ---- Paloma-11 BPB table ----
182
+ print(f"\n{'='*86}")
183
+ print("Table 2: Paloma-11 bits-per-byte (lower=better) — POST+UP vs PRE")
184
+ print(f"{'='*86}")
185
+ print(f"{'corpus':<32} {'PRE':>9} {'POST':>9} {'POST+UP':>9} {'Δ+UP':>9}")
186
+ print('-'*86)
187
+ ptasks = sorted(paloma['clusterA_mq_new'].keys())
188
+ bpb = {lab: [] for lab in labels}
189
+ for pt in ptasks:
190
+ name = paloma['clusterA_mq_new'][pt].get('alias', pt)
191
+ pre_b = paloma['clusterA_mq_new'][pt]['bits_per_byte,none']
192
+ pos_b = paloma['clusterA_mq_new_repaired'][pt]['bits_per_byte,none']
193
+ ups_b = paloma['clusterA_mq_new_repaired_upsampled'][pt]['bits_per_byte,none']
194
+ bpb['clusterA_mq_new'].append(pre_b); bpb['clusterA_mq_new_repaired'].append(pos_b); bpb['clusterA_mq_new_repaired_upsampled'].append(ups_b)
195
+ print(f"{name:<32} {pre_b:>9.4f} {pos_b:>9.4f} {ups_b:>9.4f} {pre_b-ups_b:>+9.4f}")
196
+ print('-'*86)
197
+ for lab in labels: bpb[lab+'_mean'] = statistics.mean(bpb[lab])
198
+ 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}")
199
+
200
+ # ---- Paper-aligned aggregates ----
201
+ def mean_acc(results, tasks):
202
+ vs=[]
203
+ for t in tasks:
204
+ v,_=extract(results,t)
205
+ if v is not None: vs.append(v)
206
+ return statistics.mean(vs) if vs else None
207
+
208
+ def centered_mean(results, tasks_with_rand):
209
+ vs=[]
210
+ for t, rand in tasks_with_rand:
211
+ v,_=extract(results,t)
212
+ if v is None: continue
213
+ if rand is None or rand>=1.0: continue
214
+ cv = (v - rand) / (1.0 - rand)
215
+ vs.append(cv)
216
+ return statistics.mean(vs) if vs else None
217
+
218
+ print(f"\n{'='*86}")
219
+ print("Table 3: Paper-aligned aggregates")
220
+ print(f"{'='*86}")
221
+ print(f"{'aggregate':<36} {'PRE':>9} {'POST':>9} {'POST+UP':>9} {'Δ+UP':>9}")
222
+ print('-'*86)
223
+
224
+ # FineWeb-8 (unweighted mean of acc)
225
+ fw8 = {lab: mean_acc(prose[lab], FINEWEB_8) for lab in labels}
226
+ 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")
227
+
228
+ # DCLM-Core-prose-18 (centered)
229
+ def rand_for(t):
230
+ return TASK_SPEC[t][3] if t in TASK_SPEC and TASK_SPEC[t][3] is not None else 0.0
231
+ dclm_set = [(t, rand_for(t)) for t in DCLM_CORE_PROSE_18]
232
+ dclm = {lab: centered_mean(prose[lab], dclm_set) for lab in labels}
233
+ 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")
234
+
235
+ # Dolma-Headline-8
236
+ do8 = {lab: mean_acc(prose[lab], DOLMA_HEADLINE_8) for lab in labels}
237
+ 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")
238
+
239
+ # Nemotron-CC
240
+ nem = {lab: mean_acc(prose[lab], NEMOTRON_CC) for lab in labels}
241
+ 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")
242
+
243
+ # Paloma-BPB-11 (lower=better)
244
+ 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}")
245
+
246
+ # Diagnostic aggregates
247
+ print(f"\n{'='*86}")
248
+ print("Table 4: Hypothesis-aligned diagnostic aggregates")
249
+ print(f"{'='*86}")
250
+ print(f"{'aggregate':<36} {'PRE':>9} {'POST':>9} {'POST+UP':>9} {'Δ+UP':>9}")
251
+ print('-'*86)
252
+ kn = {lab: mean_acc(prose[lab], KNOWLEDGE_AGG) for lab in labels}
253
+ 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")
254
+
255
+ # Fluency: LAMBADA acc (higher=better) + −WikiText-BPB + −Paloma-BPB-mean (both lower=better, so we invert)
256
+ def fluency(lab, prose_d, paloma_bpb_mean):
257
+ lam,_ = extract(prose_d, 'lambada_openai')
258
+ wb = prose_d['wikitext']['bits_per_byte,none']
259
+ pb = paloma_bpb_mean
260
+ # Construct as 3-component: lam (0-1) + (1-wb_normed) + (1-pb_normed)
261
+ # For an interpretable single number, just print all three.
262
+ return lam, wb, pb
263
+
264
+ print()
265
+ print(f"(g) Fluency-Agg diagnostic (3 numbers): LAMBADA-acc (↑), WikiText-BPB (↓), Paloma-BPB (↓)")
266
+ for lab in labels:
267
+ l, wb, pb = fluency(lab, prose[lab], bpb[lab+'_mean'])
268
+ print(f" {display[lab]:<10} LAMBADA={l*100:.2f}% WikiText-BPB={wb:.4f} Paloma-BPB={pb:.4f}")
269
+
270
+ print()
271
+ nt = {lab: mean_acc(prose[lab], NARRATIVE_TAX) for lab in labels}
272
+ 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")
273
+
274
+ # Top deltas
275
+ deltas_pp.sort(key=lambda r:-r[1])
276
+ print(f"\n=== Top-10 task gains (POST+UP vs PRE) ===")
277
+ 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")
278
+ print(f"\n=== Top-10 task losses ===")
279
+ 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")
make_paper_figures.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate Figures 1 and 2 for the EMNLP 2026 paper.
3
+
4
+ Figure 1 — Repair effect (POST+UP − PRE) by tier on five robust benchmarks.
5
+ Figure 2 — Per-corpus Paloma BPB delta under repair (heatmap).
6
+
7
+ Outputs PDF (vector, for LaTeX inclusion) and PNG (for previewing).
8
+ """
9
+ from __future__ import annotations
10
+ import json
11
+ import glob
12
+ import statistics
13
+ import matplotlib
14
+ matplotlib.use('Agg')
15
+ import matplotlib.pyplot as plt
16
+ import matplotlib.patches as mpatches
17
+ from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm
18
+ import numpy as np
19
+
20
+ BASE = './eval_results'
21
+ OUTDIR = './figures'
22
+
23
+ import os
24
+ os.makedirs(OUTDIR, exist_ok=True)
25
+
26
+
27
+ def load(suite, label):
28
+ f = glob.glob(f'{BASE}/{suite}/{label}_results/results_*.json')
29
+ return json.load(open(f[0]))['results'] if f else {}
30
+
31
+
32
+ # Variant lookup → anonymized display label (cluster A = Cluster A, cluster B = Cluster B)
33
+ PAIRS = {
34
+ 'LQ-A': None, # no Cluster A LQ runs
35
+ 'LQ-B': ('clusterB_lq_new', 'clusterB_lq_new_repaired_upsampled'),
36
+ 'MQ-A': ('clusterA_mq_new', 'clusterA_mq_new_repaired_upsampled'),
37
+ 'MQ-B': ('clusterB_mq_new', 'clusterB_mq_new_repaired_upsampled'),
38
+ 'HQ-A': None,
39
+ 'HQ-B': ('clusterB_hq_new', 'clusterB_hq_new_repaired_upsampled'),
40
+ }
41
+
42
+
43
+ def task_value(results, task, key=None):
44
+ """Get accuracy in [0,1] for a task. Handles mmlu_/blimp_ aggregation."""
45
+ if task == 'mmlu_mean':
46
+ accs = [v.get('acc,none') for k, v in results.items() if k.startswith('mmlu_') and k != 'mmlu']
47
+ accs = [a for a in accs if isinstance(a, (int, float))]
48
+ return statistics.mean(accs) if accs else None
49
+ if task == 'blimp_mean':
50
+ accs = [v.get('acc,none') for k, v in results.items() if k.startswith('blimp_') and k != 'blimp']
51
+ accs = [a for a in accs if isinstance(a, (int, float))]
52
+ return statistics.mean(accs) if accs else None
53
+ if key is None:
54
+ key_map = {
55
+ 'hellaswag': 'acc_norm,none', 'piqa': 'acc_norm,none', 'winogrande': 'acc,none',
56
+ 'commonsense_qa': 'acc,none', 'social_iqa': 'acc,none', 'openbookqa': 'acc_norm,none',
57
+ 'sciq': 'acc_norm,none', 'arc_easy': 'acc_norm,none', 'arc_challenge': 'acc_norm,none',
58
+ 'boolq': 'acc,none', 'race': 'acc,none', 'lambada_openai': 'acc,none',
59
+ }
60
+ key = key_map.get(task)
61
+ if key is None or task not in results:
62
+ return None
63
+ v = results[task].get(key)
64
+ return v if isinstance(v, (int, float)) else None
65
+
66
+
67
+ # ============================================================================
68
+ # FIGURE 1 — Repair effect by tier on five robust benchmarks
69
+ # ============================================================================
70
+ print("[fig1] computing repair-effect deltas by tier ...")
71
+
72
+ # 5 benchmarks (the S/N >= 4× headline set)
73
+ BENCHMARKS = [
74
+ ('lambada_openai', 'LAMBADA-OpenAI'),
75
+ ('boolq', 'BoolQ'),
76
+ ('race', 'RACE'),
77
+ ('hellaswag', 'HellaSwag'),
78
+ ('openbookqa', 'OpenBookQA'),
79
+ ]
80
+
81
+ # 4 tier × cluster bars per benchmark, in the visual order LQ → MQ-A → MQ-B → HQ
82
+ BAR_KEYS = [('LQ-B', 'LQ'), ('MQ-A', 'MQ-A'), ('MQ-B', 'MQ-B'), ('HQ-B', 'HQ')]
83
+ SIGMA_SEED = 0.6 # per-task noise floor in pp (median from Table 2)
84
+
85
+ # Load all data once
86
+ RAW = {}
87
+ for k, pair in PAIRS.items():
88
+ if pair is None:
89
+ continue
90
+ pre_lab, ups_lab = pair
91
+ RAW[k] = {
92
+ 'pre': load('prose', pre_lab),
93
+ 'ups': load('prose', ups_lab),
94
+ }
95
+
96
+ fig, axes = plt.subplots(1, 5, figsize=(14, 3.4), sharey=False)
97
+ colors_per_tier = {'LQ-B':'#c0392b', 'MQ-A':'#f39c12', 'MQ-B':'#27ae60', 'HQ-B':'#2980b9'}
98
+ tier_labels = {'LQ-B':'LQ', 'MQ-A':'MQ-A', 'MQ-B':'MQ-B', 'HQ-B':'HQ'}
99
+
100
+ for ax, (task_id, task_disp) in zip(axes, BENCHMARKS):
101
+ deltas = []
102
+ bar_colors = []
103
+ bar_labels = []
104
+ for k, lab in BAR_KEYS:
105
+ if k not in RAW:
106
+ deltas.append(0.0); bar_colors.append('#cccccc'); bar_labels.append(lab); continue
107
+ pv = task_value(RAW[k]['pre'], task_id)
108
+ uv = task_value(RAW[k]['ups'], task_id)
109
+ if pv is None or uv is None:
110
+ deltas.append(0.0)
111
+ else:
112
+ deltas.append((uv - pv) * 100)
113
+ bar_colors.append(colors_per_tier[k])
114
+ bar_labels.append(tier_labels[k])
115
+
116
+ x = np.arange(len(deltas))
117
+ bars = ax.bar(x, deltas, color=bar_colors, edgecolor='black', linewidth=0.4, width=0.7)
118
+ ax.errorbar(x, deltas, yerr=SIGMA_SEED, fmt='none', ecolor='black', lw=0.7, capsize=2)
119
+ # ±3σ significance lines
120
+ ax.axhline(y= 3*SIGMA_SEED, ls='--', lw=0.5, color='gray')
121
+ ax.axhline(y=-3*SIGMA_SEED, ls='--', lw=0.5, color='gray')
122
+ ax.axhline(y=0, color='black', lw=0.5)
123
+ ax.set_xticks(x); ax.set_xticklabels(bar_labels, fontsize=8)
124
+ ax.set_title(task_disp, fontsize=10)
125
+ ax.tick_params(axis='y', labelsize=8)
126
+ # annotate bars with delta values
127
+ for xi, di in zip(x, deltas):
128
+ ax.text(xi, di + (0.15 if di >= 0 else -0.45), f'{di:+.1f}',
129
+ ha='center', va='bottom' if di >= 0 else 'top', fontsize=7)
130
+ ax.set_ylim(min(min(deltas) - 1.0, -4.0), max(max(deltas) + 1.0, 6.0))
131
+
132
+ axes[0].set_ylabel('Δ accuracy (POST+UP − PRE), pp', fontsize=9)
133
+ fig.suptitle('Repair effect by tier on the five robust benchmarks (S/N ≥ 4×)',
134
+ fontsize=11, y=1.00)
135
+ # Add legend below figures
136
+ proxies = [mpatches.Patch(color=c, label=tier_labels[k]) for k, c in colors_per_tier.items()]
137
+ proxies.append(mpatches.Patch(color='gray', alpha=0.3, label=f'±3σ noise (={3*SIGMA_SEED:.1f} pp)'))
138
+ fig.legend(handles=proxies, loc='lower center', ncol=5, fontsize=8, frameon=False,
139
+ bbox_to_anchor=(0.5, -0.05))
140
+ plt.tight_layout()
141
+ plt.subplots_adjust(bottom=0.15)
142
+ plt.savefig(f'{OUTDIR}/fig1_repair_by_tier.pdf', bbox_inches='tight', dpi=300)
143
+ plt.savefig(f'{OUTDIR}/fig1_repair_by_tier.png', bbox_inches='tight', dpi=200)
144
+ print(f"[fig1] saved to {OUTDIR}/fig1_repair_by_tier.{{pdf,png}}")
145
+ plt.close()
146
+
147
+
148
+ # ============================================================================
149
+ # FIGURE 2 — Paloma per-corpus BPB delta heatmap
150
+ # ============================================================================
151
+ print("[fig2] computing Paloma per-corpus deltas ...")
152
+
153
+ ROWS = [
154
+ ('LQ-B', 'LQ', 'clusterB_lq_new', 'clusterB_lq_new_repaired_upsampled'),
155
+ ('MQ-A', 'MQ-A', 'clusterA_mq_new', 'clusterA_mq_new_repaired_upsampled'),
156
+ ('MQ-B', 'MQ-B', 'clusterB_mq_new', 'clusterB_mq_new_repaired_upsampled'),
157
+ ('HQ-B', 'HQ', 'clusterB_hq_new', 'clusterB_hq_new_repaired_upsampled'),
158
+ ]
159
+ # Web → mixed → literary column ordering
160
+ COL_ORDER = [
161
+ ('paloma_c4_100_domains', 'C4-100', 'web'),
162
+ ('paloma_c4_en', 'C4-en', 'web'),
163
+ ('paloma_falcon-refinedweb', 'Falcon', 'web'),
164
+ ('paloma_mc4', 'mC4', 'web'),
165
+ ('paloma_m2d2_s2orc_unsplit', 'S2ORC', 'mixed'),
166
+ ('paloma_m2d2_wikipedia_unsplit', 'M2D2-Wiki', 'mixed'),
167
+ ('paloma_dolma_100_subreddits', 'Subreddit', 'mixed'),
168
+ ('paloma_dolma-v1_5', 'Dolma', 'lit'),
169
+ ('paloma_wikitext_103', 'WikiText','lit'),
170
+ ('paloma_redpajama', 'RedPajama','lit'),
171
+ ('paloma_ptb', 'PTB', 'lit'),
172
+ ]
173
+
174
+ # Compute delta matrix
175
+ matrix = np.zeros((len(ROWS), len(COL_ORDER)))
176
+ for i, (key, _label, pre_lab, ups_lab) in enumerate(ROWS):
177
+ pre_palo = load('paloma', pre_lab)
178
+ ups_palo = load('paloma', ups_lab)
179
+ for j, (corpus, _name, _kind) in enumerate(COL_ORDER):
180
+ p = pre_palo[corpus]['bits_per_byte,none']
181
+ u = ups_palo[corpus]['bits_per_byte,none']
182
+ matrix[i, j] = u - p
183
+
184
+ fig2, ax2 = plt.subplots(figsize=(9.5, 3.0))
185
+ # Diverging colormap: red for positive (regression), blue for negative (improvement)
186
+ vmax = max(abs(matrix.min()), abs(matrix.max()))
187
+ cmap = plt.get_cmap('RdBu_r')
188
+ norm = TwoSlopeNorm(vmin=-vmax, vcenter=0.0, vmax=vmax)
189
+ im = ax2.imshow(matrix, cmap=cmap, norm=norm, aspect='auto')
190
+
191
+ # Tick labels
192
+ ax2.set_xticks(range(len(COL_ORDER)))
193
+ ax2.set_xticklabels([n[1] for n in COL_ORDER], rotation=25, ha='right', fontsize=8)
194
+ ax2.set_yticks(range(len(ROWS)))
195
+ ax2.set_yticklabels([r[1] for r in ROWS], fontsize=9)
196
+
197
+ # Annotate cells
198
+ for i in range(matrix.shape[0]):
199
+ for j in range(matrix.shape[1]):
200
+ v = matrix[i, j]
201
+ col = 'white' if abs(v) > 0.06 else 'black'
202
+ ax2.text(j, i, f'{v:+.3f}', ha='center', va='center', fontsize=7, color=col)
203
+
204
+ # Vertical dividers between web/mixed/literary blocks
205
+ boundary_indices = []
206
+ kinds = [c[2] for c in COL_ORDER]
207
+ for j in range(1, len(kinds)):
208
+ if kinds[j] != kinds[j-1]:
209
+ boundary_indices.append(j - 0.5)
210
+ for x in boundary_indices:
211
+ ax2.axvline(x=x, color='black', lw=1.2)
212
+
213
+ # Region annotations under x-axis
214
+ kind_labels = {'web':'WEB (improvement)', 'mixed':'NEUTRAL', 'lit':'LITERARY (regression)'}
215
+ # Find midpoints of each block
216
+ from itertools import groupby
217
+ groups = []
218
+ idx = 0
219
+ for kind, group in groupby(kinds):
220
+ g = list(group)
221
+ groups.append((kind, idx, idx + len(g) - 1))
222
+ idx += len(g)
223
+ for kind, lo, hi in groups:
224
+ mid = (lo + hi) / 2
225
+ ax2.text(mid, len(ROWS) + 0.15, kind_labels[kind],
226
+ ha='center', va='top', fontsize=8, style='italic',
227
+ transform=ax2.transData)
228
+
229
+ # Colorbar
230
+ cbar = fig2.colorbar(im, ax=ax2, fraction=0.025, pad=0.02)
231
+ cbar.set_label('Δ BPB (POST+UP − PRE)', fontsize=8)
232
+ cbar.ax.tick_params(labelsize=7)
233
+
234
+ ax2.set_title('Paloma-11 per-corpus repair Δ — universal web/literary split across tiers',
235
+ fontsize=10, pad=10)
236
+ plt.tight_layout()
237
+ plt.subplots_adjust(bottom=0.30, right=0.92)
238
+ plt.savefig(f'{OUTDIR}/fig2_paloma_split.pdf', bbox_inches='tight', dpi=300)
239
+ plt.savefig(f'{OUTDIR}/fig2_paloma_split.png', bbox_inches='tight', dpi=200)
240
+ print(f"[fig2] saved to {OUTDIR}/fig2_paloma_split.{{pdf,png}}")
241
+ plt.close()
242
+
243
+ print("Done.")
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Supplementary materials — analysis-script dependencies
2
+ # Match versions used in the paper's evaluation pipeline (see Appendix D)
3
+
4
+ lm-evaluation-harness==0.4.12
5
+ datasets>=3.0,<4.0
6
+ transformers>=4.50,<6.0
7
+ vllm>=0.10
8
+ numpy
9
+ matplotlib