Download scripts/phase5_copy_free.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_copy_free.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase5_copy_free.py
-
curl -L -o phase5_copy_free.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_copy_free.py
10.4 kB
| """Phase 5: the comparison between spellings with copying taken out. | |
| On greedy continuations the frozen model reuses much of its prompt, far more | |
| in romanized Hindi than in Devanagari (phase5_copy_branch.py), and the draft | |
| heads cannot follow copied words. Differences between spellings measured on | |
| continuations therefore mix two things: how well the heads draft a spelling, | |
| and how much the frozen model copies in it. This script separates them in | |
| three ways, for one condition and several seeds: | |
| real text held-out text under teacher forcing, so the prefix is never | |
| model-generated: does the first draft equal the frozen | |
| model's choice, by word-group position of the text token; | |
| also for text words that did not occur earlier in the | |
| document, and for positions where the frozen model's choice | |
| is the text token | |
| new words on the greedy continuations: the same three positions, for | |
| words that did not occur earlier in the context, and for | |
| words that did | |
| by reuse per document, tokens per pass of the chain and of the | |
| confidence tree together with the share of its continuation | |
| that sits in a 4-gram of the prompt, so the tables can be | |
| restricted to documents with little prompt reuse | |
| Counts are saved per document so that an aggregation step can bootstrap over | |
| documents and pool seeds. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID") | |
| REPO = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(REPO)) | |
| sys.path.insert(0, str(REPO / "scripts")) | |
| import numpy as np | |
| import torch | |
| from phase5_copy_branch import ngram_share | |
| from phase5_deep_tree import accepted_depth, beam_tree, chain_drafts, head_features | |
| from phase5_tree_draft import DEVICE, replay | |
| DEPTH = 3 | |
| CHUNK = 256 | |
| CLASS_NAMES = ("inside_word", "function_word_start", "group_start") | |
| REAL_SPLITS = ("all", "new_word", "word_seen_before", "frozen_choice_is_text", "new_word_and_frozen_choice_is_text") | |
| CONT_SPLITS = ("all", "new_word", "word_seen_before") | |
| def word_info(seq: list, is_start: np.ndarray, tokenizer, strip: str) -> np.ndarray: | |
| """Per token: did the whitespace word it belongs to occur earlier in seq?""" | |
| starts = [i for i, t in enumerate(seq) if is_start[t]] | |
| if not starts or starts[0] != 0: | |
| starts = [0] + starts | |
| words = [w.strip().strip(strip) for w in tokenizer.batch_decode([seq[a:b] for a, b in zip(starts, starts[1:] + [len(seq)])])] | |
| word_of = np.searchsorted(np.array(starts), np.arange(len(seq)), side="right") - 1 | |
| seen, earlier = np.zeros(len(words), dtype=bool), set() | |
| for w, word in enumerate(words): | |
| seen[w] = bool(word) and word in earlier | |
| earlier.add(word) | |
| return seen[word_of] | |
| def count(table: np.ndarray, doc: int, cls: np.ndarray, masks: list, hit: np.ndarray) -> None: | |
| """table[doc, class, split] += (hits, positions).""" | |
| for c in range(3): | |
| for s, m in enumerate(masks): | |
| sel = (cls == c) & m | |
| table[doc, c, s] += [hit[sel].sum(), sel.sum()] | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--name", required=True) | |
| p.add_argument("--ckpt-root", required=True, help="directory holding {name}_seed{s}/{arm}.pt") | |
| p.add_argument("--arm", default="dependent_teacher") | |
| p.add_argument("--seeds", default="0,1,2") | |
| p.add_argument("--heldout", required=True) | |
| p.add_argument("--scheme", default="") | |
| p.add_argument("--docs", type=int, default=512) | |
| p.add_argument("--real-tokens", type=int, default=512) | |
| p.add_argument("--out", required=True) | |
| args = p.parse_args() | |
| t0 = time.perf_counter() | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| import phase4_boundary_decoding as pb | |
| import phase5_word_groups as wg | |
| from phase5_dependent_eval import BACKBONE, load_arm | |
| from src.train.data import load_heldout_texts | |
| tok = AutoTokenizer.from_pretrained(BACKBONE) | |
| backbone = AutoModelForCausalLM.from_pretrained(BACKBONE, dtype=torch.float32).to(DEVICE).eval() | |
| vocab = backbone.config.vocab_size | |
| is_start, _, _ = wg.prefix_tables(tok, vocab) | |
| fwords = wg.function_words(args.scheme) if args.scheme else set() | |
| unembed = backbone.lm_head.weight | |
| texts = load_heldout_texts(args.heldout)[: args.docs] | |
| # real text: frozen hidden states and choices once, heads per seed | |
| real = [] | |
| frozen_is_text = np.zeros((3, 2)) | |
| for text in texts: | |
| ids = tok(text, add_special_tokens=False, truncation=True, max_length=args.real_tokens).input_ids | |
| if len(ids) < 8: | |
| continue | |
| hidden = backbone.model(input_ids=torch.tensor([ids], device=DEVICE)).last_hidden_state[0] | |
| choice = backbone.lm_head(hidden).argmax(-1) # choice[t] = frozen model's token after ids[t] | |
| cls = wg.token_classes(ids, is_start, tok, fwords)[2:] | |
| seen = word_info(ids, is_start, tok, wg.STRIP)[2:] | |
| ids_t = torch.tensor(ids, device=DEVICE) | |
| agree = (choice[1:-1] == ids_t[2:]).cpu().numpy() | |
| for c in range(3): | |
| frozen_is_text[c] += [agree[cls == c].sum(), (cls == c).sum()] | |
| real.append({"ids": ids_t, "hidden": hidden.cpu(), "choice": choice[1:-1], "cls": cls, "seen": seen, "agree": agree}) | |
| print(f"{args.name}: {len(real)} real-text documents, {time.perf_counter() - t0:.0f}s", flush=True) | |
| eos = backbone.generation_config.eos_token_id | |
| eos_ids = set(eos if isinstance(eos, list) else [eos]) | |
| pairs = pb.generate_continuations(backbone, tok, texts, 256, 64 + pb.LOOKAHEAD, 16, eos_ids) | |
| pairs = [(pr, c) for pr, c in pairs if min(64, len(c) - pb.LOOKAHEAD + 1) >= 1] | |
| cont = [] | |
| for prompt, c in pairs: | |
| horizon = min(64, len(c) - pb.LOOKAHEAD + 1) | |
| seq = prompt + c | |
| p0 = len(prompt) - 1 | |
| idx = np.arange(p0 + 2, p0 + 2 + horizon) | |
| cont.append({"seq": seq, "p0": p0, "horizon": horizon, "cls": wg.token_classes(seq, is_start, tok, fwords)[idx], | |
| "seen": word_info(seq, is_start, tok, wg.STRIP)[idx], "from_prompt": ngram_share(c[:64], prompt), "self_loop": ngram_share(c[:64], None)}) | |
| reuse = np.array([d["from_prompt"] for d in cont]) | |
| print(f"{args.name}: {len(cont)} continuation documents, prompt reuse mean {reuse.mean():.3f} median {np.median(reuse):.3f}, {time.perf_counter() - t0:.0f}s", flush=True) | |
| res = {"name": args.name, "arm": args.arm, "gpu": torch.cuda.get_device_name(DEVICE), "classes": CLASS_NAMES, | |
| "real_text_documents": len(real), "real_text_splits": REAL_SPLITS, "continuation_documents": len(cont), "continuation_splits": CONT_SPLITS, | |
| "real_text_frozen_choice_is_text_by_class": (frozen_is_text[:, 0] / np.maximum(1, frozen_is_text[:, 1])).tolist(), | |
| "prompt_reuse_by_document": reuse.tolist(), "self_looping_by_document": [d["self_loop"] for d in cont], "seeds": {}} | |
| for seed in args.seeds.split(","): | |
| stack = load_arm(backbone, Path(args.ckpt_root) / f"{args.name}_seed{seed}" / f"{args.arm}.pt", True) | |
| rt = np.zeros((len(real), 3, len(REAL_SPLITS), 2)) | |
| for d, doc in enumerate(real): | |
| ids, n = doc["ids"], len(doc["ids"]) | |
| trunk = stack.trunk_states(doc["hidden"][: n - 2].to(DEVICE)) # position t drafts ids[t + 2] given ids[t + 1] | |
| since = torch.zeros(n - 2, dtype=torch.long, device=DEVICE) | |
| feat = head_features(stack, trunk, 1, [ids[1 : n - 1]], since) | |
| draft = torch.cat([(feat[s : s + CHUNK] @ unembed.T).argmax(-1) for s in range(0, n - 2, CHUNK)]) | |
| hit = (draft == doc["choice"]).cpu().numpy() | |
| new = ~doc["seen"] | |
| count(rt, d, doc["cls"], [np.ones_like(new), new, doc["seen"], doc["agree"], new & doc["agree"]], hit) | |
| ct = np.zeros((len(cont), 3, len(CONT_SPLITS), 2)) | |
| per_doc = {"chain": [], "tree_8": [], "tree_16": []} | |
| for d, doc in enumerate(cont): | |
| seq, p0, horizon = doc["seq"], doc["p0"], doc["horizon"] | |
| trunk = stack.trunk_states(backbone.model(input_ids=torch.tensor([seq], device=DEVICE)).last_hidden_state[0, p0 : p0 + horizon]) | |
| exact_next = torch.tensor(seq[p0 + 1 : p0 + 1 + horizon], device=DEVICE) | |
| truth = torch.tensor([seq[p0 + 2 + j : p0 + 2 + j + DEPTH] for j in range(horizon)], device=DEVICE) | |
| since = torch.zeros(horizon, dtype=torch.long, device=DEVICE) | |
| match = (chain_drafts(stack, unembed, trunk, exact_next, DEPTH, since) == truth).cpu().numpy() | |
| count(ct, d, doc["cls"], [np.ones(horizon, dtype=bool), ~doc["seen"], doc["seen"]], match[:, 0]) | |
| per_doc["chain"].append(replay(np.cumprod(match, 1).sum(1))) | |
| levels = beam_tree(stack, unembed, trunk, exact_next, truth, DEPTH, 24, since) | |
| per_doc["tree_8"].append(replay(accepted_depth(levels, 8))) | |
| per_doc["tree_16"].append(replay(accepted_depth(levels, 16))) | |
| res["seeds"][seed] = {"real_text_counts": rt.tolist(), "continuation_counts": ct.tolist(), "per_document": {k: np.array(v).tolist() for k, v in per_doc.items()}} | |
| r, c = rt.sum(0), ct.sum(0) | |
| print(f"{args.name} seed {seed}, {time.perf_counter() - t0:.0f}s", flush=True) | |
| for k in range(3): | |
| if r[k, 0, 1]: | |
| print(f" {CLASS_NAMES[k]:20s} real text: " + " ".join(f"{REAL_SPLITS[s]} {r[k, s, 0] / max(1, r[k, s, 1]):.3f} (n={int(r[k, s, 1])})" for s in range(len(REAL_SPLITS))) | |
| + " | continuations: " + " ".join(f"{CONT_SPLITS[s]} {c[k, s, 0] / max(1, c[k, s, 1]):.3f} (n={int(c[k, s, 1])})" for s in range(len(CONT_SPLITS))), flush=True) | |
| del stack | |
| res["wall_seconds"] = time.perf_counter() - t0 | |
| res["peak_gpu_mib"] = torch.cuda.max_memory_allocated(DEVICE) / 2**20 | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| Path(args.out).write_text(json.dumps(res)) | |
| print(f"{args.name}: frozen model's choice is the text token by class {res['real_text_frozen_choice_is_text_by_class']}, {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True) | |
| if __name__ == "__main__": | |
| main() | |