suchirsalhan commited on
Commit
328996f
·
verified ·
1 Parent(s): 9c8c5e7

Upload code/analyze.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. code/analyze.py +78 -26
code/analyze.py CHANGED
@@ -18,7 +18,14 @@ def load(p):
18
 
19
  CV, LG = load(f"{RES}/chatvec.jsonl"), load(f"{RES}/ledger.jsonl")
20
  diag = {r["fork"]: r["diag"] for r in CV if r.get("kind") == "diag"}
21
- refs = {r["arm"]: r for r in CV if r.get("kind") == "reference"}
 
 
 
 
 
 
 
22
  byfork = {}
23
  for r in CV:
24
  if r.get("kind") in ("fork", "merge", "control"): byfork.setdefault(r["fork"], []).append(r)
@@ -66,20 +73,21 @@ for fk, d in sorted(diag.items()):
66
 
67
  if rows:
68
  ks = sorted({k for r in rows for k in r})
69
- ks = ["fork", "lang", "lam", "is_control", "frac_layers_permuted", "coord_share"] + \
70
- [k for k in ks if k not in ("fork", "lang", "lam", "is_control", "frac_layers_permuted", "coord_share")]
 
71
  with open(f"{RES}/chatvec_summary.csv", "w") as f:
72
  f.write(",".join(ks) + "\n")
73
- for r in rows: f.write(",".join(str(r.get(k, "")) for k in ks) + "\n")
 
74
 
75
- # per-model raw accuracy table
76
  with open(f"{RES}/all_model_accuracies.csv", "w") as f:
77
  allm = sorted({m for r in CV if r.get("acc") for m in r["acc"]})
78
  f.write("key,kind,fork,arm,lam," + ",".join(allm) + "\n")
79
  for r in sorted(CV, key=lambda z: z["key"]):
80
  if not r.get("acc"): continue
81
  f.write(f'{r["key"]},{r.get("kind")},{r.get("fork")},{r.get("arm")},{r.get("lam")},'
82
- + ",".join(f'{r["acc"].get(m,""):.4f}' if isinstance(r["acc"].get(m), float) else ""
83
  for m in allm) + "\n")
84
 
85
  with open(f"{RES}/diagnostics.csv", "w") as f:
@@ -94,41 +102,85 @@ print(f"{len(rows)} summary rows, {len(diag)} diagnostics")
94
 
95
  # ================================================================== FIGURES
96
  plt.rcParams.update({"figure.dpi": 150, "font.size": 9, "axes.grid": True, "grid.alpha": 0.25,
97
- "axes.spines.top": False, "axes.spines.right": False})
 
 
 
98
  CR, CC, CG = "#2563eb", "#dc2626", "#059669"
99
  THRESH = 0.01
100
 
101
  def lab(fk):
102
- return fk.replace("_PERM", " perm ").replace("swallow_ja", "Swallow").replace(
103
- "typhoon2_th", "Typhoon2").replace("sealion_id", "SEA-LION")
104
 
105
- AXES = [("ifeval_prompt", "IFEval strict prompt accuracy\n(instruction following what the chat vector is FOR)"),
106
  ("tgt", "Belebele, target language\n(language capability)"),
107
  ("belebele_eng_Latn", "Belebele English\n(retention)")]
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  if rows:
110
- fig, axs = plt.subplots(1, 3, figsize=(13.2, 4.2))
111
  for ax, (m, ttl) in zip(axs, AXES):
112
- pts = [(r["coord_share"], r.get(f"{m}__delta"), r) for r in rows if r.get(f"{m}__delta") is not None]
 
 
 
 
 
 
113
  for x, y, r in pts:
114
- ax.scatter(x, y, s=40 + 90 * r["frac_layers_permuted"],
115
  c=CC if r["is_control"] else CR, marker="D" if r["is_control"] else "o",
116
- zorder=3, edgecolors="white", linewidths=0.9)
117
- ax.annotate(lab(r["fork"]), (x, y), textcoords="offset points", xytext=(7, 4), fontsize=6.5)
118
- ax.axhline(0, color="#111", lw=0.9)
119
- ax.axvline(THRESH, color="#f59e0b", lw=1.1, ls=":",
120
- label=f"decision threshold {THRESH}")
121
- ax.set_xlabel("pre-merge coordinate share (diagnostic, computed BEFORE any merge)")
122
- ax.set_ylabel("accuracy gain from aligning the chat vector")
123
- ax.set_title(ttl, fontsize=8.5, loc="left")
124
- ax.set_xscale("symlog", linthresh=1e-3)
 
 
 
 
125
  axs[0].scatter([], [], c=CR, s=60, label="real community CPT fork")
