File size: 13,926 Bytes
3ef3d94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
305
306
307
308
309
"""J6 full-system eval: all draft branches competing for one node budget N, on the same
Devanagari test documents, for a 3-head and a 5-head stack.

Branches (box code for the tree and the copied branch, my word head for the depth branch):
  tree          confidence tree (phase5_deep_tree.beam_tree / accepted_depth)
  copy          suffix-match copied branch (phase5_copy_branch.copied_branch), COPY=5 nodes, gate m>=2
  wordhead      the deployable word head's TOP-1 predicted whole word, re-encoded to tokens and
                verified against the continuation; costs min(len,WH_MAX) nodes; gate on top-1 prob > tau_d

Configs, each a per-position accepted-draft-depth array fed to phase5_tree_draft.replay:
  (a) tree(N)
  (b) tree + copy               = where copy gate: max(tree(N-5), copy_len); else tree(N)   [= depth_copy]
  (c) tree + copy + wordhead    = reserve 5 for copy and W=min(len,WH_MAX) for the word head where each
                                  gates in, give the rest to the tree, take the max accepted length
                                  (reserve-then-max; primary). Also a mutually-exclusive variant: the word
                                  head only fills where the copy gate is OFF.
  (d) = (b) on the 5-head stack ; (e) = (c) on the 5-head stack.

tau_d is fit on the EVEN-indexed pairs (pairs[0::2]) to maximise config-(c)/(e) tokens/pass at each budget,
and every number is reported on the ODD-indexed pairs (pairs[1::2]) — the same 119-doc test set the box's
deep_tree/depth_copy tables use, so (a)/(b)/(d) are a direct cross-check of those references.
"""

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
import torch.nn as nn

from phase5_deep_tree import beam_tree, accepted_depth
from phase5_copy_branch import copied_branch
from phase5_tree_draft import DEVICE, replay, bootstrap_gain, visited

LOOKAHEAD = 7
COPY = 5
WH_MAX = 5
BEAM = 24
TOPK = 4


def tree_budget_table(levels, nmax: int, horizon: int) -> np.ndarray:
    """(nmax+1, horizon): accepted tree depth at every budget b=0..nmax (b=0 -> all zeros)."""
    tbl = np.zeros((nmax + 1, horizon), dtype=np.int64)
    for b in range(1, nmax + 1):
        tbl[b] = accepted_depth(levels, b)
    return tbl


def compose(doc, d_label, N, tau_d, exclusive):
    """Per-position (accepted draft depth, winning source 0=tree/1=copy/2=wordhead) for config (c)/(e)."""
    Tb = doc[d_label]              # (nmax+1, horizon)
    cg = doc["copy_gate"]          # bool (horizon,)
    copy_len = doc["copy_len"]     # (horizon,)
    wp = doc["wh_present"] & (doc["wh_prob"] > tau_d)
    if exclusive:
        wp = wp & ~cg
    wn = np.where(wp, doc["wh_nodes"], 0)
    tb = np.clip(N - 5 * cg.astype(int) - wn, 0, Tb.shape[0] - 1)
    tree_acc = Tb[tb, np.arange(len(tb))]
    copy_acc = np.where(cg, copy_len, 0)
    wh_acc = np.where(wp, doc["wh_len"], 0)
    stack = np.stack([tree_acc, copy_acc, wh_acc])       # ties resolve tree > copy > wordhead
    accepted = stack.max(0)
    source = stack.argmax(0)
    return accepted, source


def config_ab(doc, d_label, N, with_copy):
    """(a) tree only (with_copy=False) or (b)/(d) tree+copy (with_copy=True)."""
    Tb = doc[d_label]
    if not with_copy:
        return Tb[N].copy(), np.zeros(Tb.shape[1], dtype=np.int64)
    cg = doc["copy_gate"]
    tb = np.where(cg, N - COPY, N)
    tb = np.clip(tb, 0, Tb.shape[0] - 1)
    tree_acc = Tb[tb, np.arange(len(tb))]
    copy_acc = np.where(cg, doc["copy_len"], 0)
    stack = np.stack([tree_acc, copy_acc])
    return stack.max(0), stack.argmax(0)


