File size: 15,488 Bytes
08326df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#!/usr/bin/env python3
"""8-variant analysis (POST-only EXCLUDED): focus on PRE vs POST+UP across tiers.

Variants:
  - Cluster A MQ-PRE, Cluster A MQ-POST+UP
  - 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

Tables produced:
  Table 1  — 8-variant headline accuracy matrix (15 metrics + 4 aggregates)
  Table 2  — Tier ordering at PRE and at POST+UP, with HQ-vs-LQ spread
  Table 3  — Repair effect (POST+UP - PRE) by tier, with seed-variance floor
  Table 4  — Cross-cluster seed-variance noise floor (Cluster A MQ vs Cluster B MQ, PRE and POST+UP only)
  Table 5  — Paloma-11 BPB by variant + distributional split
"""
from __future__ import annotations
import json, glob, math, statistics

BASE = './eval_results'

VARIANTS = [
    # (lookup_label, display_name, cluster, tier, treatment)
    ('clusterA_mq_new',                          'A-MQ-PRE',   'A', 'mq', 'pre'),
    ('clusterA_mq_new_repaired_upsampled',       'A-MQ-UP',    'A', 'mq', 'ups'),
    ('clusterB_mq_new',                      'B-MQ-PRE',   'B', 'mq', 'pre'),
    ('clusterB_mq_new_repaired_upsampled',   'B-MQ-UP',    'B', 'mq', 'ups'),
    ('clusterB_hq_new',                      'B-HQ-PRE',   'B', 'hq', 'pre'),
    ('clusterB_hq_new_repaired_upsampled',   'B-HQ-UP',    'B', 'hq', 'ups'),
    ('clusterB_lq_new',                      'B-LQ-PRE',   'B', 'lq', 'pre'),
    ('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}

HEADLINE = [
    ('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 load(suite, label):
    f = glob.glob(f'{BASE}/{suite}/{label}_results/results_*.json')
    return json.load(open(f[0]))['results'] if f else {}

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)
    return v * SCALE.get(task,1.0) if isinstance(v,(int,float)) else None

# Load
data = {}
for lookup, *_ in VARIANTS:
    data[lookup] = {'prose': load('prose', lookup), 'paloma': load('paloma', lookup)}

def fineweb_agg(results):
    vs = [task_value(results,t) for t in ['commonsense_qa','hellaswag','openbookqa','piqa','social_iqa','winogrande']]
    vs = [v for v in vs if v is not None]
    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):
    vs = [task_value(results,t) for t in ['hellaswag','piqa','winogrande','openbookqa','arc_easy','arc_challenge','sciq','boolq']]
    vs = [v for v in vs if v is not None]
    return statistics.mean(vs) if vs else None

def knowledge_agg(results):
    vs = [task_value(results,t) for t in ['arc_challenge','openbookqa']]
    for t in ['mmlu_mean','triviaqa','nq_open']:
        v = task_value(results,t)
        if v is not None: vs.append(v)
    vs = [v for v in vs if v is not None]
    return statistics.mean(vs) if vs else None

# ============================================================================
# TABLE 1 — 8-variant accuracy matrix
# ============================================================================
print("="*150)
print(" Table 1 — Per-variant zero-shot accuracy (%) — POST-only EXCLUDED (PRE vs POST+UP only)")
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")
print("="*150)
hdr = f"  {'metric':<14}"
for _, disp, *_ in VARIANTS:
    hdr += f"  {disp:>10}"
print(hdr)
print('-'*150)
for mid, disp, grp in HEADLINE:
    line = f"  {disp:<14}"
    for lookup, *_ in VARIANTS:
        v = task_value(data[lookup]['prose'], mid)
        line += f"  {v*100:>10.2f}" if v is not None else f"  {'--':>10}"
    print(line)
print('-'*150)
for agg_name, agg_fn in [('FineWeb-Agg-8', fineweb_agg), ('Dolma-Hdln-8', dolma8_agg), ('Knowledge-Agg', knowledge_agg)]:
    line = f"  {agg_name:<14}"
    for lookup, *_ in VARIANTS:
        v = agg_fn(data[lookup]['prose'])
        line += f"  {v*100:>10.2f}" if v is not None else f"  {'--':>10}"
    print(line)
# Paloma BPB
line = f"  {'Paloma-BPB ↓':<14}"
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)
    line += f"  {v:>10.4f}"
print(line)

# ============================================================================
# TABLE 2 — Tier ordering at PRE and at POST+UP
# ============================================================================
print()
print("="*150)
print(" Table 2 — Tier ordering at each treatment (Cluster B cluster; A-MQ is cross-cluster anchor)")
print(" Spread = HQ − LQ (positive = expected HQ-best ordering; negative = inverted)")
print("="*150)
hdr = f"  {'metric':<14}  {'treat':<8}  {'LQ':>7}  {'MQ':>7}  {'HQ':>7}  {'spread':>8}  {'order':<12}"
print(hdr)
print('-'*100)
for mid, disp, _ in HEADLINE:
    for trt, sfx in [('PRE','new'), ('POST+UP','new_repaired_upsampled')]:
        lq = task_value(data[f'clusterB_lq_{sfx}']['prose'], mid)
        mq = task_value(data[f'clusterB_mq_{sfx}']['prose'], mid)
        hq = task_value(data[f'clusterB_hq_{sfx}']['prose'], mid)
        if lq is None or mq is None or hq is None: continue
        spread = (hq - lq) * 100
        # Determine ordering
        triple = [('LQ',lq),('MQ',mq),('HQ',hq)]
        triple_sorted = sorted(triple, key=lambda r:-r[1])
        order = '>'.join(t[0] for t in triple_sorted)
        line = f"  {disp:<14}  {trt:<8}  {lq*100:>7.2f}  {mq*100:>7.2f}  {hq*100:>7.2f}  {spread:>+7.2f}  {order:<12}"
        print(line)
    print()

# ============================================================================
# TABLE 3 — Repair effect (POST+UP − PRE) by tier  +  seed-variance noise floor
# ============================================================================
print("="*150)
print(" Table 3 — Repair effect Δ (POST+UP − PRE) by tier  +  cross-cluster seed-variance floor")
print(" Floor is |Cluster B MQ - Cluster A MQ| paired delta at the same treatment.")
print(" S/N column = |best tier delta| / floor.")
print("="*150)
hdr = f"  {'metric':<14}  {'Δ LQ':>9}  {'Δ MQ-A':>9}  {'Δ MQ-B':>9}  {'Δ HQ':>9}    {'seed-floor':>11}  {'best-S/N':>10}"
print(hdr)
print('-'*120)
def delta(lab_pre, lab_ups, mid):
    pv = task_value(data[lab_pre]['prose'], mid)
    uv = task_value(data[lab_ups]['prose'], mid)
    return (uv-pv)*100 if (pv is not None and uv is not None) else None

floor_results = {}
for mid, disp, _ in HEADLINE:
    d_lq = delta('clusterB_lq_new','clusterB_lq_new_repaired_upsampled', mid)
    d_mq_a = delta('clusterA_mq_new','clusterA_mq_new_repaired_upsampled', mid)
    d_mq_b = delta('clusterB_mq_new','clusterB_mq_new_repaired_upsampled', mid)
    d_hq = delta('clusterB_hq_new','clusterB_hq_new_repaired_upsampled', mid)
    # Seed-variance floor = median of |Cluster A MQ vs Cluster B MQ| at PRE and POST+UP
    a_pre = task_value(data['clusterA_mq_new']['prose'], mid)
    b_pre = task_value(data['clusterB_mq_new']['prose'], mid)
    a_ups = task_value(data['clusterA_mq_new_repaired_upsampled']['prose'], mid)
    b_ups = task_value(data['clusterB_mq_new_repaired_upsampled']['prose'], mid)
    floor_vals = []
    if a_pre is not None and b_pre is not None:
        floor_vals.append(abs(b_pre - a_pre) * 100)
    if a_ups is not None and b_ups is not None:
        floor_vals.append(abs(b_ups - a_ups) * 100)
    floor = statistics.median(floor_vals) if floor_vals else 0.0
    floor_results[mid] = floor
    # Best tier signal
    deltas_pp = [d for d in [d_lq, d_mq_a, d_mq_b, d_hq] if d is not None]
    best = max(deltas_pp, key=abs) if deltas_pp else 0.0
    sn = abs(best)/floor if floor > 0.001 else float('inf')
    sn_str = f"{sn:>6.1f}×" if sn != float('inf') else "   ∞"
    def fmt(d):
        return f"{d:>+8.2f}pp" if d is not None else f"  {'--':>7}"
    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}")

