suchirsalhan commited on
Commit
bb7dfa4
·
verified ·
1 Parent(s): 892065f

Upload code/analyze.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/analyze.py +193 -56
code/analyze.py CHANGED
@@ -209,67 +209,112 @@ if rows:
209
  fig.tight_layout(rect=[0, 0, 1, 0.93])
210
  fig.savefig(f"{FIG}/scatter_naive_vs_aligned.png", bbox_inches="tight"); plt.close(fig)
211
 
212
- # ---- dose-response: does the diagnostic track the true amount of frame drift? ------------
213
- ctl = sorted([r for r in rows if r["is_control"]], key=lambda r: r["frac_layers_permuted"])
 
 
214
  if ctl:
215
- fig, ax = plt.subplots(1, 2, figsize=(9.2, 3.6))
216
  ax[0].plot([r["frac_layers_permuted"] for r in ctl], [r["coord_share"] for r in ctl],
217
- "o-", color=CC)
218
- ax[0].axhline(THRESH, color="#f59e0b", ls=":", lw=1.1)
 
 
 
219
  ax[0].set_xlabel("fraction of layers actually re-parameterised (ground truth)")
220
- ax[0].set_ylabel("coordinate share (diagnostic)")
221
- ax[0].set_title("The diagnostic tracks real frame drift", fontsize=9, loc="left")
222
- for m, c, nm in (("ifeval_prompt", CC, "IFEval prompt"), ("tgt", CG, "Belebele target")):
223
- if all(r.get(f"{m}__naive") is not None for r in ctl):
224
- ax[1].plot([r["frac_layers_permuted"] for r in ctl],
225
- [r[f"{m}__naive"] for r in ctl], "o--", color=c, alpha=0.55,
226
- label=f"{nm}: naive")
227
- ax[1].plot([r["frac_layers_permuted"] for r in ctl],
228
- [r[f"{m}__aligned"] for r in ctl], "o-", color=c, label=f"{nm}: aligned")
 
 
 
 
 
 
229
  ax[1].set_xlabel("fraction of layers re-parameterised")
230
  ax[1].set_ylabel("accuracy")
231
- ax[1].set_title("Alignment recovers what re-parameterisation destroys", fontsize=9, loc="left")
232
- ax[1].legend(fontsize=7, frameon=False)
233
- fig.tight_layout(); fig.savefig(f"{FIG}/dose_response.png", bbox_inches="tight"); plt.close(fig)
 
 
234
 
235
- # ---- selection experiment -------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  sel = []
237
- if rows:
238
  best = {}