def replay_pair(accepted):
    return replay(accepted)


def tpp(rows):
    a = np.array(rows, float)
    return float(a[:, 0].sum() / a[:, 1].sum())


@torch.no_grad()
def main() -> None:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--ckpt-3h", required=True)
    p.add_argument("--ckpt-5h", required=True)
    p.add_argument("--wordhead", required=True)
    p.add_argument("--heldout", required=True)
    p.add_argument("--scheme", default="Devanagari")
    p.add_argument("--spec-docs", type=int, default=256)
    p.add_argument("--budgets", type=int, nargs="+", default=[8, 16, 24])
    p.add_argument("--out", required=True)
    args = p.parse_args()
    t0 = time.perf_counter()
    nmax = max(args.budgets)

    from transformers import AutoModelForCausalLM, AutoTokenizer
    import phase4_boundary_decoding as pb
    from phase5_dependent_eval import BACKBONE, load_arm
    from phase5_wordhead_eval import word_at
    from src.models.heads import ResBlock
    from src.train.data import load_heldout_texts

    tok = AutoTokenizer.from_pretrained(BACKBONE)
    backbone = AutoModelForCausalLM.from_pretrained(BACKBONE, dtype=torch.float32).to(DEVICE).eval()
    unembed = backbone.lm_head.weight
    vocab = backbone.config.vocab_size
    starts = pb.word_start_table(tok)
    is_start = np.array(starts + [False] * (vocab - len(starts)))
    eos = backbone.generation_config.eos_token_id
    eos_ids = set(eos if isinstance(eos, list) else [eos])

    stack3 = load_arm(backbone, Path(args.ckpt_3h), True, n_heads=4)
    stack5 = load_arm(backbone, Path(args.ckpt_5h), True, n_heads=6)

    wh = torch.load(args.wordhead, map_location=DEVICE, weights_only=False)
    words = wh["words"]
    word2class = {w: i for i, w in enumerate(words)}
    OOV = len(words)

    class WordHead(nn.Module):
        def __init__(s, h, n):
            super().__init__(); s.resblock = ResBlock(h); s.out = nn.Linear(h, n + 1)
        def forward(s, x): return s.out(s.resblock(x))
    head = WordHead(wh["hidden_size"], wh["n_words"]).to(DEVICE).eval()
    head.load_state_dict(wh["state_dict"])

    import functools

    @functools.lru_cache(maxsize=None)
    def class_tokens(c):
        return tuple(tok.encode(words[c], add_special_tokens=False))

    texts = load_heldout_texts(args.heldout)
    pairs = pb.generate_continuations(backbone, tok, texts[: args.spec_docs], 256, 64 + LOOKAHEAD, 16, eos_ids)
    pairs = [(pr, c) for pr, c in pairs if min(64, len(c) - LOOKAHEAD + 1) >= 1]

    docs = []
    cap_hits = cap_total = 0
    for prompt, cont in pairs:
        horizon = min(64, len(cont) - LOOKAHEAD + 1)
        seq = prompt + cont
        p0 = len(prompt) - 1
        base = len(prompt)
        hid = backbone.model(input_ids=torch.tensor([seq], device=DEVICE)).last_hidden_state[0]
        continuation = [prompt[-1]] + cont
        exact_next = torch.tensor(continuation[1 : horizon + 1], device=DEVICE)
        d = {"horizon": horizon}
        for lbl, stack, depth in (("3h", stack3, 3), ("5h", stack5, 5)):
            trunk = stack.trunk_states(hid[p0 : p0 + horizon])
            truth = torch.tensor([continuation[j + 2 : j + 2 + depth] for j in range(horizon)], device=DEVICE)
            since = torch.zeros(horizon, dtype=torch.long, device=DEVICE)
            levels = beam_tree(stack, unembed, trunk, exact_next, truth, depth, BEAM, since)
            d[lbl] = tree_budget_table(levels, nmax, horizon)
        # copied branch (depth-independent)
        copy_len = np.zeros(horizon, dtype=np.int64); copy_gate = np.zeros(horizon, dtype=bool)
        for j in range(horizon):
            br, m = copied_branch(seq, p0 + 1 + j, COPY)
            tr = seq[p0 + 2 + j : p0 + 2 + j + COPY]
            copy_len[j] = int(np.cumprod([a == b for a, b in zip(br, tr)]).sum()) if br else 0
            copy_gate[j] = m >= 2
        d["copy_len"] = copy_len; d["copy_gate"] = copy_gate
        # word head branch (depth-independent): head top-1 predicted word, verified vs continuation
        wh_len = np.zeros(horizon, dtype=np.int64); wh_prob = np.zeros(horizon)
        wh_present = np.zeros(horizon, dtype=bool); wh_nodes = np.zeros(horizon, dtype=np.int64)
        js, feats = [], []
        for j in range(horizon):
            w = word_at(cont, j + 1, is_start, horizon)
            if w is None or base + j >= hid.shape[0]:
                continue
            js.append(j); feats.append(base + j)
        if js:
            logits = head(hid[torch.tensor(feats, device=DEVICE)])
            top1 = logits.topk(TOPK, -1).indices.cpu().numpy()[:, 0]
            probs = torch.softmax(logits.float(), -1).cpu().numpy()
            for i, j in enumerate(js):
                t1 = int(top1[i])
                if t1 == OOV:
                    continue
                pt = class_tokens(t1)
                if not pt:
                    continue
                cap_total += 1
                if len(pt) >= WH_MAX:
                    cap_hits += 1
                use = list(pt[:WH_MAX])
                acc = 0
                for dd, tk in enumerate(use):
                    tp = j + 1 + dd
                    if tp < horizon and int(cont[tp]) == int(tk):
                        acc += 1
                    else:
                        break
                wh_present[j] = True
                wh_prob[j] = float(probs[i, t1])
                wh_nodes[j] = len(use)
                wh_len[j] = acc
        d["wh_len"] = wh_len; d["wh_prob"] = wh_prob; d["wh_present"] = wh_present; d["wh_nodes"] = wh_nodes
        docs.append(d)

    fit = list(range(0, len(docs), 2))
    test = list(range(1, len(docs), 2))
    tau_d_grid = [0.0, 0.1, 0.2, 0.3, 0.5, 0.7]

    def rows_for(accept_fn, idxs):
        return [replay_pair(accept_fn(docs[i])) for i in idxs]

    def source_share(accept_src_fn, idxs):
        by = np.zeros(3)
        for i in idxs:
            acc, src = accept_src_fn(docs[i])
            pos = visited(acc)
            a = acc[pos]; s = src[pos]
            for k in range(3):
                by[k] += a[s == k].sum()
        tot = by.sum()
        return (by / tot).tolist() if tot else [0, 0, 0]

    results = {"meta": {"backbone": BACKBONE, "scheme": args.scheme, "test_docs": len(test), "fit_docs": len(fit),
                        "copy_nodes": COPY, "wh_max": WH_MAX, "beam": BEAM, "budgets": args.budgets,
                        "wordhead_cap_hit_share": float(cap_hits / max(1, cap_total)),
                        "box_ref_devanagari": {"tree_3h": {"8": 2.661, "16": 2.833, "24": 2.899},
                                               "tree_copy_3h": {"8": 3.569, "16": 3.797},
                                               "tree_copy_5h": {"8": 3.679, "16": 4.045}}},
               "budgets": {}}

    for N in args.budgets:
        a3 = lambda d, N=N: config_ab(d, "3h", N, False)
        b3 = lambda d, N=N: config_ab(d, "3h", N, True)
        d5 = lambda d, N=N: config_ab(d, "5h", N, True)

        def fit_tau(label, N=N):
            best = (-1, 0.0)
            for td in tau_d_grid:
                t = tpp([replay_pair(compose(docs[i], label, N, td, False)[0]) for i in fit])
                if t > best[0]:
                    best = (t, td)
            return best[1]

        tau_c = fit_tau("3h")
        tau_e = fit_tau("5h")
        c3 = lambda d, N=N, td=tau_c: compose(d, "3h", N, td, False)
        c3x = lambda d, N=N, td=tau_c: compose(d, "3h", N, td, True)
        e5 = lambda d, N=N, td=tau_e: compose(d, "5h", N, td, False)
        e5x = lambda d, N=N, td=tau_e: compose(d, "5h", N, td, True)

        rows = {
            "a_tree_3h": rows_for(lambda d: a3(d)[0], test),
            "b_tree_copy_3h": rows_for(lambda d: b3(d)[0], test),
            "c_tree_copy_wh_3h": rows_for(lambda d: c3(d)[0], test),
            "c_tree_copy_wh_3h_exclusive": rows_for(lambda d: c3x(d)[0], test),
            "d_tree_copy_5h": rows_for(lambda d: d5(d)[0], test),
            "e_tree_copy_wh_5h": rows_for(lambda d: e5(d)[0], test),
            "e_tree_copy_wh_5h_exclusive": rows_for(lambda d: e5x(d)[0], test),
        }
        tpps = {k: tpp(v) for k, v in rows.items()}
        arr = {k: np.array(v, float) for k, v in rows.items()}
        order = ["a_tree_3h", "b_tree_copy_3h", "c_tree_copy_wh_3h", "d_tree_copy_5h", "e_tree_copy_wh_5h"]
        vs_prev = {}
        for i, k in enumerate(order):
            if i > 0:
                vs_prev[k] = bootstrap_gain(arr[k], arr[order[i - 1]])
        vs_a = {k: bootstrap_gain(arr[k], arr["a_tree_3h"]) for k in rows if k != "a_tree_3h"}
        results["budgets"][str(N)] = {
            "tau_d_3h": tau_c, "tau_d_5h": tau_e,
            "tokens_per_pass": tpps,
            "pct_vs_a_tree_3h": vs_a,
            "pct_vs_previous_row": vs_prev,
            "wordhead_gain_without_copy": bootstrap_gain(arr["c_tree_copy_wh_3h"], arr["b_tree_copy_3h"]),
            "wordhead_gain_with_copy_5h": bootstrap_gain(arr["e_tree_copy_wh_5h"], arr["d_tree_copy_5h"]),
            "source_share_c_3h": source_share(lambda d: c3(d), test),
            "source_share_e_5h": source_share(lambda d: e5(d), test),
        }
        r = results["budgets"][str(N)]
        print(f"N={N} tau_d 3h={tau_c} 5h={tau_e}", flush=True)
        for k in ["a_tree_3h", "b_tree_copy_3h", "c_tree_copy_wh_3h", "c_tree_copy_wh_3h_exclusive",
                  "d_tree_copy_5h", "e_tree_copy_wh_5h", "e_tree_copy_wh_5h_exclusive"]:
            print(f"   {k:32s} {tpps[k]:.4f}", flush=True)
        print(f"   source share (c 3h) tree/copy/wh = " + "/".join(f"{x:.3f}" for x in r["source_share_c_3h"]), flush=True)
        print(f"   source share (e 5h) tree/copy/wh = " + "/".join(f"{x:.3f}" for x in r["source_share_e_5h"]), flush=True)

    results["meta"]["wall_seconds"] = time.perf_counter() - t0
    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    Path(args.out).write_text(json.dumps(results, indent=1))
    print(f"wordhead cap-hit share {results['meta']['wordhead_cap_hit_share']:.3f} | {results['meta']['wall_seconds']:.0f}s", flush=True)


if __name__ == "__main__":
    main()