File size: 16,687 Bytes
5964f0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ============================================================================
# BLOCK 1 - H2 REBUILD.  CPU only.  Writes *_v2 artifacts; touches nothing published.
#
# Fixes, in order:
#   T1  panel halves rebalanced on prompt variant (variant == panel_index % 5,
#       so the old length-only stratification left half B with 3x the variant-4
#       questions of half A).  question_ids are UNCHANGED -> no regeneration.
#   T2  split-half cosine replaced by correlation of role projections, which has
#       real dynamic range, plus a role-label permutation null that actually moves.
#   T7  bootstrap and LORO recomputed on the new statistic; H4 compared on a FIXED
#       role set; per-layer nulls for the whole 32-layer curve.
# ============================================================================
CFG = {
    "OUT_ROOT": "/home/jupyter-ayjp-e788/assistant_axis",
    "HF_REPO":  "Parth4105/persona-artifacts",
    "RUN_ID":   "lu-replication/run-003",
    "COND":     "USER_EXPLICIT",
    "MID":      16,          # T02 may change this; Block 5 re-runs with the new value
    "MIN_RETAINED": 10,
    "MIN_PER_HALF": 5,
    "N_PERM":   2000,        # role-label permutation null (per layer)
    "N_SPLIT":  300,         # random variant-balanced 40/40 splits (middle layer)
    "N_BOOT":   2000,
    "SEED":     0,
    "HF_PUSH":  True,
}

import json, collections, hashlib, time, gc, sys
from pathlib import Path
import numpy as np, torch
from safetensors.torch import load_file

ROOT = Path(CFG["OUT_ROOT"]); ex, de = ROOT/"extraction", ROOT/"default"
MID, SEED = CFG["MID"], CFG["SEED"]
rng = np.random.default_rng(SEED)

def need(rel):
    """Local file, else pull it from the Hub."""
    p = ROOT / rel
    if p.exists(): return p
    from huggingface_hub import hf_hub_download
    print(f"  fetching {rel} from the Hub ...")
    p.parent.mkdir(parents=True, exist_ok=True)
    d = hf_hub_download(CFG["HF_REPO"], f"{CFG['RUN_ID']}/{rel}", repo_type="dataset")
    return Path(d)

# ---- 1. inputs -------------------------------------------------------------
panel = json.loads(need("design/panel.json").read_text("utf-8"))
PANEL = panel["question_ids"]
assert len(PANEL) == 80

meta = {}
for l in need("extraction/pooled_meta.jsonl").read_text("utf-8").splitlines():
    if l.strip(): m = json.loads(l); meta[m["uid"]] = m
scores = {}
for l in need("extraction/scores.jsonl").read_text("utf-8").splitlines():
    if l.strip(): s = json.loads(l); scores[s["uid"]] = s
print(f"{len(meta)} pooled, {len(scores)} scored")

# question text for length balance; fall back to id order if the vendor tree is gone
try:
    D = ROOT/"vendor"/"assistant-axis"/"data"
    QT = {json.loads(l)["id"]: json.loads(l)["question"]
          for l in (D/"extraction_questions.jsonl").read_text("utf-8").splitlines() if l.strip()}
    qlen = {q: len(QT[q]) for q in PANEL}
except Exception as e:
    print(f"  no vendor questions ({type(e).__name__}); balancing on question_id order")
    qlen = {q: q for q in PANEL}

# ---- 2. variant-balanced halves (T1) --------------------------------------
# prompt_idx was assigned as (index in PANEL) % 5, so variant is a deterministic
# function of question position. Split each residue class 8/8, ordered by length,
# so both halves get 8 questions of every variant AND matched length spread.
variant = {q: i % 5 for i, q in enumerate(PANEL)}
HA2, HB2 = [], []
for v in range(5):
    cls = sorted([q for q in PANEL if variant[q] == v], key=lambda q: qlen[q])
    HA2 += cls[0::2]; HB2 += cls[1::2]
