Download scripts/phase4_pilot_conflict.py from Anupam-Rawat-IITB/code-switch-mtp: direct link, hf CLI and curl.
- Browser
- Download file 8.54 kB
-
https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase4_pilot_conflict.py
- Command line
-
hf download hf://Anupam-Rawat-IITB/code-switch-mtp/scripts/phase4_pilot_conflict.py
-
curl -L -o phase4_pilot_conflict.py https://huggingface.co/Anupam-Rawat-IITB/code-switch-mtp/resolve/main/scripts/phase4_pilot_conflict.py
8.54 kB
| """Phase 4f: does boundary-aware training leave a shared trunk whose objectives conflict less? | |
| The boundary-weighted pilot (scripts/phase4_boundary_weighted_train.py) | |
| trains Hindi-Roman (ITRANS) stacks whose look-ahead losses down-weight | |
| (alpha = 0.25) or drop (alpha = 0) targets that lie past the next token's | |
| word, next to a uniform arm (alpha = 1) trained identically. Each arm's | |
| trainer logged conflict under its own weighted objective; here every arm | |
| is probed the same way -- unweighted per-position gradients, as in Phase 4a | |
| -- so the arms are comparable with each other and with Phase 3. | |
| Per arm, on the Phase 4a held-out documents: | |
| * conflict rate (cos < 0 between the next-token and k-ahead gradients on | |
| the trunk output) when the k-ahead target lies in the next word vs the | |
| same word, k = 2..4; | |
| * the within-word morpheme split of Phase 4e (ITRANS Morfessor model); | |
| * the aggregate parameter-space cosine between the two objectives. | |
| """ | |
| import argparse | |
| import csv | |
| import logging | |
| import os | |
| import sys | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID") | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| import torch | |
| import torch.nn.functional as F | |
| import yaml | |
| from scripts.phase4_gradient_conflict import load_stack, per_position_grads | |
| from scripts.phase4_morpheme_boundaries import token_byte_table, token_flags, train_segmenter | |
| from src.train.evaluate import word_start_flags | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") | |
| logging.getLogger("httpx").setLevel(logging.WARNING) | |
| logging.getLogger("huggingface_hub").setLevel(logging.WARNING) | |
| logger = logging.getLogger("phase4f") | |
| DEVICE = "cuda:0" | |
| N_HEADS = 4 | |
| PILOT_DIR = "/data/cs769_mtp/scratch/checkpoints/phase4/L2_seed0" | |
| DEFAULT_RUNS = [ | |
| f"uniform_alpha1={PILOT_DIR}/alpha_1.pt", | |
| f"downweighted_alpha0.25={PILOT_DIR}/alpha_0.25.pt", | |
| f"masked_alpha0={PILOT_DIR}/alpha_0.pt", | |
| "phase3_uniform_10M_tokens=/data/cs769_mtp/scratch/checkpoints/phase3/L2_seed0/mtp.pt", | |
| ] | |
| def parse_args() -> argparse.Namespace: | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--config", default="configs/phase3.yaml") | |
| p.add_argument("--runs", nargs="+", default=DEFAULT_RUNS, help="label=checkpoint_path") | |
| p.add_argument("--condition", default="L2") | |
| p.add_argument("--n-docs", type=int, default=128) | |
| p.add_argument("--max-tokens", type=int, default=512) | |
| p.add_argument("--morfessor-model", default="/data/cs769_mtp/scratch/runs/phase4/morfessor/morfessor_itrans.bin") | |
| p.add_argument("--out", default="results/phase4_pilot_conflict.csv") | |
| return p.parse_args() | |
| def main() -> None: | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from src.train.data import load_heldout_texts | |
| args = parse_args() | |
| with open(args.config, encoding="utf-8") as f: | |
| cfg = yaml.safe_load(f) | |
| started = time.perf_counter() | |
| tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"]) | |
| backbone = AutoModelForCausalLM.from_pretrained(cfg["backbone"]["hf_id"], dtype=torch.float32).to(DEVICE) | |
| backbone.eval() | |
| for param in backbone.parameters(): | |
| param.requires_grad = False | |
| byte_table = token_byte_table(tokenizer) | |
| if not Path(args.morfessor_model).exists(): | |
| raise FileNotFoundError(f"{args.morfessor_model}: run scripts/phase4_morpheme_boundaries.py --train-only first") | |
| segment = train_segmenter({}, Path(args.morfessor_model)) | |
| texts = load_heldout_texts(str(Path(cfg["data_dir"]) / f"{args.condition}_heldout.jsonl"))[: args.n_docs] | |
| docs = [] | |
| for text in texts: | |
| enc = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True, truncation=True, max_length=args.max_tokens) | |
| if len(enc.input_ids) < N_HEADS + 4: | |
| continue | |
| fl = token_flags(enc.input_ids, byte_table, segment, "itrans") | |
| docs.append({"ids": enc.input_ids, "word": word_start_flags(text, enc.offset_mapping), "within": fl["within"], "morph": fl["morph_start"]}) | |
| rows = [["run", "k", "split", "cell", "metric", "value", "n"]] | |
| def add(run, k, split, cell, metric, value, n): | |
| rows.append([run, k, split, cell, metric, f"{value:.6f}" if isinstance(value, float) else value, n]) | |
| for spec in args.runs: | |
| label, path = spec.split("=", 1) | |
| t0 = time.perf_counter() | |
| stack = load_stack(backbone, Path(path)) | |
| trunk_params = list(stack.trunk.parameters()) | |
| cells = defaultdict(lambda: [0, 0, 0.0]) # (k, split, cell) -> [n, n_conflict, sum_cos] | |
| param_acc = {} | |
| for d in docs: | |
| block = torch.tensor([d["ids"]], dtype=torch.long, device=DEVICE) | |
| seq = block.shape[1] | |
| with torch.no_grad(): | |
| hidden = backbone.model(input_ids=block).last_hidden_state | |
| with torch.enable_grad(): | |
| trunk_out = stack.trunk_states(hidden) | |
| leaf = trunk_out.detach().requires_grad_(True) | |
| grads = per_position_grads(stack, leaf, block) | |
| for k in range(2, N_HEADS + 1): | |
| valid = seq - k | |
| cos = F.cosine_similarity(grads[1][:valid], grads[k][:valid], dim=-1, eps=1e-12).tolist() | |
| for p_ in range(valid): | |
| span = range(p_ + 2, p_ + k + 1) | |
| keys = [(k, "all", "all"), (k, "word", "next_word" if any(d["word"][t] for t in span) else "same_word")] | |
| if all(d["within"][t] for t in span): | |
| keys.append((k, "morpheme_within_word", "crosses_morpheme" if any(d["morph"][t] for t in span) else "same_morpheme")) | |
| for key in keys: | |
| c = cells[key] | |
| c[0] += 1 | |
| c[1] += int(cos[p_] < 0) | |
| c[2] += cos[p_] | |
| weight = torch.zeros(seq, device=DEVICE) | |
| weight[:valid] = 1.0 | |
| for who in (1, k): | |
| pg = torch.autograd.grad(trunk_out, trunk_params, grad_outputs=(grads[who] * weight[:, None]).unsqueeze(0), retain_graph=True) | |
| flat = torch.cat([t.reshape(-1) for t in pg]) | |
| key = (k, who) | |
| param_acc[key] = flat if key not in param_acc else param_acc[key] + flat | |
| del grads, leaf, trunk_out, hidden | |
| for (k, split, cell), (n, nc, sc) in sorted(cells.items()): | |
| add(label, k, split, cell, "conflict_rate", nc / n if n else float("nan"), n) | |
| add(label, k, split, cell, "mean_cos", sc / n if n else float("nan"), n) | |
| for k in range(2, N_HEADS + 1): | |
| g1, gk = param_acc[(k, 1)], param_acc[(k, k)] | |
| add(label, k, "parameter", "all", "aggregate_cos", float(F.cosine_similarity(g1, gk, dim=0, eps=1e-12)), len(docs)) | |
| add(label, k, "parameter", "all", "norm_ratio_predk_over_pred1", float(gk.norm() / g1.norm()), len(docs)) | |
| add(label, 0, "meta", "all", "wall_seconds", time.perf_counter() - t0, 1) | |
| def r(k, split, cell): | |
| n, nc, _ = cells[(k, split, cell)] | |
| return nc / n if n else float("nan") | |
| logger.info( | |
| "%s: k2 conflict next-word %.3f same-word %.3f | morph crosses %.3f same %.3f | agg cos k2 %.3f k4 %.3f | %.0fs", | |
| label, r(2, "word", "next_word"), r(2, "word", "same_word"), | |
| r(2, "morpheme_within_word", "crosses_morpheme"), r(2, "morpheme_within_word", "same_morpheme"), | |
| float(F.cosine_similarity(param_acc[(2, 1)], param_acc[(2, 2)], dim=0)), | |
| float(F.cosine_similarity(param_acc[(4, 1)], param_acc[(4, 4)], dim=0)), | |
| time.perf_counter() - t0, | |
| ) | |
| del stack, param_acc | |
| torch.cuda.empty_cache() | |
| add("all", 0, "meta", "all", "docs", len(docs), len(docs)) | |
| add("all", 0, "meta", "all", "peak_gpu_mib", torch.cuda.max_memory_allocated(DEVICE) / (1024**2), 1) | |
| add("all", 0, "meta", "all", "total_wall_seconds", time.perf_counter() - started, 1) | |
| rows.append(["all", 0, "meta", "all", "gpu", torch.cuda.get_device_name(DEVICE), 1]) | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| with open(args.out, "w", newline="", encoding="utf-8") as f: | |
| csv.writer(f).writerows(rows) | |
| logger.info("wrote %s", args.out) | |
| if __name__ == "__main__": | |
| main() | |