126
  axs[0].scatter([], [], c=CC, marker="D", s=60, label="permutation control (ground truth)")
127
- axs[0].legend(fontsize=7, frameon=False, loc="best")
 
 
 
 
 
128
  fig.suptitle("Does the pre-merge diagnostic predict whether the chat vector needs aligning?",
129
- fontsize=11.5, x=0.01, ha="left")
130
- fig.tight_layout(rect=[0, 0, 1, 0.93])
131
- fig.savefig(f"{FIG}/headline_diagnostic_vs_gain.png", bbox_inches="tight"); plt.close(fig)
 
132
 
133
  # ---- secondary: naive vs aligned, y = x -------------------------------------------------
134
  fig, axs = plt.subplots(1, 2, figsize=(9.6, 4.6))
 
18
 
19
  CV, LG = load(f"{RES}/chatvec.jsonl"), load(f"{RES}/ledger.jsonl")
20
  diag = {r["fork"]: r["diag"] for r in CV if r.get("kind") == "diag"}
21
+ # Reference rows were written by more than one worker, and a later worker that only knew about
22
+ # one target language would otherwise clobber the languages the first one measured. Merge the
23
+ # accuracy dicts across every reference record instead of taking the last write.
24
+ refs = {}
25
+ for r in CV:
26
+ if r.get("kind") == "reference":
27
+ cur = refs.setdefault(r["arm"], {"arm": r["arm"], "acc": {}, "model": r.get("model")})
28
+ cur["acc"].update(r.get("acc") or {})
29
  byfork = {}
30
  for r in CV:
31
  if r.get("kind") in ("fork", "merge", "control"): byfork.setdefault(r["fork"], []).append(r)
 
73
 
74
  if rows:
75
  ks = sorted({k for r in rows for k in r})
76
+ head = ["fork", "lang", "lam", "is_control", "g_is_effectively_identity",
77
+ "frac_layers_permuted", "coord_share", "predicted_align_helps"]
78
+ ks = head + [k for k in ks if k not in head]
79
  with open(f"{RES}/chatvec_summary.csv", "w") as f:
80
  f.write(",".join(ks) + "\n")
81
+ for r in rows:
82
+ f.write(",".join(str(r.get(k, "")) for k in ks) + "\n")
83
 
 
84
  with open(f"{RES}/all_model_accuracies.csv", "w") as f:
85
  allm = sorted({m for r in CV if r.get("acc") for m in r["acc"]})
86
  f.write("key,kind,fork,arm,lam," + ",".join(allm) + "\n")
87
  for r in sorted(CV, key=lambda z: z["key"]):
88
  if not r.get("acc"): continue
89
  f.write(f'{r["key"]},{r.get("kind")},{r.get("fork")},{r.get("arm")},{r.get("lam")},'
90
+ + ",".join(f'{r["acc"][m]:.4f}' if isinstance(r["acc"].get(m), float) else ""
91
  for m in allm) + "\n")
92
 
93
  with open(f"{RES}/diagnostics.csv", "w") as f:
 
102
 
103
  # ================================================================== FIGURES
104
  plt.rcParams.update({"figure.dpi": 150, "font.size": 9, "axes.grid": True, "grid.alpha": 0.25,
105
+ "axes.spines.top": False, "axes.spines.right": False,
106
+ "axes.edgecolor": "#94a3b8", "text.color": "#1e293b",
107
+ "axes.labelcolor": "#334155", "xtick.color": "#475569",
108
+ "ytick.color": "#475569"})
109
  CR, CC, CG = "#2563eb", "#dc2626", "#059669"
110
  THRESH = 0.01
111
 
112
  def lab(fk):
113
+ return (fk.replace("_PERM", " perm ").replace("swallow_ja", "Swallow")
114
+ .replace("typhoon2_th", "Typhoon2").replace("sealion_id", "SEA-LION"))
115
 
116
+ AXES = [("ifeval_prompt", "IFEval strict prompt accuracy\n(instruction following -- what the chat vector is FOR)"),
117
  ("tgt", "Belebele, target language\n(language capability)"),
118
  ("belebele_eng_Latn", "Belebele English\n(retention)")]
119
 
