"""Dependent draft heads: look-ahead heads that also read the tokens before their target. A vanilla MTP head k predicts x_{t+k} from the hidden state z_t alone, so the K heads together model a product of marginals and cannot express that the second draft depends on the first. Here head k additionally receives the (frozen) input embeddings of x_{t+1} .. x_{t+k-1}: h_k = trunk(z_t) + sum_{i=1}^{k-1} P_{k,i} * s * E[x_{t+i}] logits_k = U * ResBlock_k(h_k) P_{k,i} is a trainable hidden x hidden matrix, zero-initialised so the stack starts out identical to the independent one; s is a fixed scalar that brings embedding rows to the hidden states' scale. Head 1 (the next-token head) has no predecessor tokens and is unchanged, so held-out BPB of head 1 against an NTP control still measures negative transfer through the shared trunk. Training is teacher-forced (true previous tokens). When drafting, x_{t+1} is the backbone's own next token (exact under greedy decoding) and later predecessors are the drafts themselves. """ import torch import torch.nn as nn import torch.nn.functional as F from src.train.model import MTPStack WEIGHT_CLIP = 10.0 # cap on a normalised acceptance weight, bounds gradient variance class DependentStack(MTPStack): """MTPStack whose look-ahead heads condition on the preceding future tokens. Args: hidden_size: backbone hidden dimensionality. unembedding: frozen lm_head shared by every head. n_heads: number of heads; head index k predicts offset k+1. embedding: frozen input-embedding module of the backbone (not trained, not stored in checkpoints). embed_scale: scalar multiplying embedding rows before projection. """ def __init__(self, hidden_size: int, unembedding: nn.Module, n_heads: int, embedding: nn.Module, embed_scale: float) -> None: super().__init__(hidden_size, unembedding, n_heads, use_shared_trunk=True) self._frozen = (embedding,) # tuple so nn.Module does not register it self.register_buffer("embed_scale", torch.tensor(float(embed_scale))) # proj[k-1][i] maps the embedding of the token at offset i+1 into head k's input (k = 1 .. n_heads-1) self.proj = nn.ModuleList( [nn.ModuleList([nn.Linear(hidden_size, hidden_size, bias=False) for _ in range(k)]) for k in range(1, n_heads)] ) for group in self.proj: for lin in group: nn.init.zeros_(lin.weight) def embed(self, token_ids: torch.Tensor) -> torch.Tensor: """token_ids: (...) -> scaled frozen embeddings (..., hidden).""" with torch.no_grad(): return self._frozen[0](token_ids) * self.embed_scale def dependent_logits(self, trunk_states: torch.Tensor, head_index: int, prev_tokens: list) -> torch.Tensor: """Logits of head `head_index` given its predecessor tokens. Args: trunk_states: (..., hidden) trunk output at the positions being scored. head_index: 0-based head; needs head_index predecessor tensors. prev_tokens: prev_tokens[i] holds the token at offset i+1 for each position, shaped like trunk_states without the last dim. """ if head_index == 0: return self.heads[0](trunk_states) if len(prev_tokens) != head_index: raise ValueError(f"head {head_index} needs {head_index} predecessor tensors, got {len(prev_tokens)}") h = trunk_states for i, tokens in enumerate(prev_tokens): h = h + self.proj[head_index - 1][i](self.embed(tokens)) return self.heads[head_index](h) def trainable_parameters(self) -> list: return super().trainable_parameters() + list(self.proj.parameters()) N_PREFIX_FEATURES = 8 # 4 word-position classes + 3 scripts + 1 whitespace flag class PrefixFeatureStack(DependentStack): """DependentStack whose look-ahead heads also read explicit features of the prefix they extend. The prefix of look-ahead head k ends at the token at offset k (the exact next token, or a draft). Three things about that token are known when drafting and are added to the head's input through a zero-initialised linear map F_k: position of the token inside its whitespace word (0, 1, 2, 3 or more), script of the token (other, Devanagari, Latin), whether the token ends in whitespace. The position is carried forward from the context: `since_start` is the number of tokens since the last word start at the context token, and each predecessor either starts a word (position 0) or adds one. The same function is used with true predecessors in training and with drafted ones when decoding. Args (beyond DependentStack): is_start, script, ends_space: (vocab,) per-token tables: the token starts a word; its script id 0/1/2; its text ends in whitespace. """ def __init__(self, hidden_size: int, unembedding: nn.Module, n_heads: int, embedding: nn.Module, embed_scale: float, is_start: torch.Tensor, script: torch.Tensor, ends_space: torch.Tensor) -> None: super().__init__(hidden_size, unembedding, n_heads, embedding, embed_scale) self.register_buffer("tok_is_start", is_start.bool()) self.register_buffer("tok_script", script.long()) self.register_buffer("tok_ends_space", ends_space.bool()) self.feat_proj = nn.ModuleList([nn.Linear(N_PREFIX_FEATURES, hidden_size, bias=False) for _ in range(1, n_heads)]) for lin in self.feat_proj: nn.init.zeros_(lin.weight) def tokens_since_word_start(self, tokens: torch.Tensor) -> torch.Tensor: """tokens: (batch, seq) -> (batch, seq) tokens since the last word-start token, 0 at a word start. Before the first word start of a row the count runs from the row's start. """ idx = torch.arange(tokens.shape[1], device=tokens.device).expand_as(tokens) last = torch.where(self.tok_is_start[tokens], idx, torch.full_like(idx, -1)).cummax(1).values return idx - last def prefix_features(self, since_start: torch.Tensor, prev_tokens: list) -> torch.Tensor: """Features of the prefix that ends at prev_tokens[-1]; since_start is the count at the context token.""" pos = since_start for tokens in prev_tokens: pos = torch.where(self.tok_is_start[tokens], torch.zeros_like(pos), pos + 1) last = prev_tokens[-1] return torch.cat([F.one_hot(pos.clamp(max=3), 4), F.one_hot(self.tok_script[last], 3), self.tok_ends_space[last][..., None].long()], -1).float() def dependent_logits(self, trunk_states: torch.Tensor, head_index: int, prev_tokens: list, since_start: torch.Tensor = None) -> torch.Tensor: if head_index == 0: return self.heads[0](trunk_states) if since_start is None: raise ValueError("look-ahead heads of a PrefixFeatureStack need since_start") h = trunk_states + self.feat_proj[head_index - 1](self.prefix_features(since_start, prev_tokens)) for i, tokens in enumerate(prev_tokens): h = h + self.proj[head_index - 1][i](self.embed(tokens)) return self.heads[head_index](h) def trainable_parameters(self) -> list: return super().trainable_parameters() + list(self.feat_proj.parameters()) def teacher_forced_logits(stack: MTPStack, trunk: torch.Tensor, block: torch.Tensor, head_index: int) -> torch.Tensor: """Logits of one head at every position that has a target, with true predecessors if dependent. trunk: (batch, seq, hidden); block: (batch, seq) token ids. Returns (batch, seq - head_index - 1, vocab); position t predicts block[:, t + head_index + 1]. """ n = block.shape[1] - (head_index + 1) if isinstance(stack, DependentStack) and head_index > 0: prev = [block[:, i + 1 : i + 1 + n] for i in range(head_index)] if isinstance(stack, PrefixFeatureStack): return stack.dependent_logits(trunk[:, :n], head_index, prev, stack.tokens_since_word_start(block)[:, :n]) return stack.dependent_logits(trunk[:, :n], head_index, prev) return stack.head_logits(trunk[:, :n], head_index) def acceptance_weights(log_reach: torch.Tensor) -> torch.Tensor: """Per-position loss weights from the log-probability that earlier drafts are accepted. log_reach: (batch, n) detached sum of log p_i(x_{t+i}) over the draft heads before this one. Weights are normalised to mean 1 and clipped. """ w = torch.exp(log_reach) w = w / w.mean().clamp_min(1e-12) return w.clamp(max=WEIGHT_CLIP) def mtp_step(stack: MTPStack, optimizer: torch.optim.Optimizer, hidden: torch.Tensor, block: torch.Tensor, lookahead_weight: float, acceptance_weighted: bool, backbone_choice: torch.Tensor = None, target_weights: torch.Tensor = None) -> tuple: """One optimizer step on L_1 + lookahead_weight * sum_{k>=2} L_k. With acceptance_weighted, L_k (k >= 3) weights each position by the detached probability that draft heads 2 .. k-1 all put their mass on the true tokens, i.e. that draft k would be reached. Head 1 is excluded from the product because the first token of a round is the backbone's own. With backbone_choice (batch, seq), where backbone_choice[:, j] is the frozen backbone's argmax for position j + 1 given the true prefix, the look-ahead heads are trained to predict the backbone's choice instead of the text token. Drafts are verified against the backbone, so this is the quantity acceptance depends on. Head 1 always keeps the text target, and the predecessor tokens fed to dependent heads stay the true ones. With target_weights (batch, seq), the look-ahead heads weight the loss at each position by the weight of the text token being predicted there (weighted mean, so the loss scale does not change). Used to down- or up-weight targets by their linguistic position. Head 1 is never weighted. Returns (per-head mean losses, per-head correct counts, per-head position counts), measured before the update on a batch never seen before (single epoch) and against whichever target the head is trained on. """ optimizer.zero_grad(set_to_none=True) trunk = stack.trunk_states(hidden) losses, correct, counts = [], [], [] log_reach = None for k in range(stack.n_heads): logits = teacher_forced_logits(stack, trunk, block, k) target = block[:, k + 1 :] if (backbone_choice is None or k == 0) else backbone_choice[:, k:-1] nll = F.cross_entropy(logits.reshape(-1, logits.shape[-1]), target.reshape(-1), reduction="none").view_as(target) if acceptance_weighted and k >= 2: loss = (acceptance_weights(log_reach[:, : target.shape[1]]) * nll).mean() elif target_weights is not None and k >= 1: w = target_weights[:, k + 1 :] loss = (w * nll).sum() / w.sum().clamp_min(1e-12) else: loss = nll.mean() weight = 1.0 if k == 0 else lookahead_weight (weight * loss).backward(retain_graph=(k < stack.n_heads - 1)) with torch.no_grad(): losses.append(float(nll.mean())) correct.append(int((logits.argmax(-1) == target).sum())) counts.append(target.numel()) if k >= 1: step = -nll.detach() log_reach = step if log_reach is None else log_reach[:, : step.shape[1]] + step del logits, nll, loss optimizer.step() return losses, correct, counts