File size: 9,776 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
"""Verified blockwise speculative decoding, run on saved Phase 4 pilot checkpoints.

src.train.evaluate.speculative_decode builds its verification probe from
only the first n_heads - 1 drafts. When every draft matches, it then
commits base_greedy[n_heads - 1] -- which is the last draft itself -- as
the base model's "bonus" token: an unverified duplicate that inflates
accepted tokens per pass and corrupts the continuation. Here the probe
holds all n_heads drafts, so the base model scores every draft and also
supplies a genuine bonus token after the last one: commit
drafts[:n_accepted] + [base_greedy[n_accepted]].

Besides tokens per verification pass and boundary completion, the loop
records acceptance per draft position split by whether the drafted token
begins a word, which is where the heads were expected to fail.
"""

import argparse
import csv
import logging
import os
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path

os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import torch
import yaml

from src.train.model import MTPStack

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logger = logging.getLogger("phase4-spec")

DEVICE = "cuda:0"  # the process is already restricted to one physical GPU by the caller


@dataclass
class VerifiedSpecStats:
    """Verified blockwise greedy speculative decoding results.

    Attributes:
        mean_accepted_per_forward: tokens committed per verification pass,
            counting the base model's own bonus token (floor 1.0, ceiling n_heads + 1).
        boundary_completion_rate: fraction of committed spans whose successor
            span opens a new word.
        n_rounds: verification passes measured.
        n_spans_scored: spans with a successor round available to classify them.
        reached_start / accepted_start: per draft position, drafts that begin
            a word which verification reached / accepted.
        reached_inner / accepted_inner: the same for drafts continuing a word.
    """

    mean_accepted_per_forward: float
    boundary_completion_rate: float
    n_rounds: int
    n_spans_scored: int
    reached_start: list = field(default_factory=list)
    accepted_start: list = field(default_factory=list)
    reached_inner: list = field(default_factory=list)
    accepted_inner: list = field(default_factory=list)


@torch.no_grad()
def speculative_decode_verified(
    backbone, stack: MTPStack, tokenizer, texts: list, device: str, prompt_tokens: int, completion_tokens: int,
    opens: torch.Tensor = None, closes: torch.Tensor = None,
) -> VerifiedSpecStats:
    """Greedy blockwise speculative decoding with every draft verified.

    Each round drafts stack.n_heads tokens from the last hidden state, then
    one pass over prompt + all drafts gives the backbone's greedy token at
    every draft position plus one beyond; the longest matching prefix is
    committed together with the backbone's token after it.

    opens / closes: optional vocabulary tables (piece opens / ends with
    whitespace) enabling the per-position word-start acceptance split.
    """
    n_heads = stack.n_heads
    total_committed = 0
    n_rounds = 0
    n_boundary = 0
    n_spans = 0
    reached_start = [0] * n_heads
    accepted_start = [0] * n_heads
    reached_inner = [0] * n_heads
    accepted_inner = [0] * n_heads

    for text in texts:
        ids = tokenizer(text, add_special_tokens=False, truncation=True, max_length=prompt_tokens).input_ids
        if len(ids) < prompt_tokens:
            continue
        seq = torch.tensor([ids], dtype=torch.long, device=device)

        produced = 0
        has_previous_span = False
        while produced < completion_tokens:
            hidden = backbone.model(input_ids=seq).last_hidden_state
            trunk = stack.trunk_states(hidden[:, -1:, :])
            drafts = [int(stack.head_logits(trunk, k)[0, -1].argmax()) for k in range(n_heads)]

            probe = torch.cat([seq, torch.tensor([drafts], dtype=torch.long, device=seq.device)], dim=1)
            base_greedy = backbone(input_ids=probe).logits[0, seq.shape[1] - 1 :, :].argmax(dim=-1).tolist()

            n_accepted = 0
            while n_accepted < n_heads and drafts[n_accepted] == base_greedy[n_accepted]:
                n_accepted += 1
            committed = drafts[:n_accepted] + [base_greedy[n_accepted]]

            if opens is not None:
                previous = int(seq[0, -1])
                for i in range(min(n_accepted + 1, n_heads)):
                    begins_word = bool(opens[drafts[i]]) or bool(closes[previous])
                    if begins_word:
                        reached_start[i] += 1
                        accepted_start[i] += int(i < n_accepted)
                    else:
                        reached_inner[i] += 1
                        accepted_inner[i] += int(i < n_accepted)
                    previous = drafts[i]

            if has_previous_span:
                piece = tokenizer.decode([committed[0]])
                if piece[:1].isspace() or piece[:1] == "":
                    n_boundary += 1
                n_spans += 1
            has_previous_span = True

            seq = torch.cat([seq, torch.tensor([committed], dtype=torch.long, device=seq.device)], dim=1)
            total_committed += len(committed)
            produced += len(committed)
            n_rounds += 1

    return VerifiedSpecStats(
        mean_accepted_per_forward=total_committed / n_rounds if n_rounds else 0.0,
        boundary_completion_rate=n_boundary / n_spans if n_spans else float("nan"),
        n_rounds=n_rounds,
        n_spans_scored=n_spans,
        reached_start=reached_start,
        accepted_start=accepted_start,
        reached_inner=reached_inner,
        accepted_inner=accepted_inner,
    )