120
+ # cross-group point: coordinate share vs the accuracy change alignment produced (alpha = 0.5)
121
+ xg = None
122
+ try:
123
+ _d = next(r["diag"] for r in LG if r.get("arm") == "diag")
124
+ _cs = _d.get("coord_fraction_bn_perm", 0.0)
125
+ _n = next(r for r in LG if r.get("arm") == "naive" and r.get("alpha") == 0.5)
126
+ _a = next(r for r in LG if r.get("arm") == "aligned" and r.get("alpha") == 0.5)
127
+ xg = (_cs, _a["acc"]["mean"] - _n["acc"]["mean"])
128
+ except Exception:
129
+ xg = None
130
+
131
+ # Categorical palette validated with the dataviz six-checks (worst adjacent CVD dE 8.6 deutan,
132
+ # normal-vision 32.0, contrast all >= 3:1). Marker SHAPE carries identity too, which is the
133
+ # secondary encoding the 6-8 dE band requires.
134
+ RESOLUTION = 2.0 / 300.0 # +/- 2 items on a 300-item benchmark: what "no change" means here
135
+
136
+ def _group_annotate(ax, pts, dx=9, dy=5):
137
+ """Coincident points get ONE label, not three stacked on top of each other."""
138
+ b = {}
139
+ for x, y, name in pts:
140
+ b.setdefault((round(x, 6), round(y, 5)), []).append(name)
141
+ for (x, y), names in b.items():
142
+ ax.annotate(" / ".join(names), (x, y), textcoords="offset points",
143
+ xytext=(dx, dy), fontsize=7, color="#334155")
144
+
145
  if rows:
146
+ fig, axs = plt.subplots(1, 3, figsize=(13.4, 4.4))
147
  for ax, (m, ttl) in zip(axs, AXES):
148
+ pts = [(r["coord_share"], r.get(f"{m}__delta"), r) for r in rows
149
+ if r.get(f"{m}__delta") is not None]
150
+ ys = [y for _, y, _ in pts] + ([xg[1]] if (m == "tgt" and xg) else []) + [0.0]
151
+ lim = max(0.05, max(abs(v) for v in ys) * 1.35)
152
+ ax.axhspan(-RESOLUTION, RESOLUTION, color="#94a3b8", alpha=0.18, lw=0, zorder=0)
153
+ ax.axhline(0, color="#334155", lw=1.0, zorder=1)
154
+ ax.axvline(THRESH, color="#b45309", lw=1.1, ls=":", zorder=1)
155
  for x, y, r in pts:
156
+ ax.scatter(x, y, s=46 + 90 * r["frac_layers_permuted"],
157
  c=CC if r["is_control"] else CR, marker="D" if r["is_control"] else "o",
158
+ zorder=3, edgecolors="white", linewidths=1.2)
159
+ _group_annotate(ax, [(x, y, lab(r["fork"])) for x, y, r in pts])
160
+ if m == "tgt" and xg is not None:
161
+ ax.scatter(xg[0], xg[1], s=80, c=CG, marker="^", zorder=3,
162
+ edgecolors="white", linewidths=1.2)
163
+ ax.annotate("pythia x Zh-Pythia", (xg[0], xg[1]), textcoords="offset points",
164
+ xytext=(9, -13), fontsize=7, color="#334155")
165
+ ax.set_ylim(-lim, lim)
166
+ ax.set_xscale("symlog", linthresh=1e-3); ax.set_xlim(-2e-4, 1.8)
167
+ if ax is axs[0]:
168
+ ax.set_ylabel("accuracy gain from aligning")
169
+ ax.set_title(ttl, fontsize=8.5, loc="left", color="#334155")
170
+ ax.grid(alpha=0.22)
171
  axs[0].scatter([], [], c=CR, s=60, label="real community CPT fork")
172
  axs[0].scatter([], [], c=CC, marker="D", s=60, label="permutation control (ground truth)")
173
+ axs[0].scatter([], [], c=CG, marker="^", s=60, label="cross-group direct merge")
174
+ axs[0].plot([], [], color="#94a3b8", lw=6, alpha=0.35, label="+/- 2 items: measurement floor")
175
+ axs[0].plot([], [], ls=":", color="#b45309", label=f"decision threshold {THRESH}")
176
+ axs[0].legend(fontsize=7, frameon=False, loc="upper left")
177
+ fig.supxlabel("pre-merge coordinate share (the diagnostic, computed BEFORE any merge)",
178
+ fontsize=9.5, y=0.015)
179
  fig.suptitle("Does the pre-merge diagnostic predict whether the chat vector needs aligning?",
180
+ fontsize=12, x=0.006, ha="left")
181
+ fig.tight_layout(rect=[0, 0.05, 1, 0.93])
182
+ fig.savefig(f"{FIG}/headline_diagnostic_vs_gain.png", bbox_inches="tight")
183
+ plt.close(fig)
184
 
185
  # ---- secondary: naive vs aligned, y = x -------------------------------------------------
186
  fig, axs = plt.subplots(1, 2, figsize=(9.6, 4.6))