HA2, HB2 = sorted(HA2), sorted(HB2)
assert len(HA2) == len(HB2) == 40 and not set(HA2) & set(HB2)
va = collections.Counter(variant[q] for q in HA2)
vb = collections.Counter(variant[q] for q in HB2)
print(f"panel_v2 variant balance  A={dict(sorted(va.items()))}  B={dict(sorted(vb.items()))}")
assert set(va.values()) == {8} and set(vb.values()) == {8}
old_a = collections.Counter(variant[q] for q in panel["half_a_ids"])
print(f"  (old half A was {dict(sorted(old_a.items()))} - this is what we are fixing)")

FP2 = hashlib.sha256(json.dumps([PANEL, HA2, HB2]).encode()).hexdigest()[:16]
panel2 = {"seed": SEED, "n": 80, "question_ids": PANEL, "half_a_ids": HA2,
          "half_b_ids": HB2, "fingerprint": FP2,
          "strategy": "halves balanced on prompt variant (index%5), 8 per variant "
                      "per half, ordered by question length within variant. "
                      "question_ids identical to panel.json - no regeneration.",
          "supersedes": "design/panel.json halves"}
(ROOT/"design").mkdir(parents=True, exist_ok=True)
(ROOT/"design"/"panel_v2.json").write_text(json.dumps(panel2, indent=2), "utf-8")
print(f"panel_v2 fingerprint {FP2}")

# ---- 3. retention on the new halves (no tensors needed) --------------------
SA, SB = set(HA2), set(HB2)
ret = collections.defaultdict(list); half = collections.defaultdict(lambda: [0, 0])
for uid, m in meta.items():
    if m.get("condition") != CFG["COND"]: continue
    s = scores.get(uid)
    if not s or not s.get("retained"): continue
    ret[m["role"]].append(uid)
    if m["question_id"] in SA: half[m["role"]][0] += 1
    elif m["question_id"] in SB: half[m["role"]][1] += 1
FULL = sorted(r for r, u in ret.items() if len(u) >= CFG["MIN_RETAINED"])
SH   = sorted(r for r in FULL if min(half[r]) >= CFG["MIN_PER_HALF"])
print(f"retained full-role vectors {len(FULL)} (gate 180) | split-half eligible "
      f"{len(SH)} (gate 150) | {'PASS' if len(FULL)>=180 and len(SH)>=150 else 'FAIL'}")
# how many clear Lu's own min_count=50, and the proportional equivalent 17/80
n50 = sum(1 for r in ret if len(ret[r]) >= 50)
n17 = sum(1 for r in ret if len(ret[r]) >= 17)
print(f"roles clearing Lu's min_count=50: {n50} | proportional equivalent 17/80: {n17}")

# ---- 4. one streaming pass -> per-role means at ALL layers -----------------
FULLS, SHS = set(FULL), set(SH)
shards = sorted(ex.glob("pooled_primary_*.safetensors"))
if not shards:
    shards = [need(f"extraction/pooled_primary_{i:02d}.safetensors") for i in range(3)]
groups = ("full", "half_a", "half_b", "unfilt")
acc, cnt = {g: {} for g in groups}, {g: collections.Counter() for g in groups}
NL = H = None
t0 = time.time()
for sh in shards:
    st = load_file(str(sh))
    for uid, t in st.items():
        m = meta.get(uid)
        if m is None or m.get("condition") != CFG["COND"]: continue
        r = m["role"]
        if r not in FULLS: continue          # H4 fix: SAME role set, filtered or not
        if NL is None: NL, H = t.shape
        v = t.float().numpy()
        def add(g):
            a = acc[g].get(r)
            if a is None: a = acc[g][r] = np.zeros((NL, H), np.float32)
            a += v; cnt[g][r] += 1
        add("unfilt")
        s = scores.get(uid)
        if not s or not s.get("retained"): continue
        add("full")
        if r in SHS:
            if   m["question_id"] in SA: add("half_a")
            elif m["question_id"] in SB: add("half_b")
    del st; gc.collect()
    print(f"  {sh.name} done ({time.time()-t0:.0f}s)")