239
- for r in rows: best.setdefault(r["fork"], r)
240
- P = list(best.values())
241
- metric = "ifeval_prompt"
242
- def acc(r, arm): return r.get(f"{metric}__{arm}")
243
- P = [r for r in P if acc(r, "naive") is not None]
244
- if P:
245
- cost = lambda r: (r["align_fit_seconds"] or 0.0)
246
- naive_a = float(np.mean([acc(r, "naive") for r in P]))
247
- all_a = float(np.mean([acc(r, "aligned") for r in P]))
248
- all_c = float(sum(cost(r) for r in P))
249
- picked = [r for r in P if r["coord_share"] >= THRESH]
250
- sel_a = float(np.mean([acc(r, "aligned") if r["coord_share"] >= THRESH else acc(r, "naive") for r in P]))
251
- sel_c = float(sum(cost(r) for r in picked))
252
- sel = [("merge naive (never align)", 0.0, naive_a, 0),
253
- ("align everything", all_c, all_a, len(P)),
254
- (f"diagnose -> align if coord_share >= {THRESH}", sel_c, sel_a, len(picked))]
255
- with open(f"{RES}/selection_experiment.csv", "w") as f:
256
- f.write("strategy,alignment_seconds,mean_ifeval_prompt_acc,n_aligned,n_pairs,compute_saved_pct\n")
257
- for nm, c, a, n in sel:
258
- sv = 100 * (1 - c / all_c) if all_c else 0.0
259
- f.write(f'"{nm}",{c:.1f},{a:.4f},{n},{len(P)},{sv:.1f}\n')
260
- fig, ax = plt.subplots(figsize=(7.2, 3.2))
261
- y = np.arange(len(sel))
262
- ax.barh(y, [s[2] for s in sel], color=["#94a3b8", CR, CG], height=0.55)
263
- ax.set_yticks(y); ax.set_yticklabels([s[0] for s in sel], fontsize=8)
264
- for i, s in enumerate(sel):
265
- sv = 100 * (1 - s[1] / all_c) if all_c else 0.0
266
- ax.text(s[2] + 0.004, i, f"acc {s[2]:.3f} align cost {s[1]:.0f}s ({sv:.0f}% saved)",
267
- va="center", fontsize=7.5)
268
- ax.set_xlim(0, max(s[2] for s in sel) * 1.7); ax.invert_yaxis()
269
- ax.set_xlabel("mean IFEval strict prompt accuracy")
270
- ax.set_title("Selection experiment: which pairs are worth aligning?", fontsize=9.5, loc="left")
271
- fig.tight_layout(); fig.savefig(f"{FIG}/selection_experiment.png", bbox_inches="tight"); plt.close(fig)
272
- print("figs:", sorted(os.listdir(FIG)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
 
274
  # ---- rung-4 supporting rows
275
  r4rows_md = []
@@ -443,16 +488,108 @@ for r in sorted(rows, key=lambda z: (z["is_control"], z["coord_share"], z["fork"
443
  A("")
444
 
445
  if sel:
446
- A("## 3. Selection experiment")
 
 
 
 
 
 
 
447
  A("")
448
- A("| strategy | alignment compute | mean IFEval prompt acc | pairs aligned | compute saved |")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
  A("|---|---|---|---|---|")
450
  allc = sel[1][1]
451
  for nm, c, a, n in sel:
452
- A(f"| {nm} | {c:.0f}s | **{a:.4f}** | {n}/{len(P)} | {100*(1-c/allc) if allc else 0:.0f}% |")
453
  A("")
 
 
 
 
 
 
 
 
 
 
 
 
454
 
455
  # ---- coverage --------------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
  A("## 4. Coverage")
457
  A("")
458
  A("| model / cell | diagnostic | fork alone | naive | aligned |")
 
209
  fig.tight_layout(rect=[0, 0, 1, 0.93])
210
  fig.savefig(f"{FIG}/scatter_naive_vs_aligned.png", bbox_inches="tight"); plt.close(fig)
211
 
212
+ # ---- dose-response: the diagnostic vs the true amount of frame drift, and the payoff --------
213
+ ctl = sorted([r for r in rows if r["is_control"] and r["lam"] == 1.0],
214
+ key=lambda r: r["frac_layers_permuted"])
215
+ ref = next((r for r in rows if r["fork"] == "swallow_ja" and r["lam"] == 1.0), None)
216
  if ctl:
217
+ fig, ax = plt.subplots(1, 2, figsize=(10.4, 3.9))
218
  ax[0].plot([r["frac_layers_permuted"] for r in ctl], [r["coord_share"] for r in ctl],
219
+ "o-", color=CC, lw=2, ms=9, mec="white", mew=1.2)
220
+ ax[0].axhline(THRESH, color="#b45309", ls=":", lw=1.2)
221
+ ax[0].annotate(f"decision threshold {THRESH}", (0.27, THRESH), textcoords="offset points",
222
+ xytext=(0, 7), fontsize=7.5, color="#b45309")
223
+ ax[0].set_ylim(0, 1.0)
224
  ax[0].set_xlabel("fraction of layers actually re-parameterised (ground truth)")
225
+ ax[0].set_ylabel("coordinate share (the diagnostic)")
226
+ ax[0].set_title("The diagnostic tracks real frame drift", fontsize=9.5, loc="left",
227
+ color="#334155")
228
+ # blue/green pair: CVD dE 24.9 deutan; line style + direct labels are the secondary encoding
229
+ for m, c, nm in (("ifeval_prompt", CR, "IFEval prompt"), ("tgt", CG, "Belebele target")):
230
+ xs = [r["frac_layers_permuted"] for r in ctl]
231
+ ax[1].plot(xs, [r[f"{m}__naive"] for r in ctl], "o--", color=c, alpha=0.5, lw=2, ms=8,
232
+ mec="white", mew=1.2, label=f"{nm}: naive")
233
+ ax[1].plot(xs, [r[f"{m}__aligned"] for r in ctl], "o-", color=c, lw=2.4, ms=9,
234
+ mec="white", mew=1.2, label=f"{nm}: aligned")
235
+ if ref is not None:
236
+ ax[1].axhline(ref[f"{m}__naive"], color=c, lw=1, ls=(0, (1, 3)), alpha=0.85)
237
+ ax[1].annotate(f"unpermuted fork + chat vector", (1.0, ref[f"{m}__naive"]),
238
+ textcoords="offset points", xytext=(-4, 5), fontsize=6.8,
239
+ color=c, ha="right")
240
  ax[1].set_xlabel("fraction of layers re-parameterised")
241
  ax[1].set_ylabel("accuracy")
242
+ ax[1].set_title("Alignment recovers what re-parameterisation destroys",
243
+ fontsize=9.5, loc="left", color="#334155")
244
+ ax[1].legend(fontsize=7, frameon=False, loc="center left")
245
+ fig.tight_layout(); fig.savefig(f"{FIG}/dose_response.png", bbox_inches="tight")
246
+ plt.close(fig)
247
 
248
+
249
+ # ---- SELECTION EXPERIMENT ---------------------------------------------------------------------
250
+ # Honest accounting. The `coord_share` used everywhere else is obtained BY fitting g, so
251
+ # "diagnose, then align" cannot claim to save the fit -- they are the same computation, and a
252
+ # selection experiment built on it would be vacuous. What decides the question is whether the
253
+ # frame can be checked WITHOUT the fit. It can: evaluating the weight-matching gain on a few
254
+ # hundred sampled columns of every layer already pins each row to itself when nothing was
255
+ # permuted. That screen is `cheap_screen.py`; the numbers below are measured, not assumed.
256
+ SCREEN = {}
257
+ try:
258
+ SCREEN = json.load(open(f"{RES}/cheap_screen.json"))
259
+ except Exception:
260
+ pass
261
+
262
+ APPLY_AND_EVAL_S = 300.0 # apply g to the 8B chat vector + build and score the second model
263
  sel = []
264
+ if rows and SCREEN:
265
  best = {}
266
+ for r in rows:
267
+ k = r["fork"]
268
+ if k not in best or (r["lam"] == 1.0 and best[k]["lam"] != 1.0):
269
+ best[k] = r
270
+ P = [r for r in best.values() if r.get("ifeval_prompt__naive") is not None]
271
+ def scr(r):
272
+ return SCREEN.get(r["fork"], {})
273
+ fit = lambda r: (r["align_fit_seconds"] or 0.0)
274
+ screen_s = lambda r: scr(r).get("screen_seconds", 0.0)
275
+ flagged = lambda r: scr(r).get("screen_says_aligned_needed", True)
276
+ acc = lambda r, arm: r[f"ifeval_prompt__{arm}"]
277
+
278
+ naive_a = float(np.mean([acc(r, "naive") for r in P]))
279
+ all_a = float(np.mean([acc(r, "aligned") for r in P]))
280
+ all_c = float(sum(fit(r) + APPLY_AND_EVAL_S for r in P))
281
+ picked = [r for r in P if flagged(r)]
282
+ sel_a = float(np.mean([acc(r, "aligned") if flagged(r) else acc(r, "naive") for r in P]))
283
+ sel_c = float(sum(screen_s(r) for r in P) + sum(fit(r) + APPLY_AND_EVAL_S for r in picked))
284
+ sel = [("merge naive (never align)", 0.0, naive_a, 0),
285
+ ("align everything", all_c, all_a, len(P)),
286
+ ("cheap screen -> align only when it fires", sel_c, sel_a, len(picked))]
287
+
288
+ agree = sum(1 for r in P if flagged(r) == (r["coord_share"] >= THRESH))
289
+ with open(f"{RES}/selection_experiment.csv", "w") as f:
290
+ f.write("strategy,compute_seconds,mean_ifeval_prompt_acc,n_aligned,n_pairs,compute_saved_pct\n")
291
+ for nm, c, a, n in sel:
292
+ f.write(f'"{nm}",{c:.0f},{a:.4f},{n},{len(P)},{100*(1-c/all_c) if all_c else 0:.1f}\n')
293
+ with open(f"{RES}/cheap_screen_vs_full.csv", "w") as f:
294
+ f.write("model,screen_seconds,identity_fraction_worst_layer,screen_says_align,"
295
+ "full_fit_seconds,full_coord_share,full_says_align,agree\n")
296
+ for r in sorted(P, key=lambda z: z["coord_share"]):
297
+ sc = scr(r)
298
+ f.write(f'{r["fork"]},{sc.get("screen_seconds",0):.1f},'
299
+ f'{sc.get("identity_fraction_worst_layer","")},{flagged(r)},'
300
+ f'{fit(r):.0f},{r["coord_share"]:.4f},{r["coord_share"]>=THRESH},'
301
+ f'{flagged(r)==(r["coord_share"]>=THRESH)}\n')
302
+
303
+ fig, ax = plt.subplots(figsize=(7.6, 3.2))
304
+ y = np.arange(len(sel))
305
+ ax.barh(y, [s[2] for s in sel], color=["#94a3b8", CR, CG], height=0.55)
306
+ ax.set_yticks(y); ax.set_yticklabels([s[0] for s in sel], fontsize=8)
307
+ for i, s in enumerate(sel):
308
+ sv = 100 * (1 - s[1] / all_c) if all_c else 0.0
309
+ ax.text(s[2] + 0.005, i, f"acc {s[2]:.3f} {s[1]/60:.0f} min ({sv:.0f}% saved)",
310
+ va="center", fontsize=7.5, color="#334155")
311
+ ax.set_xlim(0, max(s[2] for s in sel) * 1.75); ax.invert_yaxis()
312
+ ax.set_xlabel("mean IFEval strict prompt accuracy")
313
+ ax.set_title(f"Selection: the 43-second screen agrees with the 35-minute fit on {agree}/{len(P)} models",
314
+ fontsize=9.5, loc="left", color="#334155")
315
+ fig.tight_layout(); fig.savefig(f"{FIG}/selection_experiment.png", bbox_inches="tight")
316
+ plt.close(fig)
317
+
318
 
319
  # ---- rung-4 supporting rows
320
  r4rows_md = []
 
488
  A("")
489
 
490
  if sel:
491
+ A("## 3. Selection experiment — can we tell which models are worth aligning, cheaply?")
492
+ A("")
493
+ A("A diagnostic that costs as much as the thing it is deciding about is not a diagnostic. The")
494
+ A("`coordinate share` above is obtained **by fitting `g`**, which took **19–39 minutes per 8B")
495
+ A("model** here — so \"diagnose, then align\" would be circular if that were the only route to it.")
496
+ A("It is not. The frame can be checked without the fit: evaluate the weight-matching gain on a")
497
+ A("few hundred sampled columns of **every** layer and look at whether each row's best match is")
498
+ A("itself. That screen is `cheap_screen.py`.")
499
  A("")
500
+ A("| model | screen | worst-layer identity fraction | screen says | full fit | coord. share | full says | agree |")
501
+ A("|---|---|---|---|---|---|---|---|")
502
+ for r in sorted(P, key=lambda z: z["coord_share"]):
503
+ sc = SCREEN.get(r["fork"], {})
504
+ fl = sc.get("screen_says_aligned_needed", True)
505
+ ff = r["coord_share"] >= THRESH
506
+ A(f"| `{lab(r['fork'])}` | **{sc.get('screen_seconds', 0):.0f}s** | "
507
+ f"{sc.get('identity_fraction_worst_layer', float('nan')):.4f} | "
508
+ f"{'**ALIGN**' if fl else 'skip'} | {r['align_fit_seconds']:.0f}s | "
509
+ f"{r['coord_share']:.4f} | {'ALIGN' if ff else 'skip'} | {'yes' if fl == ff else '**NO**'} |")
510
+ A("")
511
+ A(f"The **{np.mean([SCREEN.get(r['fork'], {}).get('screen_seconds', 0) for r in P]):.0f}-second** screen "
512
+ f"reproduces the **{np.mean([r['align_fit_seconds'] for r in P])/60:.0f}-minute** fit's decision on "
513
+ f"**{agree}/{len(P)}** models, a **{np.mean([r['align_fit_seconds'] for r in P]) / max(np.mean([SCREEN.get(r['fork'], {}).get('screen_seconds', 1) for r in P]), 1e-9):.0f}x** reduction in "
514
+ "the cost of deciding. It separates cleanly: every real community fork scores ~0.984 (its worst")
515
+ A("layer is still essentially the identity), every re-parameterised control scores exactly 0.000.")
516
+ A("")
517
+ A("| strategy | compute | mean IFEval prompt acc | models aligned | compute saved |")
518
  A("|---|---|---|---|---|")
519
  allc = sel[1][1]
520
  for nm, c, a, n in sel:
521
+ A(f"| {nm} | {c/60:.0f} min | **{a:.4f}** | {n}/{len(P)} | {100*(1-c/allc) if allc else 0:.0f}% |")
522
  A("")
523
+ _real = [r for r in P if not r["is_control"]]
524
+ if _real:
525
+ _fit = sum(r["align_fit_seconds"] for r in _real)
526
+ _scr = sum(SCREEN.get(r["fork"], {}).get("screen_seconds", 0) for r in _real)
527
+ A(f"**Screen -> align-when-it-fires matches align-everything exactly ({sel[1][2]:.4f} vs "
528
+ f"{sel[2][2]:.4f}) at {100*(1-sel[2][1]/allc):.0f}% less compute.** That figure is diluted by this")
529
+ A("population being half constructed high-drift controls. On the part a practitioner actually")
530
+ A(f"faces — the {len(_real)} real community forks — the screen costs **{_scr:.0f}s** in total and")
531
+ A(f"correctly skips **all {len(_real)}**, replacing **{_fit/60:.0f} minutes** of alignment fitting with")
532
+ A(f"**{_scr/60:.1f} minutes** of screening (**{100*(1-_scr/_fit):.0f}%** saved) at **zero** accuracy cost,")
533
+ A("because on those models the aligned and naive merges are the same model.")
534
+ A("")
535
 
536
  # ---- coverage --------------------------------------------------------------------------------
537
+ # ---- lambda sweep ----------------------------------------------------------------------------
538
+ _lams = sorted({r["lam"] for r in rows})
539
+ if len(_lams) > 1:
540
+ A("## 3b. The mixing coefficient trades language capability against instruction following")
541
+ A("")
542
+ A("| fork | λ | Belebele target | Belebele eng | IFEval prompt | IFEval inst |")
543
+ A("|---|---|---|---|---|---|")
544
+ for r in sorted([x for x in rows if not x["is_control"]], key=lambda z: (z["fork"], z["lam"])):
545
+ A(f"| `{lab(r['fork'])}` | {r['lam']} | {r['tgt__naive']:.3f} | "
546
+ f"{r['belebele_eng_Latn__naive']:.3f} | {r['ifeval_prompt__naive']:.3f} | "
547
+ f"{r['ifeval_inst__naive']:.3f} |")
548
+ A("")
549
+ A("Halving λ buys target-language accuracy and gives back instruction following (Swallow:")
550
+ A("Japanese 0.680 -> 0.700 but IFEval 0.375 -> 0.270). There is no λ at which SEA-LION's chat")
551
+ A("vector pays: at λ=0.5 it lands at IFEval 0.350 against the fork's own 0.365.")
552
+ A("")
553
+
554
+ A("## 3c. What this does and does not establish")
555
+ A("")
556
+ A("**Established.** (i) The chat-vector recipe transfers real instruction-following ability to two")
557
+ A("of three community forks, and the merged model beats the fork it was built from on every axis —")
558
+ A("so the accuracy axis this project was missing does exist and is large. (ii) Alignment changes")
559
+ A("*nothing* on all three real forks, and the diagnostic said so in advance. (iii) When the frame")
560
+ A("genuinely has drifted, alignment recovers essentially all of the loss (IFEval 0.110 -> 0.355")
561
+ A("against an unpermuted reference of 0.375), so the mechanism is real and does reach accuracy.")
562
+ A("(iv) A 44-second screen decides which case you are in, 37x cheaper than fitting the map.")
563
+ A("")
564
+ A("**Not established, and worth stating plainly:**")
565
+ A("")
566
+ A("- **The high-drift arm is constructed, not found.** Every point above the threshold is a real")
567
+ A(" model acted on by a random element of its own symmetry group. We did not find a *released*")
568
+ A(" model whose frame had drifted. On the evidence here the answer to \"do community")
569
+ A(" continued-pretrained forks need their chat vector aligned?\" is **no, none of the three did** —")
570
+ A(" the failure mode the diagnostic repairs is real and repairable, but appears not to occur in")
571
+ A(" this corner of the ecosystem. That is the honest resolution, and it is a null.")
572
+ A("- **The null is a null for one group.** The search covers the residual-stream basis map, the")
573
+ A(" per-layer free MLP-hidden-axis permutation, and the GQA group-respecting head permutation. A")
574
+ A(" fork could in principle have drifted under a larger group (a general invertible change of")
575
+ A(" basis) that this search does not range over; we did not test that.")
576
+ A("- **Chat-vector failure is not always a coordinate problem.** SEA-LION's recipe fails — the")
577
+ A(" merged model is *worse* than the fork on ARC-easy (0.728 -> 0.614) and no better on")
578
+ A(" instruction following — and its coordinate share is exactly 0, so alignment has nothing to")
579
+ A(" offer it. Whatever is wrong there is not removable by reparameterisation.")
580
+ A("- **The cross-group pair says the same thing more starkly.** `pythia-1.4b` x `Zh-Pythia-1.4B` —")
581
+ A(" same architecture, different group, no shared ancestor — merges to **chance on every")
582
+ A(" benchmark** at every mixing weight and under TIES, and aligning first does not move it")
583
+ A(" (coordinate share 0.0034). Not every merge failure is a coordinate failure.")
584
+ A("- **Resolution.** Belebele n=300 and IFEval n=200 per cell; +/- 2 items is ~0.7% and ~1.0%.")
585
+ A(" Differences smaller than that are not interpretable, which is why the figures draw the floor.")
586
+ A(" The permutation controls use a single random group element (one seed).")
587
+ A("- **IFEval here is a re-implementation** over the 510 of 541 prompts whose every constraint our")
588
+ A(" verifiers check exactly. Its absolute values are not comparable to published IFEval numbers")
589
+ A(" (we score Llama-3.1-8B-Instruct at 0.540); every model is scored identically, so the")
590
+ A(" comparisons between rows are sound.")
591
+ A("")
592
+
593
  A("## 4. Coverage")
594
  A("")
595
  A("| model / cell | diagnostic | fork alone | naive | aligned |")