File size: 8,842 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 222 223 224 225 226 227 228 229 230 231 | """Held-out evaluation: BPB, per-head accuracy, speculative acceptance, boundary completion.
Bits-per-byte rather than per-token loss is what makes conditions with
different tokenizers comparable: a token is a different amount of text in
each condition, but a byte is not. D = BPB(MTP head 1) - BPB(NTP) is a
within-condition difference over identical text, so it is unaffected by
that normalization either way.
"""
import math
from dataclasses import dataclass
import torch
import torch.nn.functional as F
from src.train.model import MTPStack
BITS_PER_NAT = 1.0 / math.log(2.0)
def word_start_flags(text: str, offsets: list) -> list:
"""Per token, whether it begins a new word rather than continuing one.
A token begins a word if its span opens the text, opens with whitespace
(byte-pair vocabularies attach the leading space to the word-initial
token), or is immediately preceded by whitespace.
Args:
text: the original string the offsets index into.
offsets: (start, end) character offsets per token.
"""
flags = []
for start, end in offsets:
if start >= end: # zero-width special token
flags.append(False)
elif start == 0:
flags.append(True)
elif text[start].isspace() or text[start - 1].isspace():
flags.append(True)
else:
flags.append(False)
return flags
def bits_per_byte(total_nats: float, total_bytes: int) -> float:
"""Convert a summed cross-entropy in nats into bits per UTF-8 byte.
Args:
total_nats: summed negative log-likelihood over every predicted token.
total_bytes: UTF-8 byte length of the text those predictions cover.
"""
if total_bytes <= 0:
raise ValueError("total_bytes must be positive")
return total_nats * BITS_PER_NAT / total_bytes
@dataclass
class HeldOutStats:
"""Held-out results for one stack.
Attributes:
bpb: bits per byte from the offset-1 head.
head_accuracy: overall top-1 accuracy per head.
head_accuracy_intraword: accuracy restricted to targets continuing a word.
head_accuracy_boundary: accuracy restricted to targets starting a word.
n_tokens: predicted tokens scored.
n_bytes: UTF-8 bytes covered.
"""
bpb: float
head_accuracy: list
head_accuracy_intraword: list
head_accuracy_boundary: list
n_tokens: int
n_bytes: int
@torch.no_grad()
def evaluate_stack(backbone, stack: MTPStack, tokenizer, texts: list, device: str, max_tokens_per_doc: int) -> HeldOutStats:
"""Score held-out documents for BPB and per-head accuracy, split by word boundary.
Each document is tokenized independently (so offsets, and therefore the
boundary split, stay meaningful) and truncated to max_tokens_per_doc.
"""
total_nats = 0.0
total_bytes = 0
n_scored = 0
n_heads = stack.n_heads
correct = [0] * n_heads
seen = [0] * n_heads
correct_intra = [0] * n_heads
seen_intra = [0] * n_heads
correct_bound = [0] * n_heads
seen_bound = [0] * n_heads
for text in texts:
enc = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True, truncation=True, max_length=max_tokens_per_doc)
ids = enc.input_ids
if len(ids) < n_heads + 2:
continue
offsets = enc.offset_mapping
starts = word_start_flags(text, offsets)
block = torch.tensor([ids], dtype=torch.long, device=device)
hidden = backbone.model(input_ids=block).last_hidden_state
trunk = stack.trunk_states(hidden)
covered_end = offsets[len(ids) - 1][1]
covered_start = offsets[1][0]
total_bytes += len(text[covered_start:covered_end].encode("utf-8"))
for k in range(n_heads):
offset = k + 1
logits = stack.head_logits(trunk, k)[:, : len(ids) - offset, :]
targets = block[:, offset:]
if k == 0:
total_nats += float(F.cross_entropy(logits.reshape(-1, logits.shape[-1]), targets.reshape(-1), reduction="sum"))
n_scored += targets.numel()
preds = logits.argmax(dim=-1)[0]
tgt = targets[0]
hits = (preds == tgt)
correct[k] += int(hits.sum())
seen[k] += int(hits.numel())
target_is_start = torch.tensor(starts[offset : offset + hits.numel()], device=device, dtype=torch.bool)
correct_bound[k] += int((hits & target_is_start).sum())
seen_bound[k] += int(target_is_start.sum())
correct_intra[k] += int((hits & ~target_is_start).sum())
seen_intra[k] += int((~target_is_start).sum())
del logits, preds
def ratios(c: list, s: list) -> list:
return [c[i] / s[i] if s[i] else float("nan") for i in range(len(c))]
return HeldOutStats(
bpb=bits_per_byte(total_nats, total_bytes),
head_accuracy=ratios(correct, seen),
head_accuracy_intraword=ratios(correct_intra, seen_intra),
head_accuracy_boundary=ratios(correct_bound, seen_bound),
n_tokens=n_scored,
n_bytes=total_bytes,
)
@dataclass
class SpeculativeStats:
"""Blockwise greedy speculative decoding results.
Attributes:
mean_accepted_per_forward: mean tokens committed per verification pass,
counting the base model's own correction token (so the floor is 1.0).
boundary_completion_rate: fraction of committed spans that end at a word
boundary rather than mid-word.
n_rounds: verification passes measured.
n_spans_scored: spans with a successor round available to classify them.
"""
mean_accepted_per_forward: float
boundary_completion_rate: float
n_rounds: int
n_spans_scored: int
@torch.no_grad()
def speculative_decode(
backbone, stack: MTPStack, tokenizer, texts: list, device: str, prompt_tokens: int, completion_tokens: int
) -> SpeculativeStats:
"""Greedy blockwise speculative decoding, drafting with the heads and verifying
against the frozen backbone.
Each round drafts stack.n_heads tokens from one hidden state, then a single
verification pass over the prompt plus the draft yields the backbone's own
greedy tokens; the longest matching draft prefix is committed along with the
backbone's next token. Tokens committed per round is therefore
(accepted drafts + 1), and one round costs one verification pass.
A committed span is scored as boundary-completing when the first token of
the following round begins a new word, which is exactly the question of
whether the span stopped at a word edge. The final round of each document
has no successor and is left unscored rather than guessed.
"""
n_heads = stack.n_heads
total_committed = 0
n_rounds = 0
n_boundary = 0
n_spans = 0
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
pending_span_index = None
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[:-1]], dtype=torch.long, device=seq.device)], dim=1)
base_logits = backbone(input_ids=probe).logits[0, seq.shape[1] - 1 :, :]
base_greedy = base_logits.argmax(dim=-1).tolist()
n_accepted = 0
for i in range(n_heads):
if i < len(base_greedy) and drafts[i] == base_greedy[i]:
n_accepted += 1
else:
break
committed = drafts[:n_accepted] + [base_greedy[min(n_accepted, len(base_greedy) - 1)]]
if pending_span_index is not None:
first_id = committed[0]
piece = tokenizer.decode([first_id])
if piece[:1].isspace() or piece[:1] == "":
n_boundary += 1
n_spans += 1
pending_span_index = n_rounds
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 SpeculativeStats(
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,
)
|