def acceptance_rows(arm: str, spec: VerifiedSpecStats) -> list:
    """CSV rows (arm, metric, value, n) for one arm's verified decoding results."""
    rows = [
        [arm, "verified_tokens_per_verification_pass", f"{spec.mean_accepted_per_forward:.6f}", spec.n_rounds],
        [arm, "verified_boundary_completion_rate", f"{spec.boundary_completion_rate:.6f}", spec.n_spans_scored],
    ]
    for i in range(len(spec.reached_start)):
        for kind, reached, accepted in (("word_start", spec.reached_start, spec.accepted_start), ("inside_word", spec.reached_inner, spec.accepted_inner)):
            rate = accepted[i] / reached[i] if reached[i] else float("nan")
            rows.append([arm, f"draft{i + 1}_acceptance_{kind}", f"{rate:.6f}", reached[i]])
    return rows


def load_trainable_stack(path: str, backbone, n_heads: int) -> MTPStack:
    """Rebuild an MTPStack from a checkpoint holding only its trainable tensors."""
    stack = MTPStack(backbone.config.hidden_size, backbone.lm_head, n_heads, True).to(DEVICE)
    result = stack.load_state_dict(torch.load(path, map_location=DEVICE), strict=False)
    if result.unexpected_keys or any("unembedding" not in k for k in result.missing_keys):
        raise RuntimeError(f"checkpoint {path} does not match the stack: {result}")
    stack.eval()
    return stack


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--config", default="configs/phase3.yaml")
    p.add_argument("--condition", default="L2", choices=["L2", "L4", "E1"])
    p.add_argument("--checkpoint", required=True, help="trainable-only MTP stack checkpoint")
    p.add_argument("--arm", required=True, help="arm name written into the CSV")
    p.add_argument("--docs", type=int, default=64)
    p.add_argument("--out", required=True)
    return p.parse_args()


def main() -> None:
    from transformers import AutoModelForCausalLM, AutoTokenizer

    from scripts.phase4_boundary_weighted_train import build_whitespace_tables
    from src.train.data import load_heldout_texts

    args = parse_args()
    with open(args.config, encoding="utf-8") as f:
        cfg = yaml.safe_load(f)
    started = time.perf_counter()
    tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"])
    backbone = AutoModelForCausalLM.from_pretrained(cfg["backbone"]["hf_id"], dtype=torch.float32).to(DEVICE)
    backbone.eval()
    opens, closes = build_whitespace_tables(tokenizer, backbone.config.vocab_size)
    stack = load_trainable_stack(args.checkpoint, backbone, cfg["n_heads"])
    heldout = load_heldout_texts(str(Path(cfg["data_dir"]) / f"{args.condition}_heldout.jsonl"))

    spec_start = time.perf_counter()
    spec = speculative_decode_verified(
        backbone, stack, tokenizer, heldout[: args.docs], DEVICE, cfg["spec_prompt_tokens"], cfg["spec_completion_tokens"], opens, closes
    )
    spec_seconds = time.perf_counter() - spec_start
    logger.info("%s: %.4f tokens per verification pass over %d rounds (%.0fs)", args.arm, spec.mean_accepted_per_forward, spec.n_rounds, spec_seconds)

    rows = [["arm", "metric", "value", "n"]] + acceptance_rows(args.arm, spec)
    rows.append([args.arm, "spec_docs", args.docs, 1])
    rows.append([args.arm, "spec_seconds", f"{spec_seconds:.1f}", 1])
    rows.append([args.arm, "spec_wall_seconds", f"{time.perf_counter() - started:.1f}", 1])
    rows.append([args.arm, "spec_peak_gpu_mib", f"{torch.cuda.max_memory_allocated(DEVICE) / 1024**2:.1f}", 1])
    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    with open(args.out, "w", newline="", encoding="utf-8") as f:
        csv.writer(f).writerows(rows)
    logger.info("wrote %s", args.out)


if __name__ == "__main__":
    main()