File size: 15,771 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
"""Phase 4d: entropy-surge boundaries (AdaMTP-style) versus word starts.

AdaMTP (Cui et al., arXiv 2608.00434) segments text where the base model's
uncertainty jumps: with E_t the entropy of P(token t | tokens before t), a new
group starts at token t when E_t - E_{t-1} > tau, and tau is set over the
dataset so that the average group size equals the number of prediction heads.
A prediction from position p is masked when its target lies beyond the group
containing token p+1 -- the same geometry as this project's "crosses a word"
split, with entropy groups in place of words.

This script measures, on the same held-out documents and generated
continuations as Phase 4a/4b:
  1. how well entropy-surge boundaries coincide with word starts
     (precision / recall / F1, word starts as the reference);
  2. gradient conflict (cos < 0 between the next-token and k-ahead gradients
     on the shared trunk) split by "the k-span crosses an entropy boundary"
     versus "crosses a word start", including the 2x2;
  3. draft acceptance at decode time split by whether the true token is an
     entropy boundary versus a word start, including the 2x2.

Two thresholds are reported: tau_adamtp (boundary rate = 1 / n_heads, the
paper's calibration) and tau_matched (boundary rate = the language's word
start rate), so the two signals can also be compared at equal rates.
"""

import argparse
import csv
import json
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_boundary_decoding import LOOKAHEAD, drafts_for_doc, simulate_doc, word_start_table
from scripts.phase4_boundary_decoding import load_stack as load_any_stack
from scripts.phase4_gradient_conflict import per_position_grads
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("phase4d")

DEVICE = "cuda:0"
N_HEADS = 4
SIGNALS = ("word", "entropy_adamtp", "entropy_matched")


def entropy_surge(next_token_entropy: list) -> list:
    """Per token t, the surge E_t - E_{t-1}, where E_t = next_token_entropy[t-1].

    next_token_entropy[p] is the entropy of the prediction made at position p,
    i.e. of token p+1. Tokens 0 and 1 have no surge and get None.
    """
    surge = [None, None]
    for t in range(2, len(next_token_entropy) + 1):
        surge.append(next_token_entropy[t - 1] - next_token_entropy[t - 2])
    return surge


def boundary_flags(surge: list, tau: float) -> list:
    """Token t starts an entropy group when its surge exceeds tau (undefined surges -> False)."""
    return [s is not None and s > tau for s in surge]


def crossing_mask(flags: list, k: int) -> list:
    """For positions p = 0 .. len(flags)-k-1: does a flagged token occur among p+2 .. p+k?

    This is the AdaMTP masking condition for the prediction p -> p+k when the
    flags are group starts, and the Phase 4a "crosses a word" condition when
    they are word starts.
    """
    return [any(flags[p + 2 : p + k + 1]) for p in range(len(flags) - k)]


def overlap(pred: list, ref: list) -> dict:
    tp = sum(1 for a, b in zip(pred, ref) if a and b)
    fp = sum(1 for a, b in zip(pred, ref) if a and not b)
    fn = sum(1 for a, b in zip(pred, ref) if b and not a)
    precision = tp / (tp + fp) if tp + fp else float("nan")
    recall = tp / (tp + fn) if tp + fn else float("nan")
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else float("nan")
    return {"precision": precision, "recall": recall, "f1": f1, "pred_rate": (tp + fp) / len(pred), "ref_rate": (tp + fn) / len(pred), "n": len(pred)}


@torch.no_grad()
def next_token_entropy(backbone, hidden: torch.Tensor) -> list:
    """Entropy (nats) of the backbone's next-token distribution at every position of hidden (1, seq, h)."""
    out = []
    for chunk in hidden[0].split(128):
        logp = torch.log_softmax(backbone.lm_head(chunk), dim=-1)
        out.append(-(logp.exp() * logp).sum(dim=-1))
    return torch.cat(out).tolist()


