File size: 4,730 Bytes
ead9072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Unified per-site table for the 8 focus names (+ bare_Alice control).

Columns: name, variant, pos, update, doc_idx, block_first_mention(same-id),
standalone, prev_cat, next_piece, ctx_multiplicity, story_reg, dialog,
she_in_prefix, girl_in_prefix. Written as parquet if pyarrow available, else csv.gz.
"""
import json, os, sys
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")
K = 16; BLOCK = 1024; W = 131072; NL = 198; EOS = 100257

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(BASE, "sites/sites_all.npz"))
ctxs = np.load(os.path.join(BASE, "sites/contexts_all.npz"))
flags = np.load(os.path.join(BASE, "sites/block_register_flags.npz"))
eos = np.load(os.path.join(BASE, "sites/eos_positions.npy"))
h0 = json.load(open(os.path.join(BASE, "sites/h0_counts.json")))

dec_cache = {}
def dec(i):
    i = int(i)
    if i not in dec_cache:
        dec_cache[i] = tok.decode([i])
    return dec_cache[i]

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"

def is_standalone(nid):
    s = dec(nid); t = s.strip()
    if not s: return True
    if s[0].isalnum(): return False            # glued piece
    cap = bool(t) and s[0] == " " and t[0].isupper() and t.replace("-", "").replace(".", "").isalpha()
    return not cap

recs = []
FOCUS = ["Alice", "Mary", "Sarah", "Maria", "Julia", "Megan", "Karen", "Ann"]
for nm in FOCUS + ["bare_Alice"]:
    lab = nm if nm.startswith("bare") else f"sp_{nm}"
    p = sites[f"pos_{lab}"]; C = ctxs[f"ctx_{lab}"]
    if not len(p): continue
    seqlen = len(h0["patterns"][lab]["ids"])
    cs = ((p - 1) // BLOCK) * BLOCK
    prev_same = np.concatenate(([np.int64(-1)], p[:-1]))
    fm = prev_same < cs
    rows = [tuple(r) for r in C.tolist()]
    mult = Counter(rows)
    doc_idx = np.searchsorted(eos, p)
    has_flags = (not nm.startswith("bare")) and (f"{nm}_story_reg" in flags.files)
    for i in range(len(p)):
        recs.append({
            "name": nm.replace("bare_", ""), "variant": "bare" if nm.startswith("bare") else "sp",
            "pos": int(p[i]), "update": int(p[i] // W), "doc_idx": int(doc_idx[i]),
            "first_mention_block": bool(fm[i]),
            "standalone": is_standalone(C[i, K + seqlen]),
            "prev_cat": prev_cat(int(C[i, K - 1])),
            "next_piece": dec(C[i, K + seqlen])[:20],
            "ctx_multiplicity": int(mult[rows[i]]),
            "story_reg": bool(flags[f"{nm}_story_reg"][i]) if has_flags else None,
            "dialog_prefix": bool(flags[f"{nm}_dialog"][i]) if has_flags else None,
            "she_in_prefix": bool(flags[f"{nm}_she"][i]) if has_flags else None,
            "girl_in_prefix": bool(flags[f"{nm}_girl"][i]) if has_flags else None,
        })

out_base = os.path.join(BASE, "per_site_table")
try:
    import pandas as pd
    df = pd.DataFrame(recs)
    try:
        df.to_parquet(out_base + ".parquet", index=False)
        print("wrote", out_base + ".parquet", len(df), "rows")
    except Exception as e:
        df.to_csv(out_base + ".csv.gz", index=False, compression="gzip")
        print("parquet failed (", e, ") -> wrote csv.gz", len(df))
except ImportError:
    import csv, gzip
    with gzip.open(out_base + ".csv.gz", "wt", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(recs[0]))
        w.writeheader(); w.writerows(recs)
    print("wrote", out_base + ".csv.gz", len(recs), "rows")