Download scripts/phase5_calibrated_copy_tree.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 31.7 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_calibrated_copy_tree.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase5_calibrated_copy_tree.py
-
curl -L -o phase5_calibrated_copy_tree.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase5_calibrated_copy_tree.py
31.7 kB
| """Phase 5: one calibrated budget for head nodes and copied nodes; do linguistic features help there? | |
| The strongest drafter so far verifies, in one backbone pass, a confidence tree | |
| drafted by five look-ahead heads plus a branch copied from the context | |
| (phase5_depth_copy.py). That rule splits the budget by hand: 5 copied tokens | |
| and N - 5 tree nodes when a suffix of at least two tokens matched, else N tree | |
| nodes. Here a calibrator decides instead. Candidates at each position are | |
| head nodes the beam tree of phase5_deep_tree.py (depth 5, 4 candidates per | |
| node, beam 24) | |
| copy nodes the chain of up to 5 tokens that followed the most recent | |
| earlier occurrence of the longest matching suffix (3, else 2, | |
| else 1 tokens), attached at the root whenever anything matched | |
| and a small model per source and depth predicts whether a node is accepted | |
| given that its parent was. The path score is the sum of the log predictions | |
| along the path, so it never rises along a path, and the N nodes with the | |
| highest path score are verified, head and copy nodes against one budget (ties | |
| go to the shallower node). A position's accepted depth is the longer of the | |
| accepted head path and the accepted copied prefix. Three feature sets: | |
| conf confidence and source features. Head nodes: the confidence features | |
| of phase5_calibrated_tree.py plus the matched suffix length at this | |
| position and whether the node (and its whole path) equals the copied | |
| branch. Copy nodes: the head's log-probability of the copied token | |
| given the copied tokens before it, the head's top log-probability and | |
| the gap, whether the copied token is the head's first or among its | |
| four choices, the matched suffix length, distance back to the matched | |
| place, whether that place is in the prompt, length of the copied chain | |
| ling conf plus the linguistic features of phase5_calibrated_tree.py | |
| (word-group class of the candidate and of the prefix, word start, | |
| tokens since the word start, script and script switch, token length) | |
| shuf conf plus the linguistic features permuted across nodes (control) | |
| Each is fitted as a logistic regression and as a small MLP; the family with | |
| the lower validation log-loss is reported under the set's name. Baselines on | |
| the same documents: the uncalibrated five-head confidence tree at N, and the | |
| fixed rule above. Calibration documents are the even-indexed documents of the | |
| first --spec-docs held-out documents plus the next --extra-fit-docs; every | |
| fifth one is held back for validation. Tokens per pass is reported on the | |
| odd-indexed documents of the first --spec-docs, the documents of | |
| phase5_depth_copy.py. | |
| With --pool it reads several outputs of this script and tests the same | |
| contrasts with the documents of all of them pooled. | |
| """ | |
| 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_calibrated_tree import CONF_NAMES, LING_NAMES, calibration_metrics, fit_model, onehot, prefix_states, vocab_tables | |
| from phase5_copy_branch import MATCH_LENGTHS, copied_branch | |
| from phase5_deep_tree import accepted_depth, head_features | |
| from phase5_tree_draft import DEVICE, K, bootstrap_gain, replay, top_candidates | |
| DEPTH = 5 | |
| BEAM = 24 | |
| COPY = 5 | |
| LOOKAHEAD = 7 | |
| BUDGETS = (8, 16, 24) | |
| SETS = ("conf", "shuf", "ling") | |
| FAMILIES = ("lr", "mlp") | |
| SOURCES = ("head", "copy") | |
| HEAD_SOURCE_NAMES = [f"matched_suffix_{i}" for i in range(4)] + ["token_equals_copied_token", "path_equals_copied_branch"] | |
| COPY_CONF_NAMES = (["head_lp_of_copied_token", "head_lp_squared", "head_p_of_copied_token", "head_top_lp", "head_top_lp_minus_copied_lp", | |
| "copied_token_is_head_top", "copied_token_in_head_top_4", "ancestors_head_lp"] | |
| + [f"matched_suffix_{i}" for i in (1, 2, 3)] + ["log_distance_to_match", "match_in_prompt", "copied_chain_length"]) | |
| N_CONF = {"head": len(CONF_NAMES) + len(HEAD_SOURCE_NAMES), "copy": len(COPY_CONF_NAMES)} | |
| N_LING = len(LING_NAMES) | |
| TESTS = (("conf", "fixed_rule"), ("ling", "conf"), ("shuf", "conf"), ("ling", "shuf"), ("conf", "tree"), ("ling", "fixed_rule")) | |
| def conf_block(lp: np.ndarray, st: dict) -> np.ndarray: | |
| """Confidence features of phase5_calibrated_tree.node_features for children lp (..., K) of parents with state st (...).""" | |
| shape = lp.shape | |
| b = {k: np.broadcast_to(st[k][..., None], shape) for k in ("anc_lp", "parent_rank", "grand_rank")} | |
| rank = np.broadcast_to(np.arange(shape[-1]), shape) | |
| top_lp = np.broadcast_to(lp[..., :1], shape) | |
| margin = np.broadcast_to(lp[..., :1] - lp[..., 1:2], shape) | |
| p = np.exp(lp) | |
| pn = p / p.sum(-1, keepdims=True) | |
| spread = np.broadcast_to(-(pn * np.log(pn + 1e-9)).sum(-1, keepdims=True), shape) | |
| return np.concatenate([np.stack([lp, lp * lp, p, top_lp, margin, spread, b["anc_lp"]], -1), | |
| onehot(rank, K), onehot(b["parent_rank"], K), onehot(b["grand_rank"], K)], -1).astype(np.float32) | |
| def ling_block(tok: np.ndarray, lp: np.ndarray, st: dict, tables: tuple) -> tuple: | |
| """Linguistic features of phase5_calibrated_tree.node_features, and the prefix state after each child.""" | |
| is_start, gclass, script, length = tables | |
| shape = tok.shape | |
| b = {k: np.broadcast_to(st[k][..., None], shape) for k in ("word_cls", "prev_cls", "tiw", "last_script")} | |
| own_start, own_cls, own_script, ln = is_start[tok], gclass[tok], script[tok], length[tok] | |
| switch = ((own_script > 0) & (b["last_script"] > 0) & (own_script != b["last_script"])).astype(np.float32) | |
| cls1h, word1h = onehot(own_cls, 3), onehot(b["word_cls"], 3) | |
| x = np.concatenate([ | |
| np.stack([own_start.astype(np.float32), np.broadcast_to(own_start[..., :1], shape).astype(np.float32), | |
| switch, np.minimum(ln, 8) / 8.0, lp * switch], -1), | |
| cls1h, np.broadcast_to(cls1h[..., :1, :], shape + (3,)), word1h, onehot(b["prev_cls"], 3), | |
| onehot(b["tiw"], 4), onehot(own_script, 3), onehot(b["last_script"], 3), onehot(ln, 5), | |
| lp[..., None] * cls1h, lp[..., None] * word1h], -1).astype(np.float32) | |
| new = {"word_cls": np.where(own_start, own_cls, b["word_cls"]), "prev_cls": np.where(own_start, b["word_cls"], b["prev_cls"]), | |
| "tiw": np.where(own_start, 0, b["tiw"] + 1), "last_script": np.where(own_script > 0, own_script, b["last_script"])} | |
| return x, new | |
| def match_source(seq: list, end: int) -> int: | |
| """Index of the last token of the most recent earlier occurrence found by copied_branch, or -1.""" | |
| for m in MATCH_LENGTHS: | |
| if end - m + 1 < 0: | |
| continue | |
| key = seq[end - m + 1 : end + 1] | |
| for q in range(end - 1, m - 2, -1): | |
| if seq[q - m + 1 : q + 1] == key: | |
| return q | |
| return -1 | |
| def expand_heads(stack, unembed: torch.Tensor, trunk: torch.Tensor, exact_next: torch.Tensor, truth: torch.Tensor, state0: dict, | |
| copy_tok: np.ndarray, copy_len: np.ndarray, match: np.ndarray, tables: tuple) -> list: | |
| """The beam tree of phase5_deep_tree.beam_tree with, per level, features, labels and each node's parent.""" | |
| h = trunk.shape[0] | |
| since = torch.zeros(h, dtype=torch.long, device=trunk.device) | |
| hist = [exact_next[:, None]] | |
| score = torch.zeros(h, 1, device=trunk.device) | |
| on_true = torch.ones(h, 1, dtype=torch.bool, device=trunk.device) | |
| st = {k: v[:, None].copy() for k, v in state0.items()} | |
| st.update(anc_lp=np.zeros((h, 1), dtype=np.float32), parent_rank=np.full((h, 1), -1), grand_rank=np.full((h, 1), -1)) | |
| path_eq = np.ones((h, 1), dtype=bool) | |
| parent_of_slot = np.zeros((h, 1), dtype=np.int64) # index, in the previous level's node array, of each parent slot | |
| source = onehot(match, 4) # (h, 4) | |
| levels = [] | |
| for d in range(1, DEPTH + 1): | |
| p = score.shape[1] | |
| feat = head_features(stack, trunk.repeat_interleave(p, 0), d, [x.reshape(-1) for x in hist], since.repeat_interleave(p)) | |
| tok, lp = top_candidates(feat, unembed) | |
| tok, lp = tok.view(h, p, K), lp.view(h, p, K) | |
| child_score = (score[:, :, None] + lp).reshape(h, p * K) | |
| child_true = (on_true[:, :, None] & (tok == truth[:, d - 1, None, None])).reshape(h, p * K) | |
| tok_n, lp_n = tok.cpu().numpy(), lp.cpu().numpy().astype(np.float32) | |
| ling, new = ling_block(tok_n, lp_n, st, tables) | |
| tok_eq = (copy_len >= d)[:, None, None] & (tok_n == copy_tok[:, d - 1][:, None, None]) | |
| peq = tok_eq & path_eq[:, :, None] | |
| conf = np.concatenate([conf_block(lp_n, st), np.broadcast_to(source[:, None, None, :], (h, p, K, 4)), | |
| tok_eq[..., None].astype(np.float32), peq[..., None].astype(np.float32)], -1) | |
| levels.append({"score": child_score, "true_t": child_true, "true": child_true.cpu().numpy(), | |
| "parent_true": np.repeat(on_true.cpu().numpy(), K, 1), "parent": np.repeat(parent_of_slot, K, 1), | |
| "x": np.concatenate([conf, ling], -1).reshape(h, p * K, -1).astype(np.float32)}) | |
| if d == DEPTH: | |
| break | |
| new.update(anc_lp=st["anc_lp"][..., None] + lp_n, grand_rank=np.broadcast_to(st["parent_rank"][..., None], (h, p, K)), | |
| parent_rank=np.broadcast_to(np.arange(K), (h, p, K))) | |
| st = {k: np.ascontiguousarray(np.broadcast_to(v, (h, p, K))).reshape(h, p * K) for k, v in new.items()} | |
| path_eq = peq.reshape(h, p * K) | |
| hist = [x.repeat_interleave(K, 1) for x in hist] + [tok.reshape(h, p * K)] | |
| score, on_true = child_score, child_true | |
| parent_of_slot = np.broadcast_to(np.arange(p * K), (h, p * K)).copy() | |
| if p * K > BEAM: | |
| keep = child_score.topk(BEAM, 1).indices | |
| score, on_true = child_score.gather(1, keep), child_true.gather(1, keep) | |
| hist = [x.gather(1, keep) for x in hist] | |
| kn = keep.cpu().numpy() | |
| st = {k: np.take_along_axis(v, kn, 1) for k, v in st.items()} | |
| path_eq = np.take_along_axis(path_eq, kn, 1) | |
| parent_of_slot = kn | |
| return levels | |
| def copy_nodes(stack, unembed: torch.Tensor, trunk: torch.Tensor, exact_next: torch.Tensor, state0: dict, copy_tok: np.ndarray, | |
| copy_len: np.ndarray, match: np.ndarray, distance: np.ndarray, in_prompt: np.ndarray, tables: tuple) -> np.ndarray: | |
| """(H, COPY, features) of the copied chain; rows past the chain's length are meaningless.""" | |
| h = trunk.shape[0] | |
| since = torch.zeros(h, dtype=torch.long, device=trunk.device) | |
| hist = [exact_next] | |
| anc = np.zeros(h, dtype=np.float32) | |
| st = {k: v.copy() for k, v in state0.items()} | |
| fixed = np.concatenate([onehot(match - 1, 3), np.stack([np.log1p(distance) / 6.0, in_prompt.astype(np.float32), copy_len / float(COPY)], -1)], -1) | |
| out = [] | |
| for d in range(1, COPY + 1): | |
| logp = torch.log_softmax(head_features(stack, trunk, d, hist, since) @ unembed.T, -1) | |
| c = torch.tensor(copy_tok[:, d - 1], device=trunk.device) | |
| top_lp, top_tok = logp.topk(K, -1) | |
| lp = logp.gather(1, c[:, None])[:, 0].cpu().numpy().astype(np.float32) | |
| top = top_lp[:, 0].cpu().numpy().astype(np.float32) | |
| conf = np.concatenate([np.stack([lp, lp * lp, np.exp(lp), top, top - lp, (top_tok[:, 0] == c).cpu().numpy().astype(np.float32), | |
| (top_tok == c[:, None]).any(1).cpu().numpy().astype(np.float32), anc], -1), fixed], -1) | |
| ling, new = ling_block(copy_tok[:, d - 1][:, None], lp[:, None], st, tables) | |
| out.append(np.concatenate([conf, ling[:, 0]], -1).astype(np.float32)) | |
| st = {k: v[:, 0] for k, v in new.items()} | |
| anc = anc + lp | |
| hist.append(c) | |
| return np.stack(out, 1) | |
| def allocate(head_scores: list, head_true: list, copy_score: np.ndarray, copy_true: np.ndarray, budget: int) -> tuple: | |
| """Accepted depth per position when the `budget` best nodes of both sources are verified; and copy nodes verified.""" | |
| cols, kinds = [], [] | |
| for d in range(DEPTH): | |
| cols += [head_scores[d], copy_score[:, d : d + 1]] | |
| kinds += [("head", d, head_scores[d].shape[1]), ("copy", d, 1)] | |
| scores = np.concatenate(cols, 1) | |
| order = np.argsort(-scores, axis=1, kind="stable") # ties keep the shallower node first | |
| place = np.empty_like(order) | |
| np.put_along_axis(place, order, np.broadcast_to(np.arange(scores.shape[1]), scores.shape), 1) | |
| chosen = (place < budget) & np.isfinite(scores) | |
| h = scores.shape[0] | |
| ok_h, ok_c = np.ones(h, dtype=bool), np.ones(h, dtype=bool) | |
| d_h, d_c, n_copy = np.zeros(h, dtype=np.int64), np.zeros(h, dtype=np.int64), np.zeros(h, dtype=np.int64) | |
| off = 0 | |
| for kind, d, n in kinds: | |
| sel = chosen[:, off : off + n] | |
| if kind == "head": | |
| ok_h = ok_h & (head_true[d] & sel).any(1) | |
| d_h += ok_h | |
| else: | |
| ok_c = ok_c & copy_true[:, d] & sel[:, 0] | |
| d_c += ok_c | |
| n_copy += sel[:, 0] | |
| off += n | |
| return np.maximum(d_h, d_c), n_copy | |
| def tpp(rows) -> float: | |
| a = np.array(rows, dtype=float) | |
| return float(a[:, 0].sum() / a[:, 1].sum()) | |
| def pool(paths: list, out: str) -> None: | |
| runs = [json.loads(Path(p).read_text()) for p in paths] | |
| res = {"pooled": [str(p) for p in paths], "name": runs[0]["name"], "seeds": [r["seed"] for r in runs], "tokens_per_pass_mean_of_seeds": {}, "tests_percent_gain": {}} | |
| names = list(runs[0]["per_document"]) | |
| for pol in names: | |
| res["tokens_per_pass_mean_of_seeds"][pol] = {str(n): float(np.mean([r["tokens_per_pass"][pol][str(n)] for r in runs])) for n in BUDGETS} | |
| for n in BUDGETS: | |
| arr = {pol: np.concatenate([np.array(r["per_document"][pol][str(n)], dtype=float) for r in runs]) for pol in names} | |
| t = {} | |
| for suffix in ("", "_lr", "_mlp"): | |
| for a, b in TESTS: | |
| a_, b_ = (a + suffix if a in SETS else a), (b + suffix if b in SETS else b) | |
| t[f"{a_}_vs_{b_}"] = bootstrap_gain(arr[a_], arr[b_]) | |
| res["tests_percent_gain"][str(n)] = t | |
| Path(out).write_text(json.dumps(res, indent=1)) | |
| print(f"{res['name']} pooled over seeds {res['seeds']}") | |
| for pol in ("tree", "fixed_rule", "conf", "ling", "shuf", "conf_lr", "ling_lr", "shuf_lr", "conf_mlp", "ling_mlp", "shuf_mlp"): | |
| print(f" {pol:12s} " + " ".join(f"N={n}: {res['tokens_per_pass_mean_of_seeds'][pol][str(n)]:.3f}" for n in BUDGETS)) | |
| for n in BUDGETS: | |
| for k, v in res["tests_percent_gain"][str(n)].items(): | |
| print(f" N={n:2d} {k:26s} {v[0]:+.2f}% [{v[1]:+.2f}, {v[2]:+.2f}]") | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--pool", nargs="+", help="outputs of this script to pool; needs only --out") | |
| p.add_argument("--name") | |
| p.add_argument("--ckpt-root", help="directory holding {name}_seed{s}/{arm}.pt with five look-ahead heads") | |
| p.add_argument("--arm", default="dependent_teacher") | |
| p.add_argument("--seeds", default="0") | |
| p.add_argument("--heldout") | |
| p.add_argument("--scheme", default="", help="Devanagari, ITRANS, IAST or ISO for the Hindi function-word list; empty for English") | |
| p.add_argument("--train-ids", default="", help="training token ids, needed with --scheme") | |
| p.add_argument("--spec-docs", type=int, default=256) | |
| p.add_argument("--extra-fit-docs", type=int, default=256) | |
| p.add_argument("--fit-seed", type=int, default=0) | |
| p.add_argument("--out", required=True, help="output file; with several seeds, {seed} in it is replaced") | |
| args = p.parse_args() | |
| if args.pool: | |
| pool(args.pool, args.out) | |
| return | |
| 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 | |
| starts = pb.word_start_table(tok) | |
| is_start = np.array(starts + [False] * (vocab - len(starts))) | |
| script, length = vocab_tables(tok, vocab) | |
| unembed = backbone.lm_head.weight | |
| fwords = set() | |
| gclass = np.where(is_start, wg.GROUP_START, wg.WITHIN_WORD).astype(np.int64) | |
| if args.scheme: | |
| fwords = wg.function_words(args.scheme) | |
| gclass, _ = wg.token_group_table(np.load(args.train_ids, mmap_mode="r"), is_start, tok, fwords) | |
| tables = (is_start, gclass, script, length) | |
| eos = backbone.generation_config.eos_token_id | |
| eos_ids = set(eos if isinstance(eos, list) else [eos]) | |
| texts = load_heldout_texts(args.heldout) | |
| def continuations(chunk: list) -> list: | |
| pairs = pb.generate_continuations(backbone, tok, chunk, 256, 64 + LOOKAHEAD, 16, eos_ids) | |
| return [(pr, c) for pr, c in pairs if min(64, len(c) - LOOKAHEAD + 1) >= 1] | |
| first = continuations(texts[: args.spec_docs]) | |
| extra = continuations(texts[args.spec_docs : args.spec_docs + args.extra_fit_docs]) if args.extra_fit_docs else [] | |
| role = ["test" if i % 2 else "calib" for i in range(len(first))] + ["calib"] * len(extra) | |
| calib_index = 0 | |
| for i, r in enumerate(role): # every fifth calibration document is held back for validation | |
| if r == "calib": | |
| role[i] = "val" if calib_index % 5 == 4 else "train" | |
| calib_index += 1 | |
| # everything that does not depend on the heads | |
| static = [] | |
| for prompt, cont in first + extra: | |
| horizon = min(64, len(cont) - LOOKAHEAD + 1) | |
| seq = prompt + cont | |
| p0 = len(prompt) - 1 | |
| truth = np.array([seq[p0 + 2 + j : p0 + 2 + j + DEPTH] for j in range(horizon)]) | |
| branches = [copied_branch(seq, p0 + 1 + j, COPY) for j in range(horizon)] | |
| copy_tok = np.zeros((horizon, COPY), dtype=np.int64) | |
| for j, (br, _) in enumerate(branches): | |
| copy_tok[j, : len(br)] = br | |
| copy_len = np.array([len(br) for br, _ in branches]) | |
| match = np.array([m for _, m in branches]) | |
| exists = np.arange(COPY)[None] < copy_len[:, None] | |
| copy_true = (np.cumprod(copy_tok == truth, 1) > 0) & exists | |
| src = np.array([match_source(seq, p0 + 1 + j) for j in range(horizon)]) | |
| states = prefix_states(seq, is_start, gclass, script, wg.token_classes(seq, is_start, tok, fwords)) | |
| static.append({"seq": seq, "p0": p0, "horizon": horizon, "truth": truth, "copy_tok": copy_tok, "copy_len": copy_len, "match": match, | |
| "exists": exists, "copy_true": copy_true, "distance": np.where(src >= 0, p0 + 1 + np.arange(horizon) - src, 0).astype(np.float32), | |
| "in_prompt": (src >= 0) & (src < len(prompt)), | |
| "state0": {k: v[len(prompt) : len(prompt) + horizon] for k, v in states.items()}}) # after the exact next token | |
| n_test, n_train, n_val = (role.count(r) for r in ("test", "train", "val")) | |
| print(f"{args.name}: {n_test} test, {n_train} calibration, {n_val} validation documents; features head {N_CONF['head']}+{N_LING}, " | |
| f"copy {N_CONF['copy']}+{N_LING}; {time.perf_counter() - t0:.0f}s", flush=True) | |
| for seed in args.seeds.split(","): | |
| t1 = time.perf_counter() | |
| torch.cuda.reset_peak_memory_stats(DEVICE) | |
| stack = load_arm(backbone, Path(args.ckpt_root) / f"{args.name}_seed{seed}" / f"{args.arm}.pt", True, n_heads=DEPTH + 1) | |
| fit = {(r, s, d): ([], []) for r in ("train", "val", "test") for s in SOURCES for d in range(DEPTH)} | |
| test = [] | |
| for doc, r in zip(static, role): | |
| 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(doc["truth"], device=DEVICE) | |
| levels = expand_heads(stack, unembed, trunk, exact_next, truth, doc["state0"], doc["copy_tok"], doc["copy_len"], doc["match"], tables) | |
| cx = copy_nodes(stack, unembed, trunk, exact_next, doc["state0"], doc["copy_tok"], doc["copy_len"], doc["match"], doc["distance"], doc["in_prompt"], tables) | |
| for d in range(DEPTH): # rows a calibrator is fitted and scored on: nodes whose parent is accepted | |
| sel = levels[d]["parent_true"] | |
| fit[r, "head", d][0].append(levels[d]["x"][sel]) | |
| fit[r, "head", d][1].append(levels[d]["true"][sel]) | |
| sel = doc["exists"][:, d] & (doc["copy_true"][:, d - 1] if d else True) | |
| fit[r, "copy", d][0].append(cx[sel, d]) | |
| fit[r, "copy", d][1].append(doc["copy_true"][sel, d]) | |
| if r == "test": | |
| pairs = [(lv["score"], lv["true_t"]) for lv in levels] | |
| copy_depth = doc["copy_true"].sum(1) | |
| base = {} | |
| for n in BUDGETS: | |
| full = accepted_depth(pairs, n) | |
| base["tree", n] = full | |
| base["fixed_rule", n] = np.where(doc["match"] >= 2, np.maximum(accepted_depth(pairs, n - COPY), copy_depth), full) | |
| test.append({"x": [lv["x"] for lv in levels], "true": [lv["true"] for lv in levels], "parent": [lv["parent"] for lv in levels], | |
| "cx": cx, "exists": doc["exists"], "copy_true": doc["copy_true"], "base": base}) | |
| del stack | |
| rows = {k: (np.concatenate(v[0]), np.concatenate(v[1]).astype(np.float32)) for k, v in fit.items()} | |
| print(f"{args.name} seed {seed}: trees built, {time.perf_counter() - t1:.0f}s; baseline " | |
| + " ".join(f"{pol} N={n}: {tpp([replay(d['base'][pol, n]) for d in test]):.3f}" for pol in ("tree", "fixed_rule") for n in BUDGETS), flush=True) | |
| rng = np.random.default_rng(args.fit_seed) | |
| def view(x: np.ndarray, s: str, which: str, perm=None) -> np.ndarray: | |
| if which == "conf": | |
| return x[:, : N_CONF[s]] | |
| if which == "shuf": | |
| return np.concatenate([x[:, : N_CONF[s]], x[perm, N_CONF[s] :]], 1) | |
| return x | |
| models, val_loss, norm, coef, fit_rows = {}, {}, {}, {}, {} | |
| for s in SOURCES: | |
| for d in range(DEPTH): | |
| (xt, yt), (xv, yv) = rows["train", s, d], rows["val", s, d] | |
| fit_rows[f"{s}_{d + 1}"] = {"train": int(len(yt)), "validation": int(len(yv)), "accepted_share": float(yt.mean())} | |
| pt, pv = rng.permutation(len(xt)), rng.permutation(len(xv)) | |
| ytt, yvt = torch.tensor(yt, device=DEVICE), torch.tensor(yv, device=DEVICE) | |
| for which in SETS: | |
| a, b = view(xt, s, which, pt), view(xv, s, which, pv) | |
| mu, sd = a.mean(0), a.std(0) + 1e-6 | |
| norm[s, which, d] = (mu, sd) | |
| at, bt = torch.tensor((a - mu) / sd, device=DEVICE), torch.tensor((b - mu) / sd, device=DEVICE) | |
| for fam in FAMILIES: | |
| models[s, which, fam, d], val_loss[s, which, fam, d] = fit_model(fam, at, ytt, bt, yvt, args.fit_seed) | |
| if which == "ling": | |
| names = (CONF_NAMES + HEAD_SOURCE_NAMES if s == "head" else COPY_CONF_NAMES) + LING_NAMES | |
| coef[f"{s}_{d + 1}"] = {n: float(v) for n, v in zip(names, models[s, which, "lr", d].weight[0].cpu().numpy())} | |
| chosen = {which: min(FAMILIES, key=lambda fam: sum(val_loss[s, which, fam, d] for s in SOURCES for d in range(DEPTH))) for which in SETS} | |
| print(f"{args.name} seed {seed}: fitted, {time.perf_counter() - t1:.0f}s; chosen {chosen}; validation log-loss by depth: " | |
| + "; ".join(f"{s}_{w}_{f} " + "/".join(f"{val_loss[s, w, f, d]:.4f}" for d in range(DEPTH)) for s in SOURCES for w in SETS for f in FAMILIES), flush=True) | |
| def predict(s: str, which: str, fam: str, d: int, x: np.ndarray) -> torch.Tensor: | |
| mu, sd = norm[s, which, d] | |
| return models[s, which, fam, d](torch.tensor((x - mu) / sd, device=DEVICE)).squeeze(-1) | |
| test_calibration = {} | |
| for s in SOURCES: | |
| for d in range(DEPTH): | |
| xs, ys = rows["test", s, d] | |
| entry = {"rows": int(len(ys)), "accepted_share": float(ys.mean()), "base_rate": calibration_metrics(np.full(len(ys), ys.mean()), ys), | |
| "head_probability": calibration_metrics(xs[:, 2], ys)} | |
| for which in ("conf", "ling"): | |
| for fam in FAMILIES: | |
| entry[f"{which}_{fam}"] = calibration_metrics(torch.sigmoid(predict(s, which, fam, d, view(xs, s, which))).cpu().numpy(), ys) | |
| test_calibration[f"{s}_{d + 1}"] = entry | |
| # one permutation of the linguistic block over all test nodes of a source and depth, for the shuffled calibrator | |
| shuffled = {} | |
| for d in range(DEPTH): | |
| for s, key in (("head", "x"), ("copy", "cx")): | |
| block = np.concatenate([(doc[key][d] if s == "head" else doc[key][:, d]).reshape(-1, N_CONF[s] + N_LING)[:, N_CONF[s] :] for doc in test]) | |
| sizes = [doc[key][d].shape[0] * doc[key][d].shape[1] if s == "head" else doc[key].shape[0] for doc in test] | |
| real = np.arange(len(block)) if s == "head" else np.flatnonzero(np.concatenate([doc["exists"][:, d] for doc in test])) | |
| block[real] = block[rng.permutation(real)] # copied chains that are too short keep their (unused) rows | |
| shuffled[s, d] = (block, np.concatenate([[0], np.cumsum(sizes)])) | |
| policies = ["tree", "fixed_rule"] + [f"{w}_{f}" for w in SETS for f in FAMILIES] | |
| per_doc = {pol: {n: [] for n in BUDGETS} for pol in policies} | |
| copy_verified = {pol: {n: [0, 0] for n in BUDGETS} for pol in policies[2:]} | |
| for i, doc in enumerate(test): | |
| for pol in ("tree", "fixed_rule"): | |
| for n in BUDGETS: | |
| per_doc[pol][n].append(replay(doc["base"][pol, n])) | |
| for which in SETS: | |
| for fam in FAMILIES: | |
| head_scores, prev = [], None | |
| copy_score = np.zeros((doc["cx"].shape[0], COPY), dtype=np.float32) | |
| for d in range(DEPTH): | |
| x = doc["x"][d].reshape(-1, N_CONF["head"] + N_LING) | |
| c = doc["cx"][:, d] | |
| if which == "conf": | |
| x, c = x[:, : N_CONF["head"]], c[:, : N_CONF["copy"]] | |
| elif which == "shuf": | |
| (bh, oh), (bc, oc) = shuffled["head", d], shuffled["copy", d] | |
| x = np.concatenate([x[:, : N_CONF["head"]], bh[oh[i] : oh[i + 1]]], 1) | |
| c = np.concatenate([c[:, : N_CONF["copy"]], bc[oc[i] : oc[i + 1]]], 1) | |
| own = torch.nn.functional.logsigmoid(predict("head", which, fam, d, x)).cpu().numpy().reshape(doc["x"][d].shape[:2]) | |
| prev = own if prev is None else np.take_along_axis(prev, doc["parent"][d], 1) + own | |
| head_scores.append(prev) | |
| copy_score[:, d] = (copy_score[:, d - 1] if d else 0) + torch.nn.functional.logsigmoid(predict("copy", which, fam, d, c)).cpu().numpy() | |
| copy_score = np.where(doc["exists"], copy_score, -np.inf) | |
| for n in BUDGETS: | |
| depth, n_copy = allocate(head_scores, doc["true"], copy_score, doc["copy_true"], n) | |
| per_doc[f"{which}_{fam}"][n].append(replay(depth)) | |
| copy_verified[f"{which}_{fam}"][n][0] += int(n_copy.sum()) | |
| copy_verified[f"{which}_{fam}"][n][1] += len(n_copy) | |
| for which in SETS: # the calibrator of each feature set is the family with the lower validation log-loss | |
| per_doc[which] = per_doc[f"{which}_{chosen[which]}"] | |
| names = policies + list(SETS) | |
| res = { | |
| "name": args.name, "seed": int(seed), "ckpt_root": args.ckpt_root, "arm": args.arm, "gpu": torch.cuda.get_device_name(DEVICE), "scheme": args.scheme, | |
| "look_ahead_heads": DEPTH, "beam": BEAM, "candidates_per_node": K, "copied_tokens": COPY, | |
| "test_docs": n_test, "calibration_docs": n_train, "validation_docs": n_val, | |
| "features": {"head_confidence_and_source": CONF_NAMES + HEAD_SOURCE_NAMES, "copy_confidence_and_source": COPY_CONF_NAMES, "linguistic": LING_NAMES}, | |
| "fit_rows_by_source_and_depth": fit_rows, | |
| "validation_log_loss_by_depth": {f"{s}_{w}_{f}": [val_loss[s, w, f, d] for d in range(DEPTH)] for s in SOURCES for w in SETS for f in FAMILIES}, | |
| "test_calibration_by_source_and_depth": test_calibration, "chosen_family": chosen, | |
| "tokens_per_pass": {pol: {str(n): tpp(per_doc[pol][n]) for n in BUDGETS} for pol in names}, | |
| "copy_nodes_verified_per_pass_position": {pol: {str(n): v[n][0] / v[n][1] for n in BUDGETS} for pol, v in copy_verified.items()}, | |
| "tests_percent_gain": {}, "ling_lr_coefficients_by_source_and_depth": coef, | |
| "per_document": {pol: {str(n): np.array(per_doc[pol][n]).tolist() for n in BUDGETS} for pol in names}, | |
| } | |
| for n in BUDGETS: | |
| arr = {pol: np.array(per_doc[pol][n], dtype=float) for pol in names} | |
| t = {} | |
| for suffix in ("", "_lr", "_mlp"): | |
| for a, b in TESTS: | |
| a_, b_ = (a + suffix if a in SETS else a), (b + suffix if b in SETS else b) | |
| t[f"{a_}_vs_{b_}"] = bootstrap_gain(arr[a_], arr[b_]) | |
| res["tests_percent_gain"][str(n)] = t | |
| res["wall_seconds"] = time.perf_counter() - t1 | |
| res["wall_seconds_shared_setup"] = t1 - t0 if seed == args.seeds.split(",")[0] else 0.0 | |
| res["peak_gpu_mib"] = torch.cuda.max_memory_allocated(DEVICE) / 2**20 | |
| out = Path(args.out.replace("{seed}", seed)) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| out.write_text(json.dumps(res, indent=1)) | |
| print(f"{args.name} seed {seed}: chosen {chosen}", flush=True) | |
| for pol in names: | |
| print(f" {pol:12s} " + " ".join(f"N={n}: {res['tokens_per_pass'][pol][str(n)]:.3f}" for n in BUDGETS), flush=True) | |
| for n in BUDGETS: | |
| t = res["tests_percent_gain"][str(n)] | |
| print(f" N={n:2d} " + " ".join(f"{k} {t[k][0]:+.2f}% [{t[k][1]:+.2f}, {t[k][2]:+.2f}]" for k in ("conf_vs_fixed_rule", "ling_vs_conf", "shuf_vs_conf", "conf_vs_tree", "ling_lr_vs_conf_lr", "ling_mlp_vs_conf_mlp")), flush=True) | |
| print(" copy nodes verified per position: " + " ".join(f"{pol} " + "/".join(f"{res['copy_nodes_verified_per_pass_position'][pol][str(n)]:.2f}" for n in BUDGETS) for pol in ("conf_lr", "conf_mlp", "ling_mlp")), flush=True) | |
| for key, e in test_calibration.items(): | |
| print(f" {key} test log-loss / ECE: " + " ".join(f"{k} {e[k]['log_loss']:.4f} / {e[k]['ece']:.4f}" for k in e if isinstance(e[k], dict)), flush=True) | |
| print(f"{args.name} seed {seed}: {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True) | |
| del test, rows, fit | |
| if __name__ == "__main__": | |
| main() | |