def quantile_threshold(values: list, flagged_rate: float) -> float:
    vals = torch.tensor(values, dtype=torch.float64)
    return float(torch.quantile(vals, 1.0 - flagged_rate))


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--config", default="configs/phase3.yaml")
    p.add_argument("--runs", nargs="+", default=["L4_seed0", "L4_seed1", "L2_seed0", "E1_seed0"])
    p.add_argument("--n-docs", type=int, default=128, help="held-out documents for overlap and gradient conflict")
    p.add_argument("--max-tokens", type=int, default=512)
    p.add_argument("--continuations", default="/data/cs769_mtp/scratch/runs/phase4/continuations/{condition}_p256_c64_n256.json")
    p.add_argument("--completion-tokens", type=int, default=64)
    p.add_argument("--out", default="results/phase4_entropy_vs_word.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
    starts_table = word_start_table(tokenizer)

    rows = [["run", "condition", "seed", "analysis", "signal", "cell", "metric", "value", "n"]]

    def add(run, analysis, signal, cell, metric, value, n):
        condition, seed = run.split("_") if "_" in run else (run, "all")
        rows.append([run, condition, seed, analysis, signal, cell, metric, f"{value:.6f}" if isinstance(value, float) else value, n])

    # ---- per language: base-model entropies, thresholds, overlap (independent of the MTP checkpoint)
    lang = {}
    for condition in dict.fromkeys(r.split("_")[0] for r in args.runs):
        t0 = time.perf_counter()
        texts = load_heldout_texts(str(Path(cfg["data_dir"]) / f"{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)
            ids = enc.input_ids
            if len(ids) < N_HEADS + 4:
                continue
            block = torch.tensor([ids], dtype=torch.long, device=DEVICE)
            with torch.no_grad():
                hidden = backbone.model(input_ids=block).last_hidden_state
            ent = next_token_entropy(backbone, hidden)
            docs.append({"ids": ids, "word": word_start_flags(text, enc.offset_mapping), "surge": entropy_surge(ent[:-1])})
        surges = [s for d in docs for s in d["surge"] if s is not None]
        word_rate = sum(sum(d["word"][2:]) for d in docs) / sum(len(d["word"]) - 2 for d in docs)
        tau = {"entropy_adamtp": quantile_threshold(surges, 1.0 / N_HEADS), "entropy_matched": quantile_threshold(surges, word_rate)}

        # generated continuations: entropies over prompt + continuation
        pairs = json.loads(Path(args.continuations.format(condition=condition)).read_text())
        gen = []
        for prompt, cont in pairs:
            horizon = min(args.completion_tokens, len(cont) - LOOKAHEAD + 1)
            if horizon < 1:
                continue
            full = torch.tensor([prompt + cont], dtype=torch.long, device=DEVICE)
            with torch.no_grad():
                hidden = backbone.model(input_ids=full).last_hidden_state
            ent = next_token_entropy(backbone, hidden)
            surge_abs = entropy_surge(ent[:-1])  # aligned with absolute token index
            p0 = len(prompt) - 1
            continuation = [prompt[-1]] + cont
            gen.append({"prompt": prompt, "cont": cont, "horizon": horizon, "surge": surge_abs[p0 : p0 + len(continuation)], "word": [starts_table[t] for t in continuation]})

        for signal in ("entropy_adamtp", "entropy_matched"):
            for d in docs:
                d[signal] = boundary_flags(d["surge"], tau[signal])
            for g in gen:
                g[signal] = boundary_flags(g["surge"], tau[signal])
            held = overlap([f for d in docs for f in d[signal][2:]], [f for d in docs for f in d["word"][2:]])
            gener = overlap([f for g in gen for f in g[signal][1 : g["horizon"] + 1]], [f for g in gen for f in g["word"][1 : g["horizon"] + 1]])
            for metric, value in held.items():
                add(f"{condition}_all", "overlap_heldout", signal, "all", metric, float(value) if metric != "n" else value, held["n"])
            for metric, value in gener.items():
                add(f"{condition}_all", "overlap_generated", signal, "all", metric, float(value) if metric != "n" else value, gener["n"])
            add(f"{condition}_all", "threshold", signal, "all", "tau_nats", tau[signal], len(surges))
        add(f"{condition}_all", "threshold", "word", "all", "word_start_rate_heldout", word_rate, len(surges))
        lang[condition] = {"docs": docs, "gen": gen, "tau": tau}
        logger.info(
            "%s: tau_adamtp %.3f tau_matched %.3f word-rate %.3f | %.0fs",
            condition, tau["entropy_adamtp"], tau["entropy_matched"], word_rate, time.perf_counter() - t0,
        )

    # ---- per checkpoint: gradient conflict and draft acceptance by signal
    for run in args.runs:
        condition = run.split("_")[0]
        t0 = time.perf_counter()
        stack = load_any_stack(backbone, Path(cfg["checkpoint_dir"]) / run / "mtp.pt", shared_trunk=True)
        for p in stack.parameters():
            p.requires_grad_(False)

        conflict = defaultdict(lambda: [0, 0])  # (k, signal, cell) -> [n, n_conflict]
        conflict2x2 = defaultdict(lambda: [0, 0])  # (k, entropy signal, word?, entropy?) -> [n, n_conflict]
        for d in lang[condition]["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
                trunk_out = stack.trunk_states(hidden)
            leaf = trunk_out.detach().requires_grad_(True)
            with torch.enable_grad():
                grads = per_position_grads(stack, leaf, block)
            for k in range(2, N_HEADS + 1):
                valid = seq - k
                neg = (F.cosine_similarity(grads[1][:valid], grads[k][:valid], dim=-1, eps=1e-12) < 0).tolist()
                masks = {s: crossing_mask(d[s], k) for s in SIGNALS}
                for s in SIGNALS:
                    for p_, c in enumerate(masks[s]):
                        cell = conflict[(k, s, c)]
                        cell[0] += 1
                        cell[1] += int(neg[p_])
                for s in ("entropy_adamtp", "entropy_matched"):
                    for p_ in range(valid):
                        cell = conflict2x2[(k, s, masks["word"][p_], masks[s][p_])]
                        cell[0] += 1
                        cell[1] += int(neg[p_])
            del grads, leaf, trunk_out, hidden

        for (k, s, c), (n, nc) in sorted(conflict.items()):
            add(run, f"conflict_k{k}", s, "crosses" if c else "within", "conflict_rate", nc / n if n else float("nan"), n)
        for (k, s, w, e), (n, nc) in sorted(conflict2x2.items()):
            add(run, f"conflict_k{k}_2x2", s, f"word_{'crosses' if w else 'within'}__entropy_{'crosses' if e else 'within'}", "conflict_rate", nc / n if n else float("nan"), n)

        accept = defaultdict(lambda: [0, 0])  # (i, signal, flag) -> [reached, accepted]
        accept2x2 = defaultdict(lambda: [0, 0])  # (i, entropy signal, word flag, entropy flag)
        failures = defaultdict(lambda: [0, 0])  # signal -> [n failures, n failures on a flagged token]
        for g in lang[condition]["gen"]:
            dd = drafts_for_doc(backbone, stack, g["prompt"], g["cont"], g["horizon"], starts_table)
            per_signal = {s: simulate_doc(dd["drafts"], dd["draft_starts"], dd["continuation"], g[s], g["horizon"], "fixed4") for s in SIGNALS}
            for idx, r_word in enumerate(per_signal["word"]):
                for i in range(N_HEADS):
                    if r_word["n_acc"] < i:
                        break
                    ok = int(r_word["n_acc"] > i)
                    flags = {s: per_signal[s][idx]["true_starts"][i] for s in SIGNALS}
                    for s in SIGNALS:
                        cell = accept[(i + 1, s, flags[s])]
                        cell[0] += 1
                        cell[1] += ok
                    for s in ("entropy_adamtp", "entropy_matched"):
                        cell = accept2x2[(i + 1, s, flags["word"], flags[s])]
                        cell[0] += 1
                        cell[1] += ok
                for s in SIGNALS:
                    f = per_signal[s][idx]["failed_at_word_start"]
                    if f is not None:
                        failures[s][0] += 1
                        failures[s][1] += int(f)

        for (i, s, flag), (n, a) in sorted(accept.items()):
            add(run, f"accept_pos{i}", s, "flagged" if flag else "not_flagged", "acceptance", a / n if n else float("nan"), n)
        for (i, s, w, e), (n, a) in sorted(accept2x2.items()):
            add(run, f"accept_pos{i}_2x2", s, f"word_{'start' if w else 'inside'}__entropy_{'boundary' if e else 'none'}", "acceptance", a / n if n else float("nan"), n)
        for s, (n, nf) in failures.items():
            add(run, "failures", s, "all", "failure_token_flagged", nf / n if n else float("nan"), n)
        add(run, "meta", "all", "all", "wall_seconds", time.perf_counter() - t0, 1)

        def rate(table, key):
            n, x = table[key]
            return x / n if n else float("nan")

        logger.info(
            "%s: conflict k2 word %.3f/%.3f adamtp %.3f/%.3f matched %.3f/%.3f | accept pos2 word %.3f/%.3f adamtp %.3f/%.3f matched %.3f/%.3f | %.0fs",
            run,
            rate(conflict, (2, "word", True)), rate(conflict, (2, "word", False)),
            rate(conflict, (2, "entropy_adamtp", True)), rate(conflict, (2, "entropy_adamtp", False)),
            rate(conflict, (2, "entropy_matched", True)), rate(conflict, (2, "entropy_matched", False)),
            rate(accept, (2, "word", True)), rate(accept, (2, "word", False)),
            rate(accept, (2, "entropy_adamtp", True)), rate(accept, (2, "entropy_adamtp", False)),
            rate(accept, (2, "entropy_matched", True)), rate(accept, (2, "entropy_matched", False)),
            time.perf_counter() - t0,
        )
        del stack
        torch.cuda.empty_cache()

    add("all_all", "meta", "all", "all", "peak_gpu_mib", torch.cuda.max_memory_allocated(DEVICE) / (1024**2), 1)
    add("all_all", "meta", "all", "all", "total_wall_seconds", time.perf_counter() - started, 1)
    rows.append(["all", "all", "all", "meta", "all", "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()