# Aggregate deltas
print('-'*120)
def agg_delta(agg_fn, pre, ups):
    p = agg_fn(data[pre]['prose']); u = agg_fn(data[ups]['prose'])
    return (u-p)*100 if (p is not None and u is not None) else None
for name, agg_fn in [('FineWeb-Agg-8', fineweb_agg), ('Dolma-Hdln-8', dolma8_agg), ('Knowledge-Agg', knowledge_agg)]:
    d_lq = agg_delta(agg_fn,'clusterB_lq_new','clusterB_lq_new_repaired_upsampled')
    d_mq_a = agg_delta(agg_fn,'clusterA_mq_new','clusterA_mq_new_repaired_upsampled')
    d_mq_b = agg_delta(agg_fn,'clusterB_mq_new','clusterB_mq_new_repaired_upsampled')
    d_hq = agg_delta(agg_fn,'clusterB_hq_new','clusterB_hq_new_repaired_upsampled')
    def fmt(d):
        return f"{d:>+8.2f}pp" if d is not None else f"  {'--':>7}"
    print(f"  {name:<14}  {fmt(d_lq):>9}  {fmt(d_mq_a):>9}  {fmt(d_mq_b):>9}  {fmt(d_hq):>9}")

# Paloma BPB Δ
def palo_mean_delta(pre, ups):
    p = statistics.mean([data[pre]['paloma'][c]['bits_per_byte,none'] for c in data[pre]['paloma']])
    u = statistics.mean([data[ups]['paloma'][c]['bits_per_byte,none'] for c in data[ups]['paloma']])
    return u - p
