File size: 9,194 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
"""Phase 5: how long should the copied branch be, and should it end at a word-group boundary?

phase5_depth_copy.py spends 5 of the N verified tokens on the copied branch
whenever a suffix of at least two tokens occurred earlier in the context.
This script compares, at the same N and on the same documents (replay
against the frozen model's greedy continuation, three look-ahead heads):

  fixed 3, 5, 8       the copied branch has that many tokens and the tree
                      gets N minus that many nodes
  fixed 5, exact      as fixed 5, but slots the branch cannot fill (the
                      earlier occurrence is too close to the end of the
                      context) go back to the tree
  word group          the copied branch runs to the end of the current word
                      group: it stops before the first copied token after
                      the first that starts a new group (a content word),
                      at most 8 tokens; the tree gets the rest

Word groups come from the closed-class list of phase5_word_groups.py, read
off the copied tokens where they first occurred. Nothing is fitted.
"""

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

from phase5_copy_branch import MATCH_LENGTHS
from phase5_deep_tree import accepted_depth, beam_tree
from phase5_tree_draft import DEVICE, bootstrap_gain, replay

LOOKAHEAD = 7  # as in phase5_depth_copy.py, so that documents and scored positions are the same
MAX_COPY = 8
GATE = 2
DEPTH = 3
BUDGETS = (8, 16)
RULES = ("fixed_3", "fixed_5", "fixed_8", "fixed_5_exact", "word_group")


def earlier_occurrence(seq: list, end: int) -> tuple:
    """Position of the most recent earlier occurrence of the suffix ending at seq[end]; and the suffix length matched."""
    for m in MATCH_LENGTHS:
        if end - m + 1 < 0:
            continue
        key = seq[end - m + 1 : end + 1]
        for q in range(end - 1, m - 2, -1):
            if seq[q - m + 1 : q + 1] == key:
                return q, m
    return -1, 0


