"""Register/genre metrics per site + effective-dose decomposition (H1/H4 refinement). For each focus name's " Name" sites: fraction with dialogue/fiction/story cues in the +-16 context; joint effective-dose counts (first-mention x standalone x non-megacluster); Alice site-category mixture; dP_named vs first-mention check. """ import json, os, sys, math from collections import Counter import numpy as np REPO = "/mnt/nlpgpu-io1/data/maggie/explain-m0de-collapse/replicate" sys.path.insert(0, REPO) BASE = os.path.join(REPO, "out/alice_vs_megan") SITES = os.path.join(BASE, "sites") STATS = os.path.join(BASE, "stats") W = 131072; U0 = 50000; 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) 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"))) def pos_of(lab): return sites[f"pos_{lab}"] def ctx_of(lab): return ctxs[f"ctx_{lab}"] # --- build id sets for register cues by scanning the whole vocab once --- QUOTE_CHARS = set('"“”‘’«»') quote_ids, said_ids, narr_ids, she_ids, girlstory_ids = set(), set(), set(), set(), set() NARR = {"was","were","had","said","asked","replied","smiled","looked","went","cried", "shouted","whispered","thought","felt","saw","heard","knew","wanted","began"} SHE = {"she","her","hers","herself"} GIRLSTORY = {"girl","story","once","princess","little","fairy","mother","doll","school", "child","children","daughter","sister"} for i in range(100278): try: s = tok.decode([i]) except Exception: continue if any(c in QUOTE_CHARS for c in s): quote_ids.add(i) t = s.strip().lower() if t in ("said", "says"): said_ids.add(i) if t in NARR: narr_ids.add(i) if t in SHE: she_ids.add(i) if t in GIRLSTORY: girlstory_ids.add(i) def idmask(idset): m = np.zeros(100352, bool) m[list(idset)] = True return m M_quote, M_said, M_narr, M_she, M_gs = map(idmask, (quote_ids, said_ids, narr_ids, she_ids, girlstory_ids)) def cap_follow_mask(ctx, seqlen): """next token is ' Xxx' capitalized alpha => part of multi-word name.""" nxt = ctx[:, K+seqlen] out = np.zeros(len(ctx), bool) cache = {} for j, i in enumerate(nxt.tolist()): if i not in cache: s = tok.decode([i]); t = s.strip() cache[i] = bool(t) and s[0] == " " and t[0].isupper() and t.replace("-","").replace(".","").isalpha() out[j] = cache[i] return out def glue_mask(ctx, seqlen): nxt = ctx[:, K+seqlen] out = np.zeros(len(ctx), bool) cache = {} for j, i in enumerate(nxt.tolist()): if i not in cache: s = tok.decode([i]) cache[i] = bool(s) and (s[0].isalnum()) # no leading space => glued piece out[j] = cache[i] return out def first_mention_flags(p): p = np.sort(p) cstart = ((p - 1) // BLOCK) * BLOCK prev_same = np.concatenate(([np.int64(-1)], p[:-1])) return prev_same < cstart rows = {} for nm in FOCUS: lab = f"sp_{nm}" p = pos_of(lab); C = ctx_of(lab) n = len(p) if n == 0: continue seqlen = len(h0["patterns"][lab]["ids"]) left = C[:, :K]; right = C[:, K+seqlen:] both = np.concatenate([left, right], axis=1) fm = first_mention_flags(p) cap_f = cap_follow_mask(C, seqlen) glue_f = glue_mask(C, seqlen) standalone = ~(cap_f | glue_f) doc_idx = np.searchsorted(eos_pos, p) dc = Counter(doc_idx.tolist()) mega = np.array([dc[d] >= 10 for d in doc_idx]) quote_any = M_quote[both].any(axis=1) said_any = M_said[both].any(axis=1) narr_any = M_narr[both].any(axis=1) she_any = M_she[both].any(axis=1) gs_any = M_gs[both].any(axis=1) fiction = quote_any | said_any | (narr_any & she_any) eff = fm & standalone eff_nomega = eff & ~mega rows[nm] = { "n_raw": int(n), "standalone": int(standalone.sum()), "first_mention": int(fm.sum()), "eff_fm_standalone": int(eff.sum()), "eff_fm_standalone_nomega": int(eff_nomega.sum()), "pct_quote_ctx": round(float(quote_any.mean()), 4), "pct_said_ctx": round(float(said_any.mean()), 4), "pct_narrpast_ctx": round(float(narr_any.mean()), 4), "pct_she_her_ctx": round(float(she_any.mean()), 4), "pct_girlstory_ctx": round(float(gs_any.mean()), 4), "pct_fiction_proxy": round(float(fiction.mean()), 4), "eff_fiction": int((eff & fiction).sum()), "eff_nomega_fiction": int((eff_nomega & fiction).sum()), "pct_fiction_among_eff": round(float(fiction[eff].mean()), 4) if eff.sum() else 0.0, } print(f"{'name':>7} {'raw':>5} {'stand':>6} {'fm':>5} {'fm&st':>6} {'fm&st&!mega':>11} " f"{'quote%':>7} {'said%':>6} {'she%':>6} {'narr%':>6} {'girlst%':>7} {'fict%':>6} " f"{'effFict':>7} {'effnmFict':>9}") for nm, d in rows.items(): print(f"{nm:>7} {d['n_raw']:>5} {d['standalone']:>6} {d['first_mention']:>5} " f"{d['eff_fm_standalone']:>6} {d['eff_fm_standalone_nomega']:>11} " f"{d['pct_quote_ctx']:>7.3f} {d['pct_said_ctx']:>6.3f} {d['pct_she_her_ctx']:>6.3f} " f"{d['pct_narrpast_ctx']:>6.3f} {d['pct_girlstory_ctx']:>7.3f} {d['pct_fiction_proxy']:>6.3f} " f"{d['eff_fiction']:>7} {d['eff_nomega_fiction']:>9}") # --- Alice site-category mixture (compare to prior autopsy 40/20/32) --- lab = "sp_Alice"; C = ctx_of(lab); p = pos_of(lab) left = C[:, :K]; both = np.concatenate([left, C[:, K+1:]], axis=1) prev1 = C[:, K-1] DEAR = tok(" Dear", add_special_tokens=False)["input_ids"][0] BOB = tok(" Bob", add_special_tokens=False)["input_ids"][0] WLAND = tok(" Wonderland", add_special_tokens=False)["input_ids"] cats = Counter() w_first = np.zeros(len(p), bool) dear_ctx = (both == DEAR).any(axis=1) bob_ctx = (both == BOB).any(axis=1) wl_ctx = np.zeros(len(p), bool) if len(WLAND) == 1: wl_ctx = (both == WLAND[0]).any(axis=1) quote_any = M_quote[both].any(axis=1) said_any = M_said[both].any(axis=1) she_any = M_she[both].any(axis=1) gs_any = M_gs[both].any(axis=1) for i in range(len(p)): if dear_ctx[i]: cats["dear_alice_column"] += 1 elif bob_ctx[i]: cats["alice_and_bob_crypto"] += 1 elif wl_ctx[i]: cats["wonderland"] += 1 elif quote_any[i] or said_any[i]: cats["dialogue_quote"] += 1 elif she_any[i] or gs_any[i]: cats["girl_narrative"] += 1 else: cats["other"] += 1 alice_mix = {k: [v, round(v/len(p), 3)] for k, v in cats.most_common()} print("\nAlice site mixture:", json.dumps(alice_mix, indent=1)) # --- dP_named / dP_story vs effective dose among raw>=300 names --- reg = json.load(open(os.path.join(STATS, "regression.json"))) big = [r for r in reg["rows"] if r.get("dP_story") is not None and r["raw_sp"] >= 300] from scipy.stats import spearmanr for target in ("dP_named", "dP_story"): y = [r[target] for r in big] out = {} for k in ("raw_sp", "first_mention", "slot_cue", "fm_and_slot"): rho, pv = spearmanr([r[k] for r in big], y) out[k] = (round(float(rho), 3), round(float(pv), 5)) print(f"\nSpearman {target} (n={len(big)} names raw>=300):", out) top_named = sorted(big, key=lambda r: -r["dP_named"])[:8] print("\ntop dP_named:", [(r['name'], round(r['dP_named'],5), 'fm='+str(r['first_mention'])) for r in top_named]) json.dump({"register_rows": rows, "alice_mixture": alice_mix}, open(os.path.join(STATS, "register.json"), "w"), indent=1) print("\nwritten", os.path.join(STATS, "register.json"))