d_lq = palo_mean_delta('clusterB_lq_new','clusterB_lq_new_repaired_upsampled')
d_mq_a = palo_mean_delta('clusterA_mq_new','clusterA_mq_new_repaired_upsampled')
d_mq_b = palo_mean_delta('clusterB_mq_new','clusterB_mq_new_repaired_upsampled')
d_hq = palo_mean_delta('clusterB_hq_new','clusterB_hq_new_repaired_upsampled')
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)")

# ============================================================================
# TABLE 4 — Cross-cluster seed-variance noise floor (PRE and POST+UP only)
# ============================================================================
print()
print("="*150)
print(" Table 4 — Seed-variance noise floor (Cluster A MQ vs Cluster B MQ, same treatment)")
print(" Excludes POST-only (Cluster B MQ-POST was anomalous: BoolQ +7.6pp, PubMedQA +15.2pp)")
print("="*150)
print(f"  {'metric':<14}  {'|Δ| PRE':>10}  {'|Δ| POST+UP':>14}  {'median':>9}")
print('-'*60)
floors = []
for mid, disp, _ in HEADLINE:
    mp = task_value(data['clusterA_mq_new']['prose'], mid)
    hp = task_value(data['clusterB_mq_new']['prose'], mid)
    mu = task_value(data['clusterA_mq_new_repaired_upsampled']['prose'], mid)
    hu = task_value(data['clusterB_mq_new_repaired_upsampled']['prose'], mid)
    vs = []
    if mp is not None and hp is not None: vs.append(abs(hp-mp)*100)
    if mu is not None and hu is not None: vs.append(abs(hu-mu)*100)
    med = statistics.median(vs) if vs else 0
    print(f"  {disp:<14}  {vs[0]:>10.3f}pp  {vs[1]:>13.3f}pp  {med:>8.3f}pp")
    floors.extend(vs)
print('-'*60)
floors.sort()
print(f"\n  Overall noise floor (15 metrics × 2 treatments = 30 deltas):")
print(f"    median = {statistics.median(floors):.3f} pp")
print(f"    p75    = {floors[int(len(floors)*0.75)]:.3f} pp")
print(f"    p95    = {floors[int(len(floors)*0.95)]:.3f} pp")
print(f"    max    = {floors[-1]:.3f} pp")

# Paloma seed floor
palo_floors = []
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')]:
    for c in data[mlab]['paloma']:
        m = data[mlab]['paloma'][c]['bits_per_byte,none']
        h = data[hlab]['paloma'][c]['bits_per_byte,none']
        palo_floors.append(abs(h-m))
palo_floors.sort()
print(f"\n  Paloma seed floor (22 deltas):  median = {statistics.median(palo_floors):.5f}  max = {palo_floors[-1]:.5f}")

# ============================================================================
# TABLE 5 — Paloma per-corpus 8-variant matrix + distributional split
# ============================================================================
print()
print("="*150)
print(" Table 5 — Paloma-11 bits-per-byte per corpus (lower=better)")
print("="*150)
corpora = sorted(data['clusterA_mq_new']['paloma'].keys())
hdr = f"  {'corpus':<32}"
for _, disp, *_ in VARIANTS: hdr += f"  {disp:>10}"
print(hdr)
print('-'*150)
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]['bits_per_byte,none']
        line += f"  {v:>10.4f}"
    print(line)
print('-'*150)
line = f"  {'Paloma-BPB-11 mean ↓':<32}"
for lookup, *_ in VARIANTS:
    v = statistics.mean([data[lookup]['paloma'][c]['bits_per_byte,none'] for c in corpora])
    line += f"  {v:>10.4f}"
print(line)

# Per-corpus repair delta by tier (POST+UP - PRE)
print()
print(" Repair Δ on Paloma BPB (POST+UP − PRE), by tier")
print(" Negative = repair improves on that corpus; positive = repair regresses")
print(" Distributional-specialization signature: web-y corpora improve, literary corpora regress")
print('-'*100)
print(f"  {'corpus':<32}  {'Δ LQ':>9}  {'Δ MQ-A':>9}  {'Δ MQ-B':>9}  {'Δ HQ':>9}")
for c in corpora:
    name = data['clusterA_mq_new']['paloma'][c].get('alias', c)
    def palo_d(pre, ups):
        return data[ups]['paloma'][c]['bits_per_byte,none'] - data[pre]['paloma'][c]['bits_per_byte,none']
    d_lq = palo_d('clusterB_lq_new','clusterB_lq_new_repaired_upsampled')
    d_mq_a = palo_d('clusterA_mq_new','clusterA_mq_new_repaired_upsampled')
    d_mq_b = palo_d('clusterB_mq_new','clusterB_mq_new_repaired_upsampled')
    d_hq = palo_d('clusterB_hq_new','clusterB_hq_new_repaired_upsampled')
    print(f"  {name:<32}  {d_lq:>+9.4f}  {d_mq_a:>+9.4f}  {d_mq_b:>+9.4f}  {d_hq:>+9.4f}")

print()
print("="*150)
print("END")
print("="*150)