"""H1-H4 contrastive analysis of name sites in updates [50000,55000). Consumes out/alice_vs_megan/sites/* produced by scan_extract.py. Produces out/alice_vs_megan/stats/*.json, examples_*.txt, tables_*.md. """ import json, os, sys, math, random from collections import Counter, defaultdict import numpy as np REPO = "/mnt/nlpgpu-io1/data/maggie/explain-m0de-collapse/replicate" sys.path.insert(0, REPO) from scripts.name_lists import GIRLS BASE = os.path.join(REPO, "out/alice_vs_megan") SITES = os.path.join(BASE, "sites") STATS = os.path.join(BASE, "stats") os.makedirs(STATS, exist_ok=True) W = 131072 U0, U1 = 50000, 55000 BLOCK = 1024 EOS = 100257 NL = 198 K = 16 FOCUS = ["Alice", "Maria", "Mary", "Julia", "Ann", "Megan", "Karen", "Sarah"] from transformers import AutoTokenizer tok = AutoTokenizer.from_pretrained( os.path.join(REPO, "data/olmo3_prefix_hfstream_50b/tokenizer"), trust_remote_code=True) _dec_cache = {} def dec(i): i = int(i) if i not in _dec_cache: _dec_cache[i] = tok.decode([i]) return _dec_cache[i] sites = np.load(os.path.join(SITES, "sites_all.npz")) ctxs = np.load(os.path.join(SITES, "contexts_all.npz")) eos_pos = np.load(os.path.join(SITES, "eos_positions.npy")) h0 = json.load(open(os.path.join(SITES, "h0_counts.json"))) labels = [k[4:] for k in sites.files] # strip "pos_" def pos_of(lab): return sites[f"pos_{lab}"] def ctx_of(lab): return ctxs[f"ctx_{lab}"] HONOR = {"mrs","mr","ms","miss","aunt","auntie","aunty","lady","princess","queen", "sister","grandma","grandmother","mother","mom","mama","cousin","dr", "madam","madame","saint","st","mrs.","ms.","dr.","st.","dame"} PREPS = {"about","with","to","from","for","of","as","at","on","in","like"} QUOTES = set('"“”‘’\'`«»') def prev_cat(pid): s = dec(pid) if pid == EOS: return "doc_start" if pid == NL or s.endswith("\n"): return "newline" t = s.strip(); tl = t.lower() if not t: return "space" if tl in ("named","called"): return "named_called" if tl == "dear": return "dear" if tl == "and": return "and" if tl in HONOR: return "honorific_kin" if t[-1] in ".!?…": return "sentence_end" if t[-1] in QUOTES: return "quote_adj" if t[-1] == ":": return "colon" if t[-1] == ",": return "comma" if tl == "by": return "by" if tl in PREPS: return "prep" if t[0].isdigit(): return "digit" if s[0] == " " and t[0].isupper(): return "cap_word" if s[0] == " " and t[0].islower(): return "lower_word" if t[0].islower(): return "glue_lower" return "other" SLOT_CUES = {"named_called","dear","and","honorific_kin","sentence_end","quote_adj", "colon","doc_start","newline"} def next_cat(nid): s = dec(nid) if nid == EOS: return "doc_end" if nid == NL or s.startswith("\n"): return "newline" t = s.strip() if not t: return "space" if t in ("'s","’s"): return "possessive" if s[0] == " " and t[0].isupper() and t.replace("-","").replace(".","").isalpha(): return "cap_word" if s[0] == " " and t[0].islower(): return "lower_word" if not t[0].isalnum(): return "punct" if t[0].isdigit(): return "digit" if t[0].islower(): return "glue_lower" if t[0].isupper(): return "glue_cap" return "other" def entropy_bits(counter): n = sum(counter.values()) if n == 0: return 0.0 return -sum((c/n)*math.log2(c/n) for c in counter.values()) def gini(x): x = np.sort(np.asarray(x, dtype=np.float64)) n = len(x) if n == 0 or x.sum() == 0: return 0.0 return float((2*np.sum((np.arange(1,n+1))*x)/(n*x.sum())) - (n+1)/n) def profile(lab, seqlen=1): """H1/H4 context profile for one label.""" C = ctx_of(lab); P = pos_of(lab) n = len(P) if n == 0: return None prev1 = C[:, K-1]; prev2 = C[:, K-2]; nxt = C[:, K+seqlen] pc = Counter(prev_cat(p) for p in prev1) nc = Counter(next_cat(x) for x in nxt) prev_ctr = Counter(prev1.tolist()); next_ctr = Counter(nxt.tolist()) bg_ctr = Counter(zip(prev2.tolist(), prev1.tolist())) # context markers in left window: girl/story cues marks = {" girl": 3828, " story": 3446, " Once": 9843} mark_ids = {} for w, i in marks.items(): mark_ids[w] = i left = C[:, :K] girl_adj = np.zeros(n, bool) for w, i in mark_ids.items(): girl_adj |= (left == i).any(axis=1) out = { "n": n, "prev_entropy_bits": round(entropy_bits(prev_ctr), 3), "prev_eff_vocab": round(2**entropy_bits(prev_ctr), 1), "prev_bigram_entropy_bits": round(entropy_bits(bg_ctr), 3), "next_entropy_bits": round(entropy_bits(next_ctr), 3), "next_eff_vocab": round(2**entropy_bits(next_ctr), 1), "prev_top1_share": round(prev_ctr.most_common(1)[0][1]/n, 4), "prev_top5_share": round(sum(c for _,c in prev_ctr.most_common(5))/n, 4), "next_top1_share": round(next_ctr.most_common(1)[0][1]/n, 4), "next_top5_share": round(sum(c for _,c in next_ctr.most_common(5))/n, 4), "prev_cats": {k: round(v/n, 4) for k, v in pc.most_common()}, "next_cats": {k: round(v/n, 4) for k, v in nc.most_common()}, "slot_cue_frac": round(sum(v for k, v in pc.items() if k in SLOT_CUES)/n, 4), "followed_by_cap_frac": round(nc.get("cap_word", 0)/n, 4), "standalone_frac": round(1 - (nc.get("cap_word",0)+nc.get("glue_cap",0)+nc.get("glue_lower",0)+nc.get("digit",0))/n, 4), "girlstory_marker_left16_frac": round(float(girl_adj.mean()), 4), "top20_prev": [[dec(i), c] for i, c in prev_ctr.most_common(20)], "top20_next": [[dec(i), c] for i, c in next_ctr.most_common(20)], "top15_prev_bigram": [[dec(a)+dec(b), c] for (a, b), c in bg_ctr.most_common(15)], } return out def first_mention(pos_arr, union_pos=None): """H2: same-id (and optional any-variant) first-mention flags. Context for predicting token at g is [((g-1)//1024)*1024, g).""" p = np.sort(pos_arr) cstart = ((p - 1) // BLOCK) * BLOCK prev_same = np.concatenate(([np.int64(-1)], p[:-1])) fm_same = prev_same < cstart if union_pos is None: return p, fm_same, fm_same u = np.sort(union_pos) idx = np.searchsorted(u, p) # u[idx-1] = nearest union occurrence strictly before p prev_any = np.where(idx > 0, u[np.maximum(idx - 1, 0)], -1) fm_any = prev_any < cstart return p, fm_same, fm_any def dispersion(pos_arr): u = pos_arr // W - U0 hist = np.bincount(u, minlength=U1-U0) doc_idx = np.searchsorted(eos_pos, pos_arr) dc = Counter(doc_idx.tolist()) docs = np.array(sorted(dc.values()))[::-1] n = len(pos_arr) return { "n": int(n), "updates_with_ge1": int((hist > 0).sum()), "top_update_share": round(float(hist.max())/n, 4), "top10_updates_share": round(float(np.sort(hist)[-10:].sum())/n, 4), "gini_over_updates": round(gini(hist), 4), "n_docs": int(len(docs)), "sites_per_doc_mean": round(float(n/len(docs)), 2), "max_sites_one_doc": int(docs[0]), "top1_doc_share": round(float(docs[0])/n, 4), "top10_doc_share": round(float(docs[:10].sum())/n, 4), "docs_with_ge10_sites": int((docs >= 10).sum()), "frac_sites_in_docs_ge10": round(float(docs[docs >= 10].sum())/n, 4), "update_hist_argmax": int(np.argmax(hist) + U0), }, hist, dc # ---------- run all ---------- results = {"profiles": {}, "first_mention": {}, "dispersion": {}} hists = {} # focus labels incl. controls focus_labels = [] for nm in FOCUS: for form in ("sp", "bare"): lab = f"{form}_{nm}" if lab in labels: focus_labels.append(lab) for lab in focus_labels: seqlen = len(h0["patterns"][lab]["ids"]) prof = profile(lab, seqlen) if prof: results["profiles"][lab] = prof # split controls: bare_Alice after-newline (was swapped in CF) vs not (survived, impotent) cA = ctx_of("bare_Alice"); pA = pos_of("bare_Alice") after_nl = cA[:, K-1] == NL for sub, mask in (("bare_Alice_afterNL", after_nl), ("bare_Alice_other", ~after_nl)): if mask.sum() == 0: continue # build a temporary profile on the masked subset sub_ctx = cA[mask] prev_ctr = Counter(sub_ctx[:, K-1].tolist()); next_ctr = Counter(sub_ctx[:, K+1].tolist()) pc = Counter(prev_cat(p) for p in sub_ctx[:, K-1]) ncat = Counter(next_cat(x) for x in sub_ctx[:, K+1]) nn = int(mask.sum()) results["profiles"][sub] = { "n": nn, "prev_entropy_bits": round(entropy_bits(prev_ctr), 3), "next_entropy_bits": round(entropy_bits(next_ctr), 3), "prev_cats": {k: round(v/nn, 4) for k, v in pc.most_common()}, "next_cats": {k: round(v/nn, 4) for k, v in ncat.most_common()}, "slot_cue_frac": round(sum(v for k, v in pc.items() if k in SLOT_CUES)/nn, 4), "followed_by_cap_frac": round(ncat.get("cap_word", 0)/nn, 4), "top20_prev": [[dec(i), c] for i, c in prev_ctr.most_common(20)], "top20_next": [[dec(i), c] for i, c in next_ctr.most_common(20)], } # megan_bare (line-initial "M"+"egan") — the H0 star: what follows/precedes if "bare_Megan" in labels and len(pos_of("bare_Megan")): results["profiles"]["bare_Megan"] = profile("bare_Megan", seqlen=2) # H2 + H3 for focus names (union variants for any-variant FM) union_map = {} for nm in FOCUS: parts = [] for form in ("sp", "bare"): lab = f"{form}_{nm}" if lab in labels: parts.append(pos_of(lab)) union_map[nm] = np.concatenate(parts) if parts else np.empty(0, np.int64) for nm in FOCUS: lab = f"sp_{nm}" if lab not in labels or len(pos_of(lab)) == 0: continue p, fm_same, fm_any = first_mention(pos_of(lab), union_map[nm]) # earlier-mentions-in-context histogram (same id) cstart = ((p - 1) // BLOCK) * BLOCK nprev = np.array([np.searchsorted(p, g) - np.searchsorted(p, cs) for g, cs in zip(p, cstart)]) results["first_mention"][nm] = { "n": int(len(p)), "first_mention_same_id": int(fm_same.sum()), "fm_same_frac": round(float(fm_same.mean()), 4), "first_mention_any_variant": int(fm_any.sum()), "fm_any_frac": round(float(fm_any.mean()), 4), "repeats": int((~fm_same).sum()), "earlier_mentions_hist": {str(k): int(v) for k, v in sorted(Counter(np.minimum(nprev, 5).tolist()).items())}, } d, hist, dc = dispersion(pos_of(lab)) results["dispersion"][nm] = d hists[nm] = hist # bare_Megan dispersion (chat-log clustering test) if "bare_Megan" in labels and len(pos_of("bare_Megan")): d, hist, dc = dispersion(pos_of("bare_Megan")) results["dispersion"]["Megan_bare_lineinitial"] = d hists["Megan_bare_lineinitial"] = hist np.savez_compressed(os.path.join(STATS, "update_hists.npz"), **{k: v for k, v in hists.items()}) # ---------- cross-name dose-response regression ---------- probe = {} for r in map(json.loads, open(os.path.join( REPO, "out/olmo3_50b_ddp_resumecheck/name_slot_dist_v2.jsonl"))): if r["step"] in (50000, 55000) and r["prompt_label"] in ("girl_story", "girl_isnamed"): probe[(r["step"], r["prompt_label"])] = r["name_first_prob"] reg_rows = [] for nm in GIRLS: lab = f"sp_{nm}" if lab not in labels: continue if len(h0["patterns"][lab]["ids"]) > 1: continue # " Name" multi-token: probe P is a shared-first-token upper bound; excluded p = pos_of(lab) if len(p) == 0: raw = fm = slot = fm_slot = 0 ndocs = 0; g = 0.0 else: pp, fm_same, _ = first_mention(p) C = ctx_of(lab) cats = np.array([prev_cat(x) in SLOT_CUES for x in C[:, K-1]]) # align cats (ctx rows are in ascending pos order == sorted order) raw = len(p); fm = int(fm_same.sum()); slot = int(cats.sum()) order = np.argsort(p) fm_flags = fm_same # first_mention() sorted internally; positions ascending already fm_slot = int((fm_flags & cats[order]).sum()) d, _, _ = dispersion(p) ndocs = d["n_docs"]; g = d["gini_over_updates"] row = {"name": nm, "raw_sp": raw, "first_mention": fm, "slot_cue": slot, "fm_and_slot": fm_slot, "n_docs": ndocs, "gini": g} for (step, lblp), d_ in probe.items(): v = d_.get(nm) row[f"P{step//1000}k_{'story' if lblp=='girl_story' else 'named'}"] = ( v["p"] if isinstance(v, dict) else None) if row.get("P50k_story") is not None: row["dP_story"] = row["P55k_story"] - row["P50k_story"] row["dP_named"] = row["P55k_named"] - row["P50k_named"] reg_rows.append(row) def spearman(x, y): try: from scipy.stats import spearmanr r, pv = spearmanr(x, y) return round(float(r), 3), float(pv) except ImportError: def rank(v): a = np.argsort(v); rk = np.empty(len(v)); rk[a] = np.arange(len(v)) # average ties vv = np.asarray(v, float) for val in np.unique(vv): m = vv == val rk[m] = rk[m].mean() return rk rx, ry = rank(x), rank(y) r = float(np.corrcoef(rx, ry)[0, 1]) return round(r, 3), float("nan") reg = {"rows": sorted(reg_rows, key=lambda r: -(r.get("dP_story") or 0))} have = [r for r in reg_rows if r.get("dP_story") is not None and r["raw_sp"] > 0] try: xs = {k: [r[k] for r in have] for k in ("raw_sp","first_mention","slot_cue","fm_and_slot","n_docs")} y = [r["dP_story"] for r in have] y2 = [r["dP_named"] for r in have] reg["spearman_dP_story"] = {k: spearman(v, y) for k, v in xs.items()} reg["spearman_dP_named"] = {k: spearman(v, y2) for k, v in xs.items()} reg["n_names"] = len(have) except Exception as e: reg["spearman_error"] = str(e) with open(os.path.join(STATS, "analysis.json"), "w") as f: json.dump(results, f, indent=1) with open(os.path.join(STATS, "regression.json"), "w") as f: json.dump(reg, f, indent=1) # ---------- qualitative example dumps ---------- rng = random.Random(1234) def dump_examples(lab, fname, n_rand=40): P = pos_of(lab); C = ctx_of(lab) if len(P) == 0: return lines = [f"# {lab}: {len(P)} sites; ctx +-{K} tokens; site token in [[...]]\n"] idxs = rng.sample(range(len(P)), min(n_rand, len(P))) seqlen = len(h0["patterns"][lab]["ids"]) for i in sorted(idxs): row = C[i] left = tok.decode(row[:K].tolist()).replace("\n", "\\n") site = tok.decode(row[K:K+seqlen].tolist()).replace("\n", "\\n") right = tok.decode(row[K+seqlen:].tolist()).replace("\n", "\\n") u = int(P[i]) // W lines.append(f"upd {u} pos {int(P[i])}: {left}[[{site}]]{right}") # top-doc cluster examples doc_idx = np.searchsorted(eos_pos, P) top_docs = Counter(doc_idx.tolist()).most_common(3) for di, cnt in top_docs: lines.append(f"\n## top doc cluster: doc#{di} with {cnt} sites") sel = np.flatnonzero(doc_idx == di)[:5] for i in sel: row = C[i] left = tok.decode(row[:K].tolist()).replace("\n", "\\n") site = tok.decode(row[K:K+seqlen].tolist()).replace("\n", "\\n") right = tok.decode(row[K+seqlen:].tolist()).replace("\n", "\\n") lines.append(f" {left}[[{site}]]{right}") with open(os.path.join(STATS, fname), "w") as f: f.write("\n".join(lines) + "\n") for lab in focus_labels + (["bare_Megan"] if "bare_Megan" in labels else []): dump_examples(lab, f"examples_{lab}.txt") print("analysis written to", STATS) print(json.dumps({k: results["profiles"][k].get("slot_cue_frac") for k in results["profiles"]}, indent=1))