@torch.no_grad()
def main() -> None:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--name", required=True)
    p.add_argument("--scheme", default="", help="Devanagari, ITRANS, IAST or ISO; empty for English (every word is its own group)")
    p.add_argument("--ckpt-root", required=True, help="directory holding {name}_seed{s}/{arm}.pt with three look-ahead heads")
    p.add_argument("--arm", default="dependent_teacher")
    p.add_argument("--seeds", default="0")
    p.add_argument("--heldout", required=True)
    p.add_argument("--spec-docs", type=int, default=256)
    p.add_argument("--out", required=True)
    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_dependent_eval import BACKBONE, load_arm
    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
    is_start, _, _ = wg.prefix_tables(tok, backbone.config.vocab_size)
    fwords = wg.function_words(args.scheme) if args.scheme else set()
    eos = backbone.generation_config.eos_token_id
    eos_ids = set(eos if isinstance(eos, list) else [eos])
    texts = load_heldout_texts(args.heldout)
    extra = MAX_COPY - 5  # tokens generated beyond what phase5_depth_copy.py generates, to score a branch of 8
    pairs = pb.generate_continuations(backbone, tok, texts[: args.spec_docs], 256, 64 + LOOKAHEAD + extra, 16, eos_ids)
    pairs = [(pr, c) for pr, c in pairs if min(64, len(c[: 64 + LOOKAHEAD]) - LOOKAHEAD + 1) >= 1]
    docs, lengths = [], {r: [] for r in RULES}
    for prompt, cont in pairs[1::2]:
        horizon = min(64, len(cont[: 64 + LOOKAHEAD]) - LOOKAHEAD + 1)
        seq = prompt + cont
        p0 = len(prompt) - 1
        classes = wg.token_classes(seq, is_start, tok, fwords)
        match, gate, span = np.zeros(horizon, dtype=np.int64), np.zeros(horizon, dtype=bool), {r: np.zeros(horizon, dtype=np.int64) for r in RULES}
        for j in range(horizon):
            end = p0 + 1 + j
            q, m = earlier_occurrence(seq, end)
            branch = seq[q + 1 : min(q + 1 + MAX_COPY, end + 1)] if m else []
            if m < GATE or not branch:
                continue
            gate[j] = True
            truth = seq[end + 1 : end + 1 + MAX_COPY]
            match[j] = int(np.cumprod([a == b for a, b in zip(branch, truth)]).sum())
            later_starts = [i for i in range(1, len(branch)) if classes[q + 1 + i] == 2]
            span["word_group"][j] = later_starts[0] if later_starts else len(branch)
            span["fixed_5_exact"][j] = min(5, len(branch))
            for n in (3, 5, 8):
                span[f"fixed_{n}"][j] = n
        docs.append({"seq": seq, "p0": p0, "horizon": horizon, "match": match, "gate": gate, "span": span})
        for r in RULES:
            lengths[r].extend(span[r][gate].tolist())
    print(f"{args.name}: {len(docs)} test documents, copied branch opens at {np.mean(np.concatenate([d['gate'] for d in docs])):.3f} of positions, "
          f"mean length when open: " + "  ".join(f"{r} {np.mean(lengths[r]):.2f}" for r in RULES) + f", {time.perf_counter() - t0:.0f}s", flush=True)

    res = {"name": args.name, "arm": args.arm, "gpu": torch.cuda.get_device_name(DEVICE), "test_docs": len(docs), "rules": RULES,
           "mean_copied_length_when_open": {r: float(np.mean(lengths[r])) for r in RULES},
           "word_group_length_distribution": np.bincount(lengths["word_group"], minlength=MAX_COPY + 1).tolist(), "seeds": {}}
    pooled = {}
    for seed in args.seeds.split(","):
        stack = load_arm(backbone, Path(args.ckpt_root) / f"{args.name}_seed{seed}" / f"{args.arm}.pt", True, n_heads=DEPTH + 1)
        per = {f"tree_{n}": [] for n in BUDGETS} | {f"{r}_{n}": [] for r in RULES for n in BUDGETS}
        for d in docs:
            seq, p0, horizon = d["seq"], d["p0"], d["horizon"]
            trunk = stack.trunk_states(backbone.model(input_ids=torch.tensor([seq], device=DEVICE)).last_hidden_state[0, p0 : p0 + horizon])
            exact_next = torch.tensor(seq[p0 + 1 : p0 + 1 + horizon], device=DEVICE)
            truth = torch.tensor([seq[p0 + 2 + j : p0 + 2 + j + DEPTH] for j in range(horizon)], device=DEVICE)
            levels = beam_tree(stack, unembed, trunk, exact_next, truth, DEPTH, 24, torch.zeros(horizon, dtype=torch.long, device=DEVICE))
            by_budget = np.stack([accepted_depth(levels, b) if b else np.zeros(horizon, dtype=np.int64) for b in range(max(BUDGETS) + 1)])  # (budget, position)
            for n in BUDGETS:
                per[f"tree_{n}"].append(replay(by_budget[n]))
                for r in RULES:
                    span = np.minimum(d["span"][r], n)  # the branch never takes more than the whole budget
                    tree = by_budget[n - span, np.arange(horizon)]
                    per[f"{r}_{n}"].append(replay(np.where(d["gate"], np.maximum(tree, np.minimum(d["match"], span)), by_budget[n])))
        rows = {k: np.array(v, dtype=float) for k, v in per.items()}
        for k, v in rows.items():
            pooled.setdefault(k, []).append(v)
        del stack
        out = {"tokens_per_pass": {k: float(v[:, 0].sum() / v[:, 1].sum()) for k, v in rows.items()},
               "percent_gain_vs_fixed_5": {f"{r}_{n}": bootstrap_gain(rows[f"{r}_{n}"], rows[f"fixed_5_{n}"]) for r in RULES if r != "fixed_5" for n in BUDGETS},
               "per_document": {k: v.tolist() for k, v in rows.items()}}
        res["seeds"][seed] = out
        print(f"{args.name} seed {seed}: " + "  ".join(f"{k} {v:.3f}" for k, v in out["tokens_per_pass"].items()) + f"  {time.perf_counter() - t0:.0f}s", flush=True)
    cat = {k: np.concatenate(v) for k, v in pooled.items()}
    res["pooled"] = {"tokens_per_pass": {k: float(np.mean([x[:, 0].sum() / x[:, 1].sum() for x in v])) for k, v in pooled.items()},
                     "percent_gain_vs_fixed_5": {f"{r}_{n}": bootstrap_gain(cat[f"{r}_{n}"], cat[f"fixed_5_{n}"]) for r in RULES if r != "fixed_5" for n in BUDGETS}}
    print(f"{args.name}, seeds {args.seeds} pooled: " + "  ".join(f"{k} {v:.3f}" for k, v in res["pooled"]["tokens_per_pass"].items()), flush=True)
    for k, v in res["pooled"]["percent_gain_vs_fixed_5"].items():
        print(f"    {k:18s} vs fixed_5: {v[0]:+.2f}% [{v[1]:+.2f}, {v[2]:+.2f}]", flush=True)
    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))
    print(f"{args.name}: {res['wall_seconds']:.0f}s, peak {res['peak_gpu_mib']:.0f} MiB", flush=True)


if __name__ == "__main__":
    main()