means = {g: {r: acc[g][r]/cnt[g][r] for r in acc[g]} for g in groups}
del acc; gc.collect()
print(f"{NL} layers, hidden {H}; role means built for {len(means['full'])} roles")

dst = de/"pooled_primary_00.safetensors"
dst = dst if dst.exists() else need("default/pooled_primary_00.safetensors")
dd = load_file(str(dst))
DEF = np.stack([t.float().numpy() for t in dd.values()]).mean(0)   # (NL,H) unfiltered
print(f"default vector from {len(dd)} unfiltered outputs (Lu's construction)")
del dd; gc.collect()

# ---- 5. statistics ---------------------------------------------------------
def unit(x): return x / (np.linalg.norm(x) + 1e-12)
def pearson(a, b):
    a, b = a - a.mean(), b - b.mean()
    return float(a @ b / (np.linalg.norm(a)*np.linalg.norm(b) + 1e-12))
def rank(x):
    o = np.argsort(x, kind="mergesort"); r = np.empty(len(x), float); r[o] = np.arange(len(x))
    _, inv, c = np.unique(x, return_inverse=True, return_counts=True)   # average ties
    s = np.zeros(len(c)); np.add.at(s, inv, r); return (s/c)[inv]
def spearman(a, b): return pearson(rank(a), rank(b))
def cos(a, b): return float(a @ b / (np.linalg.norm(a)*np.linalg.norm(b) + 1e-12))

R = sorted(means["half_a"])           # roles with both halves
MA = np.stack([means["half_a"][r] for r in R])     # (nR, NL, H)
MB = np.stack([means["half_b"][r] for r in R])
MF = np.stack([means["full"][r]   for r in FULL])
MU = np.stack([means["unfilt"][r] for r in FULL])
print(f"statistic on {len(R)} roles; axes from {len(FULL)} roles")

per_layer = []
for L in range(NL):
    d = DEF[L]
    ua, ub = unit(d - MA[:, L].mean(0)), unit(d - MB[:, L].mean(0))
    uf = unit(d - MF[:, L].mean(0))
    pa, pb = MA[:, L] @ ua, MB[:, L] @ ub          # independent-axis projections
    fa, fb = MA[:, L] @ uf, MB[:, L] @ uf          # fixed-axis projections
    r_ind, r_fix, rho = pearson(pa, pb), pearson(fa, fb), spearman(pa, pb)
    # role-label permutation null: shuffling roles leaves the axis (a grand mean)
    # untouched but destroys the pairing, so this null has real variance.
    nul = np.array([pearson(pa, pb[rng.permutation(len(R))]) for _ in range(CFG["N_PERM"])])
    per_layer.append({
        "layer": L, "r_independent_axes": round(r_ind, 4),
        "r_fixed_axis": round(r_fix, 4), "spearman": round(rho, 4),
        "cosine_axes_legacy": round(cos(d - MA[:, L].mean(0), d - MB[:, L].mean(0)), 4),
        "null_mean": round(float(nul.mean()), 4), "null_sd": round(float(nul.std()), 4),
        "z": round(float((r_ind - nul.mean())/(nul.std() + 1e-12)), 2),
        "p_emp": float((nul >= r_ind).mean())})
    if L == MID: NUL_MID = nul
M = per_layer[MID]
print(f"\nMIDDLE LAYER {MID}")
print(f"  r (independent axes)   {M['r_independent_axes']:.4f}   "
      f"null {M['null_mean']:.4f} +- {M['null_sd']:.4f}   z={M['z']}  p={M['p_emp']:.4g}")
print(f"  r (fixed full axis)    {M['r_fixed_axis']:.4f}")
print(f"  spearman               {M['spearman']:.4f}")
print(f"  legacy cosine          {M['cosine_axes_legacy']:.4f}  <- the ceilinged number")

