File size: 10,720 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
"""Probe: does conditioning draft token k on draft token k-1 help, and where?

Training-free. Existing Medusa-style heads give p_k(x_{t+k} | ctx). We add a
product-of-experts correction from a token-bigram table counted on the
training stream:

    score(x) = log p_k(x | ctx) + beta * [log p_big(x | prev) - log p_uni(x)]

Variants restrict the correction to within-word structure (which continuation
piece) or cross-word structure (which word-start piece), the other class only
receiving the class-level ratio.

Part A: teacher-forced accuracy on held-out text, split by target type.
Part B: replay against the backbone's greedy continuation (tokens per
verification pass, 4 drafts + 1 bonus token), same protocol as
scripts/phase4_boundary_decoding.py.
"""

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("/home/cs769_mtp/code-switch-mtp")
sys.path.insert(0, str(REPO))
sys.path.insert(0, str(REPO / "scripts"))

import numpy as np
import torch
import torch.nn.functional as F

DEVICE = "cuda:0"
N_HEADS = 4
ALPHA = 1.0


class Bigram:
    def __init__(self, ids: np.ndarray, vocab: int, is_start: torch.Tensor):
        ids = ids.astype(np.int64)
        a, b = ids[:-1], ids[1:]
        keys, counts = np.unique(a * vocab + b, return_counts=True)
        ka, kb = keys // vocab, keys % vocab
        c1 = np.bincount(a, minlength=vocab).astype(np.float64)
        pu = (np.bincount(ids, minlength=vocab) + 0.5).astype(np.float64)
        pu /= pu.sum()
        vals = np.log((counts + ALPHA * pu[kb]) / ((c1[ka] + ALPHA) * pu[kb]))
        row_ptr = np.searchsorted(ka, np.arange(vocab + 1))
        st = is_start.cpu().numpy()
        cs = np.bincount(a, weights=st[b].astype(np.float64), minlength=vocab)
        ps = float((pu * st).sum())
        p_start = (cs + ALPHA * ps) / (c1 + ALPHA)
        self.vocab = vocab
        self.is_start = is_start.to(DEVICE)
        self.cols = torch.from_numpy(kb).to(DEVICE)
        self.vals = torch.from_numpy(vals).float().to(DEVICE)
        self.row_ptr = torch.from_numpy(row_ptr).to(DEVICE)
        self.base = torch.from_numpy(np.log(ALPHA / (c1 + ALPHA))).float().to(DEVICE)
        self.start_ratio = torch.from_numpy(np.log(p_start / ps)).float().to(DEVICE)
        self.cont_ratio = torch.from_numpy(np.log((1 - p_start) / (1 - ps))).float().to(DEVICE)
        self.nnz = len(keys)

    def rows(self, prev: torch.Tensor, variant: str) -> torch.Tensor:
        """prev: (n,) token ids -> (n, vocab) log-ratio correction."""
        n = prev.shape[0]
        lo, hi = self.row_ptr[prev], self.row_ptr[prev + 1]
        lens = hi - lo
        R = self.base[prev][:, None].expand(n, self.vocab).clone()
        if int(lens.sum()) > 0:
            row_idx = torch.repeat_interleave(torch.arange(n, device=DEVICE), lens)
            starts = torch.repeat_interleave(lo, lens)
            offs = torch.arange(int(lens.sum()), device=DEVICE) - torch.repeat_interleave(torch.cumsum(lens, 0) - lens, lens)
            idx = starts + offs
            R[row_idx, self.cols[idx]] = self.vals[idx]
        if variant == "full":
            return R
        if variant == "within":  # which continuation piece; word-start class only by class ratio
            return torch.where(self.is_start[None, :], self.start_ratio[prev][:, None], R)
        if variant == "cross":  # which word-start piece; continuation class only by class ratio
            return torch.where(self.is_start[None, :], R, self.cont_ratio[prev][:, None])
        raise ValueError(variant)


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--name", required=True)
    p.add_argument("--ckpt", required=True)
    p.add_argument("--train-ids", required=True)
    p.add_argument("--heldout", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--n-docs", type=int, default=128)
    p.add_argument("--spec-docs", type=int, default=256)
    p.add_argument("--betas", default="0.25,0.5,1.0")
    args = p.parse_args()
    betas = [float(x) for x in args.betas.split(",")]
    t0 = time.perf_counter()

    from transformers import AutoModelForCausalLM, AutoTokenizer
    import phase4_boundary_decoding as pb
    from src.train.data import load_heldout_texts
    from src.train.evaluate import word_start_flags

    tok = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-1B")
    backbone = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B", dtype=torch.float32).to(DEVICE).eval()
    for q in backbone.parameters():
        q.requires_grad = False
    V = backbone.config.vocab_size
    starts_table = pb.word_start_table(tok)
    is_start = torch.zeros(V, dtype=torch.bool)
    is_start[: len(starts_table)] = torch.tensor(starts_table)
    bg = Bigram(np.load(args.train_ids), V, is_start)
    stack = pb.load_stack(backbone, Path(args.ckpt), shared_trunk=True)
    texts = load_heldout_texts(args.heldout)
    res = {"name": args.name, "bigram_nnz": bg.nnz, "betas": betas}
    variants = ["full", "within", "cross"]
    CH = 96

    # ---------- Part A: teacher-forced accuracy on held-out text ----------
    keys = ["marginal", "oracle_backbone"] + [f"{v}_b{b}" for v in variants for b in betas]
    acc = {k: {h: {"intra": [0, 0], "bound": [0, 0]} for h in range(1, N_HEADS + 1)} for k in keys}
    with torch.no_grad():
        for text in texts[: args.n_docs]:
            enc = tok(text, add_special_tokens=False, return_offsets_mapping=True, truncation=True, max_length=512)
            ids = enc.input_ids
            if len(ids) < 16:
                continue
            flags = torch.tensor(word_start_flags(text, enc.offset_mapping), device=DEVICE)
            block = torch.tensor([ids], device=DEVICE)
            hidden = backbone.model(input_ids=block).last_hidden_state
            trunk = stack.trunk_states(hidden)
            base_pred = backbone.lm_head(hidden).argmax(-1)[0]  # predicts ids[t+1]
            x = block[0]
            L = len(ids)
            for h in range(1, N_HEADS + 1):
                n = L - h
                tgt = x[h:]
                tflag = flags[h:]
                logp = F.log_softmax(stack.head_logits(trunk, h - 1)[0, :n], dim=-1)
                preds = {"marginal": logp.argmax(-1), "oracle_backbone": base_pred[h - 1 : h - 1 + n]}
                if h >= 2:
                    prev = x[h - 1 : h - 1 + n]
                    for v in variants:
                        outs = {b: [] for b in betas}
                        for s in range(0, n, CH):
                            R = bg.rows(prev[s : s + CH], v)
                            for b in betas:
                                outs[b].append((logp[s : s + CH] + b * R).argmax(-1))
                            del R
                        for b in betas:
                            preds[f"{v}_b{b}"] = torch.cat(outs[b])
                else:
                    for v in variants:
                        for b in betas:
                            preds[f"{v}_b{b}"] = preds["marginal"]
                for k, pr in preds.items():
                    ok = pr == tgt
                    acc[k][h]["bound"][0] += int((ok & tflag).sum()); acc[k][h]["bound"][1] += int(tflag.sum())
                    acc[k][h]["intra"][0] += int((ok & ~tflag).sum()); acc[k][h]["intra"][1] += int((~tflag).sum())
    res["teacher_forced"] = {
        k: {str(h): {"intra": d["intra"][0] / max(1, d["intra"][1]), "bound": d["bound"][0] / max(1, d["bound"][1]),
                     "all": (d["intra"][0] + d["bound"][0]) / max(1, d["intra"][1] + d["bound"][1]),
                     "n_intra": d["intra"][1], "n_bound": d["bound"][1]} for h, d in hd.items()}
        for k, hd in acc.items()
    }
    res["partA_seconds"] = time.perf_counter() - t0
    Path(args.out).write_text(json.dumps(res, indent=1))
    print(args.name, "part A done", f"{res['partA_seconds']:.0f}s", flush=True)

    # ---------- Part B: replay on the backbone's greedy continuation ----------
    t1 = time.perf_counter()
    eos = backbone.generation_config.eos_token_id
    eos_ids = set(eos if isinstance(eos, list) else [eos])
    pairs = pb.generate_continuations(backbone, tok, texts[: args.spec_docs], 256, 64 + pb.LOOKAHEAD, 16, eos_ids)
    pol = ["marginal"] + [f"{v}_b{b}" for v in variants for b in betas]
    tot = {k: [0, 0] for k in pol}  # committed, rounds
    pos_acc = {k: [[0, 0] for _ in range(N_HEADS)] for k in pol}  # per draft position: accepted, reached
    with torch.no_grad():
        for prompt, cont in pairs:
            horizon = min(64, len(cont) - pb.LOOKAHEAD + 1)
            if horizon < 1:
                continue
            full = torch.tensor([prompt + cont], device=DEVICE)
            p0 = len(prompt) - 1
            hidden = backbone.model(input_ids=full).last_hidden_state[:, p0 : p0 + horizon, :]
            trunk = stack.trunk_states(hidden)
            logps = [F.log_softmax(stack.head_logits(trunk, i)[0], dim=-1) for i in range(N_HEADS)]
            continuation = [prompt[-1]] + cont
            drafts = {"marginal": torch.stack([lp.argmax(-1) for lp in logps], 1).tolist()}
            for v in variants:
                for b in betas:
                    d = [logps[0].argmax(-1)]
                    for i in range(1, N_HEADS):
                        out = []
                        for s in range(0, horizon, CH):
                            out.append((logps[i][s : s + CH] + b * bg.rows(d[-1][s : s + CH], v)).argmax(-1))
                        d.append(torch.cat(out))
                    drafts[f"{v}_b{b}"] = torch.stack(d, 1).tolist()
            for k in pol:
                j = 0
                while j < horizon:
                    n_acc = pb.accepted_count(drafts[k][j], continuation, j, N_HEADS)
                    for i in range(N_HEADS):
                        if i <= n_acc:
                            pos_acc[k][i][1] += 1
                            pos_acc[k][i][0] += int(i < n_acc)
                    tot[k][0] += n_acc + 1
                    tot[k][1] += 1
                    j += n_acc + 1
    res["replay"] = {k: {"tokens_per_step": tot[k][0] / tot[k][1], "rounds": tot[k][1],
                         "accept_by_position": [a / max(1, r) for a, r in pos_acc[k]]} for k in pol}
    res["replay_docs"] = len(pairs)
    res["partB_seconds"] = time.perf_counter() - t1
    res["peak_gpu_mib"] = torch.cuda.max_memory_allocated(DEVICE) / 2**20
    res["gpu"] = torch.cuda.get_device_name(DEVICE)
    Path(args.out).write_text(json.dumps(res, indent=1))
    print(args.name, "done", f"{time.perf_counter() - t0:.0f}s", flush=True)


if __name__ == "__main__":
    main()