File size: 14,804 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
"""Phase 5: does the make-up or the size of the draft shortlist matter, in particular at Hindi-English switches?

The draft heads are trained against the full vocabulary. At decoding time the
draft token is the best-scoring token of a shortlist: the 256 most frequent
successors of the previous token plus the 4,096 most frequent training tokens
(phase5_shortlist_pilot.py). A list ranked by frequency in Hindi text holds
few Latin-script tokens, so it could starve English words. This script
compares, on the same trained heads and with no retraining:

  full                    full vocabulary
  succ256+freq4096        the list used so far (4,352 candidates)
  succ256+balanced4096    successors plus 2,816 Devanagari, 1,024 Latin and 256 other tokens, each by frequency
  freq4352                frequency list alone, no successors
  balanced4352            3,072 Devanagari + 1,024 Latin + 256 other, no successors
  succ256+freq7936        a list twice as large (8,192 candidates)

and reports, per list: tokens per pass on the frozen model's continuations
(what lossless decoding accepts); how often the token to be drafted is in
the list, by script; the first draft at Hindi-English switch positions of the
real held-out text (same positions as phase5_switch_points.py); the time to
draft three tokens; and end-to-end decoding speed against greedy decoding.
"""

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

DEVICE = "cuda:0"
SCRIPTS = ("other", "devanagari", "latin")
CHUNK = 128