# bootstrap + LORO on the new statistic (real dynamic range now)
d = DEF[MID]
ua, ub = unit(d - MA[:, MID].mean(0)), unit(d - MB[:, MID].mean(0))
pa, pb = MA[:, MID] @ ua, MB[:, MID] @ ub
boot = np.array([pearson(pa[i], pb[i]) for i in
                 (rng.integers(0, len(R), len(R)) for _ in range(CFG["N_BOOT"]))])
keep = np.arange(len(R))
loro = np.array([pearson(pa[keep != i], pb[keep != i]) for i in range(len(R))])
print(f"  bootstrap CI95         [{np.percentile(boot,2.5):.4f}, {np.percentile(boot,97.5):.4f}]")
print(f"  LORO min {loro.min():.4f} max {loro.max():.4f} "
      f"(most influential: {R[int(loro.argmin())]})")

# ---- 6. random variant-balanced splits, middle layer (T1 sensitivity) ------
rm = ex/"reduced_rollout_middle.safetensors"
rm = rm if rm.exists() else need("extraction/reduced_rollout_middle.safetensors")
mid_st = load_file(str(rm))
keep_uids = [u for r in SH for u in ret[r]]
V   = np.stack([mid_st[u].float().numpy() for u in keep_uids])         # (n, H)
ri  = np.array([R.index(meta[u]["role"]) for u in keep_uids])
qi  = np.array([meta[u]["question_id"] for u in keep_uids])
del mid_st; gc.collect()
byv = {v: [q for q in PANEL if variant[q] == v] for v in range(5)}
splits = []
for _ in range(CFG["N_SPLIT"]):
    A = set()
    for v in range(5): A |= set(rng.choice(byv[v], 8, replace=False))
    ma, mb = np.isin(qi, list(A)), ~np.isin(qi, list(A))
    ca, cb = np.bincount(ri[ma], minlength=len(R)), np.bincount(ri[mb], minlength=len(R))
    ok = (ca >= CFG["MIN_PER_HALF"]) & (cb >= CFG["MIN_PER_HALF"])
    if ok.sum() < 50: continue
    Ia = np.zeros((len(R), len(V)), np.float32); Ia[ri[ma], np.where(ma)[0]] = 1
    Ib = np.zeros((len(R), len(V)), np.float32); Ib[ri[mb], np.where(mb)[0]] = 1
    A_ = (Ia @ V)[ok] / ca[ok, None]; B_ = (Ib @ V)[ok] / cb[ok, None]
    dm = DEF[MID]
    splits.append(pearson(A_ @ unit(dm - A_.mean(0)), B_ @ unit(dm - B_.mean(0))))
splits = np.array(splits)
print(f"  across {len(splits)} random variant-balanced splits: mean {splits.mean():.4f} "
      f"CI95 [{np.percentile(splits,2.5):.4f}, {np.percentile(splits,97.5):.4f}]")

# ---- 7. H4 on a FIXED role set, and PC1 -----------------------------------
ax_f = DEF[MID] - MF[:, MID].mean(0); ax_u = DEF[MID] - MU[:, MID].mean(0)
h4 = {"roles_both": len(FULL), "cosine_filtered_vs_unfiltered": round(cos(ax_f, ax_u), 4),
      "note": "same 262 roles on both sides; the old comparison used 275 unfiltered "
              "vs 262 filtered and confounded filtering with role set"}
print(f"\nH4 filtered vs unfiltered axis, same {len(FULL)} roles: "
      f"cosine {h4['cosine_filtered_vs_unfiltered']:.4f}")

Mc = MF[:, MID] - MF[:, MID].mean(0)
_, S, Vt = np.linalg.svd(Mc, full_matrices=False)
var = S**2/(S**2).sum(); pc1 = Vt[0]
if pc1 @ ax_f < 0: pc1 = -pc1
proj = Mc @ pc1; dpos = (DEF[MID] - MF[:, MID].mean(0)) @ pc1
beyond = [FULL[i] for i in np.where(proj > dpos)[0]]
rel = float((dpos - proj.min())/(proj.max() - proj.min() + 1e-12))
print(f"PC1 var {var[0]:.4f} | axis-PC1 cos {cos(pc1, ax_f):.4f} | default rel pos {rel:.4f}")
print(f"  roles projecting BEYOND the default on PC1 ({len(beyond)}): {beyond}")

