Download alice_vs_megan/code/make_persite_table.py from Ibisbill/m0de-collapse-out: direct link, hf CLI and curl.
- Browser
- Download file 4.73 kB
-
https://huggingface.co/datasets/Ibisbill/m0de-collapse-out/resolve/main/alice_vs_megan/code/make_persite_table.py
- Command line
-
hf download hf://datasets/Ibisbill/m0de-collapse-out/alice_vs_megan/code/make_persite_table.py
-
curl -L -o make_persite_table.py https://huggingface.co/datasets/Ibisbill/m0de-collapse-out/resolve/main/alice_vs_megan/code/make_persite_table.py
4.73 kB
| """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") | |