@torch.no_grad()
def main() -> None:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--name", default="Devanagari")
    p.add_argument("--ckpt-root", required=True, help="directory holding {name}_seed{s}/{arm}.pt")
    p.add_argument("--arm", default="dependent_teacher")
    p.add_argument("--seeds", default="0,1,2")
    p.add_argument("--train-ids", required=True)
    p.add_argument("--heldout", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--spec-docs", type=int, default=256)
    p.add_argument("--switch-docs", type=int, default=512)
    p.add_argument("--timing-docs", type=int, default=48)
    args = p.parse_args()
    t0 = time.perf_counter()

    from transformers import AutoModelForCausalLM, AutoTokenizer
    import phase4_boundary_decoding as pb
    import phase5_word_groups as wg
    from phase5_calibrated_tree import vocab_tables
    from phase5_decode_timing import drafted, greedy
    from phase5_dependent_eval import BACKBONE, load_arm, replay
    from phase5_shortlist_pilot import ShortlistDrafter, successor_table
    from phase5_switch_points import BUCKETS, bucket_of_tokens, interval
    from phase5_tree_draft import head_features
    from src.train.data import load_heldout_texts

    tok = AutoTokenizer.from_pretrained(BACKBONE)
    backbone = AutoModelForCausalLM.from_pretrained(BACKBONE, dtype=torch.float32).to(DEVICE).eval()
    vocab = backbone.config.vocab_size
    starts = pb.word_start_table(tok)
    is_start = starts + [False] * (vocab - len(starts))
    script, _ = vocab_tables(tok, vocab)
    script_t = torch.from_numpy(script).to(DEVICE)
    train_ids = np.load(args.train_ids)
    succ, freq_rank = successor_table(train_ids, vocab)
    counts = np.bincount(train_ids.astype(np.int64), minlength=vocab)
    freq = freq_rank.cpu().numpy()
    by_script = [freq[script[freq] == s] for s in range(3)]  # each in frequency order

    def balanced(n_dev: int, n_lat: int, n_other: int) -> np.ndarray:
        return np.concatenate([by_script[1][:n_dev], by_script[2][:n_lat], by_script[0][:n_other]])

    lists = {
        "full": (0, None),
        "succ256+freq4096": (256, freq[:4096]),
        "succ256+balanced4096": (256, balanced(2816, 1024, 256)),
        "freq4352": (0, freq[:4352]),
        "balanced4352": (0, balanced(3072, 1024, 256)),
        "succ256+freq7936": (256, freq[:7936]),
    }
    makeup = {}
    for name, (n_succ, ids) in lists.items():
        if ids is not None:
            makeup[name] = {"successors": n_succ, "static": int(len(ids)),
                            **{f"static_{SCRIPTS[s]}": int((script[ids] == s).sum()) for s in range(3)},
                            "static_tokens_never_seen_in_training": int((counts[ids] == 0).sum()),
                            "share_of_training_tokens_in_static_list": float(counts[ids].sum() / counts.sum())}
    member = {name: torch.zeros(vocab, dtype=torch.bool, device=DEVICE).index_fill_(0, torch.from_numpy(ids).to(DEVICE), True)
              for name, (_, ids) in lists.items() if ids is not None}
    rank = {name: torch.from_numpy(np.ascontiguousarray(ids)).to(DEVICE) for name, (_, ids) in lists.items() if ids is not None}

    def covered(name: str, prev: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        n_succ = lists[name][0]
        c = member[name][target]
        if n_succ:
            c = c | (succ[prev, :n_succ] == target[:, None]).any(1)
        return c

    eos = backbone.generation_config.eos_token_id
    eos_ids = set(eos if isinstance(eos, list) else [eos])
    texts = load_heldout_texts(args.heldout)
    pairs = pb.generate_continuations(backbone, tok, texts[: args.spec_docs], 256, 64 + pb.LOOKAHEAD, 16, eos_ids)
    pairs = [(pr, c) for pr, c in pairs if min(64, len(c) - pb.LOOKAHEAD + 1) >= 1]
    fwords = wg.function_words(args.name)
    is_start_np = np.array(is_start)
    switch_docs = []
    for text in texts[: args.switch_docs]:
        ids = tok(text, add_special_tokens=False, truncation=True, max_length=512).input_ids
        if len(ids) < 8:
            continue
        hidden = backbone.model(input_ids=torch.tensor([ids], device=DEVICE)).last_hidden_state[0]
        switch_docs.append({"ids": torch.tensor(ids, device=DEVICE), "hidden": hidden.cpu(), "choice": backbone.lm_head(hidden).argmax(-1),
                            "labels": np.array([b or "" for b in bucket_of_tokens(ids, is_start_np, tok, fwords, None)[2:]])})
    print(f"{args.name}: {len(pairs)} continuation docs, {len(switch_docs)} real-text docs, {time.perf_counter() - t0:.0f}s", flush=True)

    seeds = args.seeds.split(",")
    names = list(lists)
    per_seed_tpp = {n: [] for n in names}
    # continuations: first-draft target by script: (in list, draft right, positions), pooled over seeds
    cont_script = {n: np.zeros((3, 3)) for n in names}
    metrics = ("text_token_in_list", "draft_is_text", "draft_is_backbone_choice")
    sw = {n: {b: {m: np.zeros((len(switch_docs), 2)) for m in metrics} for b in BUCKETS} for n in names}
    timing = {}
    for seed in seeds:
        stack = load_arm(backbone, Path(args.ckpt_root) / f"{args.name}_seed{seed}" / f"{args.arm}.pt", args.arm.startswith("dependent"))
        drafters = {n: ShortlistDrafter(stack, backbone.lm_head.weight, succ, rank[n] if n in rank else freq_rank) for n in names}
        size = {n: (lists[n][0], 0 if lists[n][1] is None else len(lists[n][1])) for n in names}
        tot = {n: [0, 0] for n in names}
        for prompt, cont in pairs:
            horizon = min(64, len(cont) - pb.LOOKAHEAD + 1)
            full = torch.tensor([prompt + cont], device=DEVICE)
            p0 = len(prompt) - 1
            trunk = stack.trunk_states(backbone.model(input_ids=full).last_hidden_state[0, p0 : p0 + horizon])
            continuation = [prompt[-1]] + cont
            exact_next = torch.tensor(continuation[1 : horizon + 1], device=DEVICE)
            target = torch.tensor(continuation[2 : horizon + 2], device=DEVICE)
            tscript = script_t[target]
            for n in names:
                drafts = drafters[n].draft(trunk, exact_next, *size[n])
                r = replay(drafts.tolist(), continuation, horizon, 2, is_start)
                tot[n][0] += r["committed"]
                tot[n][1] += r["rounds"]
                inlist = covered(n, exact_next, target) if n != "full" else torch.ones_like(target, dtype=torch.bool)
                right = drafts[:, 0] == target
                for s in range(3):
                    sel = tscript == s
                    cont_script[n][s] += [int((inlist & sel).sum()), int((right & sel).sum()), int(sel.sum())]
        for n in names:
            per_seed_tpp[n].append(tot[n][0] / tot[n][1])

        for d, doc in enumerate(switch_docs):
            ids, m = doc["ids"], len(doc["ids"])
            trunk = stack.trunk_states(doc["hidden"][: m - 2].to(DEVICE))  # position t drafts ids[t + 2] given ids[t + 1]
            prev, target, choice = ids[1 : m - 1], ids[2:], doc["choice"][1 : m - 1]
            feat = head_features(stack, trunk, 1, [prev])
            for n in names:
                pick = torch.cat([drafters[n].pick(feat[s : s + CHUNK], prev[s : s + CHUNK], *size[n]) for s in range(0, m - 2, CHUNK)])
                inlist = covered(n, prev, target) if n != "full" else torch.ones_like(target, dtype=torch.bool)
                vals = {"text_token_in_list": inlist.cpu().numpy(), "draft_is_text": (pick == target).cpu().numpy(),
                        "draft_is_backbone_choice": (pick == choice).cpu().numpy()}
                for b in BUCKETS:
                    sel = doc["labels"] == b
                    if sel.any():
                        for k in metrics:
                            sw[n][b][k][d] += [vals[k][sel].sum(), sel.sum()]

        if not timing:  # speed on the first seed only; needs a GPU with nothing else running
            trunk1, next1 = trunk[:1], prev[:1]

            def timed(fn, reps: int = 50) -> float:
                fn()
                torch.cuda.synchronize()
                t = time.perf_counter()
                for _ in range(reps):
                    fn()
                torch.cuda.synchronize()
                return 1000 * (time.perf_counter() - t) / reps

            prompts = []
            for text in texts:
                ids = tok(text, add_special_tokens=False, truncation=True, max_length=256).input_ids
                if len(ids) >= 256:
                    prompts.append(ids)
                if len(prompts) >= args.timing_docs:
                    break
            greedy(backbone, prompts[0], 8)
            for n in names:
                drafted(backbone, drafters[n], prompts[0], 8, *size[n])
            base = [0.0, 0]
            stats = {n: {"seconds": 0.0, "committed": 0, "passes": 0, "identical_docs": 0} for n in names}
            for prompt in prompts:
                ref, _, sec = greedy(backbone, prompt, 64)
                base[0] += sec
                base[1] += len(ref)
                for n in names:
                    gen, passes, sec, committed = drafted(backbone, drafters[n], prompt, 64, *size[n])
                    s = stats[n]
                    s["seconds"] += sec
                    s["committed"] += committed
                    s["passes"] += passes
                    s["identical_docs"] += int(gen == ref)
            base_tps = base[1] / base[0]
            timing = {"seed": seed, "docs": len(prompts), "new_tokens": 64, "greedy_tokens_per_second": base_tps, "lists": {}}
            for n in names:
                s = stats[n]
                tps = s["committed"] / s["seconds"]
                timing["lists"][n] = {"draft_3_tokens_ms": timed(lambda: drafters[n].draft(trunk1, next1, *size[n])),
                                      "tokens_per_second": tps, "speedup_over_greedy": tps / base_tps,
                                      "ms_per_pass": 1000 * s["seconds"] / s["passes"], "tokens_per_pass": s["committed"] / s["passes"],
                                      "identical_docs": s["identical_docs"]}
        del stack, drafters
        print(f"{args.name}: seed {seed} done, {time.perf_counter() - t0:.0f}s", flush=True)

    res = {"name": args.name, "arm": args.arm, "seeds": args.seeds, "gpu": torch.cuda.get_device_name(DEVICE),
           "continuation_docs": len(pairs), "real_text_docs": len(switch_docs), "list_makeup": makeup, "lists": {}, "timing": timing}
    for n in names:
        c = cont_script[n]
        res["lists"][n] = {
            "tokens_per_pass_by_seed": per_seed_tpp[n], "tokens_per_pass_mean": float(np.mean(per_seed_tpp[n])),
            "continuations_first_draft_by_script_of_target": {
                SCRIPTS[s]: {"positions": int(c[s, 2] / len(seeds)), "target_in_list": float(c[s, 0] / max(1, c[s, 2])), "draft_right": float(c[s, 1] / max(1, c[s, 2]))}
                for s in range(3)},
            "continuations_target_in_list": float(c[:, 0].sum() / c[:, 2].sum()),
            "real_text_by_position": {
                b: {"positions": int(sw[n][b][metrics[0]][:, 1].sum() / len(seeds)), **{k: interval(sw[n][b][k]) for k in metrics}} for b in BUCKETS},
        }
    res["wall_seconds"] = time.perf_counter() - t0
    res["peak_gpu_mib"] = torch.cuda.max_memory_allocated(DEVICE) / 2**20
    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    Path(args.out).write_text(json.dumps(res, indent=1))
    for n, mk in makeup.items():
        print(f"  {n:22s} static {mk['static']} = {mk['static_devanagari']} Devanagari + {mk['static_latin']} Latin + {mk['static_other']} other; "
              f"never seen {mk['static_tokens_never_seen_in_training']}; covers {100 * mk['share_of_training_tokens_in_static_list']:.2f}% of training tokens", flush=True)
    for n in names:
        r, tm = res["lists"][n], timing["lists"][n]
        cs = r["continuations_first_draft_by_script_of_target"]
        print(f"  {n:22s} tokens/pass {r['tokens_per_pass_mean']:.3f} {[round(v, 3) for v in r['tokens_per_pass_by_seed']]}  target in list {r['continuations_target_in_list']:.4f} "
              f"(Latin targets {cs['latin']['target_in_list']:.3f}, n={cs['latin']['positions']})  draft 3 tokens {tm['draft_3_tokens_ms']:.2f} ms  "
              f"{tm['tokens_per_second']:.1f} tokens/s  {tm['speedup_over_greedy']:.2f}x  {tm['ms_per_pass']:.2f} ms/pass  identical {tm['identical_docs']}/{timing['docs']}", flush=True)
    for b in ("enter_english", "inside_english", "return_hindi_function", "return_hindi_content", "hindi_group_start"):
        print(f"  {b}", flush=True)
        for n in names:
            o = res["lists"][n]["real_text_by_position"][b]
            print(f"    {n:22s} n={o['positions']:6d}  " + "  ".join(f"{k} {o[k][0]:.3f} [{o[k][1]:.3f}, {o[k][2]:.3f}]" for k in metrics), flush=True)
    print(f"{args.name}: greedy {timing['greedy_tokens_per_second']:.1f} tokens/s, {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True)


if __name__ == "__main__":
    main()