# ---- 8. write + push -------------------------------------------------------
out = {
  "supersedes": "extraction/geometry.json H2_reliability + stability blocks",
  "panel": "design/panel_v2.json", "panel_fingerprint": FP2,
  "middle_layer": MID, "n_layers": NL, "condition": CFG["COND"],
  "gates": {"retained_full_role_vectors": len(FULL), "split_half_eligible_roles": len(SH),
            "pass": bool(len(FULL) >= 180 and len(SH) >= 150),
            "min_retained": CFG["MIN_RETAINED"],
            "roles_clearing_lu_min_count_50": n50,
            "roles_clearing_proportional_17_of_80": n17,
            "note": "Lu's 4_vectors.py default is min_count=50 on 240 questions "
                    "(20.8%); 10 of 80 is 12.5%. The proportional equivalent is 17."},
  "H2": {"primary": "pearson correlation across roles of projections onto the "
                    "half-specific Axis; the legacy cosine is reported alongside "
                    "because its null sits at 0.96 and it cannot fall below it",
         "middle": M, "per_layer": per_layer,
         "bootstrap_ci95": [round(float(np.percentile(boot, 2.5)), 4),
                            round(float(np.percentile(boot, 97.5)), 4)],
         "loro_min": round(float(loro.min()), 4), "loro_max": round(float(loro.max()), 4),
         "most_influential_role": R[int(loro.argmin())],
         "random_split_mean": round(float(splits.mean()), 4),
         "random_split_ci95": [round(float(np.percentile(splits, 2.5)), 4),
                               round(float(np.percentile(splits, 97.5)), 4)],
         "n_splits": len(splits), "n_perm": CFG["N_PERM"], "n_roles": len(R)},
  "H4": h4,
  "pc1_descriptive": {"variance_fraction": round(float(var[0]), 4),
      "components_to_70pct": int(np.searchsorted(np.cumsum(var), 0.70)+1),
      "axis_to_pc1_cosine": round(cos(pc1, ax_f), 4),
      "default_relative_position": round(rel, 4),
      "roles_projecting_beyond_default": beyond,
      "note": "the position statistic can exceed 1; 0.93 means the default is near, "
              "not at, the extreme"},
}
(ex/"geometry_v2.json").write_text(json.dumps(out, indent=2), "utf-8")
np.save(ex/"h2_v2_perm_null_middle.npy", NUL_MID)
np.save(ex/"h2_v2_split_distribution.npy", splits)
np.save(ex/"h2_v2_bootstrap.npy", boot)
print("\nwrote geometry_v2.json + 3 distributions")

if CFG["HF_PUSH"]:
    from huggingface_hub import HfApi
    api = HfApi()
    src = ROOT/"worker_geometry_v2.py"
    try:    src.write_text(In[-1], "utf-8")          # archive this cell verbatim
    except Exception: src.write_text("# source not captured\n", "utf-8")
    for lp, dest in ((ROOT/"design"/"panel_v2.json", "design/panel_v2.json"),
                     (ex/"geometry_v2.json", "extraction/geometry_v2.json"),
                     (ex/"h2_v2_perm_null_middle.npy", "extraction/h2_v2_perm_null_middle.npy"),
                     (ex/"h2_v2_split_distribution.npy", "extraction/h2_v2_split_distribution.npy"),
                     (ex/"h2_v2_bootstrap.npy", "extraction/h2_v2_bootstrap.npy"),
                     (src, "code/worker_geometry_v2.py")):
        api.upload_file(path_or_fileobj=str(lp), repo_id=CFG["HF_REPO"], repo_type="dataset",
                        path_in_repo=f"{CFG['RUN_ID']}/{dest}")
        print(f"  pushed {dest}")
print("\nReport r_independent_axes with its permutation null. Report the legacy "
      "cosine only next to its 0.96 null, never alone.")