"""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, )