File size: 6,581 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
"""Phase 5: end-to-end lossless decoding with a key-value cache, timed.

Greedy decoding (one backbone pass per token) against draft-and-verify
decoding (one pass per round over the backbone's own next token plus three
drafts). Reports tokens per second for the decode phase after the prompt has
been encoded, tokens per pass, and whether the drafted output is identical
to the greedy output.
"""

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"
SHORTLIST = (256, 4096)  # successors of the previous token, most frequent tokens


@torch.no_grad()
def prefill(backbone, prompt: list):
    out = backbone.model(input_ids=torch.tensor([prompt], device=DEVICE), use_cache=True)
    z = out.last_hidden_state[0, -1]
    return out.past_key_values, z, backbone.lm_head(z).argmax(-1)


@torch.no_grad()
def greedy(backbone, prompt: list, n_new: int) -> tuple:
    past, _, nxt = prefill(backbone, prompt)
    torch.cuda.synchronize()
    t = time.perf_counter()
    gen, passes = [], 0
    while len(gen) < n_new:
        gen.append(nxt)
        out = backbone.model(input_ids=nxt.view(1, 1), past_key_values=past, use_cache=True)
        past = out.past_key_values
        nxt = backbone.lm_head(out.last_hidden_state[0, -1]).argmax(-1)
        passes += 1
    gen = torch.stack(gen).tolist()
    torch.cuda.synchronize()
    return gen, passes, time.perf_counter() - t


@torch.no_grad()
def drafted(backbone, drafter, prompt: list, n_new: int, n_succ: int, n_static: int) -> tuple:
    past, z, nxt = prefill(backbone, prompt)
    torch.cuda.synchronize()
    t = time.perf_counter()
    gen, passes, length = [], 0, len(prompt)
    while len(gen) < n_new:
        drafts = drafter.draft(drafter.stack.trunk_states(z[None]), nxt[None], n_succ, n_static)[0]
        inp = torch.cat([nxt.view(1), drafts])
        out = backbone.model(input_ids=inp[None], past_key_values=past, use_cache=True)
        hidden = out.last_hidden_state[0]
        preds = backbone.lm_head(hidden).argmax(-1)  # preds[i] = backbone's token after inp[i]
        n = int((drafts == preds[:-1]).long().cumprod(0).sum())  # accepted drafts
        gen.extend(inp[: n + 1].tolist())
        nxt, z = preds[n], hidden[n]
        length += n + 1
        past = out.past_key_values
        past.crop(length)
        passes += 1
    torch.cuda.synchronize()
    return gen[:n_new], passes, time.perf_counter() - t, len(gen)


def main() -> None:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--name", required=True)
    p.add_argument("--ckpt-dir", required=True)
    p.add_argument("--train-ids", required=True)
    p.add_argument("--heldout", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--arms", default="independent,dependent,dependent_teacher")
    p.add_argument("--docs", type=int, default=48)
    p.add_argument("--new-tokens", type=int, default=64)
    args = p.parse_args()

    from transformers import AutoModelForCausalLM, AutoTokenizer
    from phase5_dependent_eval import BACKBONE, load_arm
    from phase5_shortlist_pilot import ShortlistDrafter, successor_table
    from src.train.data import load_heldout_texts

    tok = AutoTokenizer.from_pretrained(BACKBONE)
    backbone = AutoModelForCausalLM.from_pretrained(BACKBONE, dtype=torch.float32).to(DEVICE).eval()
    succ, freq_rank = successor_table(np.load(args.train_ids), backbone.config.vocab_size)
    arms = [a for a in args.arms.split(",") if (Path(args.ckpt_dir) / f"{a}.pt").exists()]
    drafters = {a: ShortlistDrafter(load_arm(backbone, Path(args.ckpt_dir) / f"{a}.pt", a.startswith("dependent")),
                                    backbone.lm_head.weight, succ, freq_rank) for a in arms}
    prompts = []
    for text in load_heldout_texts(args.heldout):
        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.docs:
            break

    modes = [(f"{a}, {label}", a, cfg) for a in arms for label, cfg in (("full vocabulary", (0, 0)), ("shortlist", SHORTLIST))]
    stats = {m: {"seconds": 0.0, "tokens": 0, "committed": 0, "passes": 0, "identical_docs": 0, "token_match": 0} for m, _, _ in modes}
    base = {"seconds": 0.0, "tokens": 0, "passes": 0}
    greedy(backbone, prompts[0], 8)  # warm-up
    for m, a, cfg in modes:
        drafted(backbone, drafters[a], prompts[0], 8, *cfg)
    for prompt in prompts:
        ref, passes, sec = greedy(backbone, prompt, args.new_tokens)
        base["seconds"] += sec
        base["tokens"] += len(ref)
        base["passes"] += passes
        for m, a, cfg in modes:
            gen, passes, sec, committed = drafted(backbone, drafters[a], prompt, args.new_tokens, *cfg)
            s = stats[m]
            s["seconds"] += sec
            s["tokens"] += len(gen)
            s["committed"] += committed
            s["passes"] += passes
            s["identical_docs"] += int(gen == ref)
            s["token_match"] += sum(int(x == y) for x, y in zip(gen, ref))
    base_tps = base["tokens"] / base["seconds"]
    res = {"name": args.name, "docs": len(prompts), "new_tokens": args.new_tokens, "gpu": torch.cuda.get_device_name(DEVICE),
           "shortlist": {"successors": SHORTLIST[0], "most_frequent": SHORTLIST[1]},
           "greedy": {"tokens_per_second": base_tps, "ms_per_token": 1000 / base_tps}, "modes": {},
           "peak_gpu_mib": torch.cuda.max_memory_allocated(DEVICE) / 2**20}
    print(f"{args.name}: {len(prompts)} docs x {args.new_tokens} tokens on {res['gpu']}; greedy {base_tps:.1f} tokens/s")
    for m, s in stats.items():
        tps = s["committed"] / s["seconds"]
        res["modes"][m] = {"tokens_per_second": tps, "speedup": tps / base_tps, "tokens_per_pass": s["committed"] / s["passes"],
                           "identical_docs": s["identical_docs"], "token_match": s["token_match"] / s["tokens"]}
        print(f"  {m:36s} {tps:6.1f} tokens/s  {tps / base_tps:.2f}x  {s['committed'] / s['passes']:.3f} tokens/pass  "
              f"identical {s['identical_docs']}/{len(prompts)}  token match {s['token_match'] / s['tokens']:.4f}")
    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    Path(args.out).write_text(json.dumps(res, indent=1))


if __name__ == "__main__":
    main()