File size: 8,536 Bytes
3bbd5dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
"""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()