code-switch-mtp / src /models /heads.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
2.3 kB
"""Medusa-1 style multi-token-prediction heads on a frozen backbone.
Each head is a single residual block feeding the backbone's own frozen
unembedding matrix. The unembedding is shared across all heads so that
adding heads costs one ResBlock (~hidden_size**2 params) rather than a
full vocab-sized output matrix per head.
"""
import torch
import torch.nn as nn
HIDDEN_INIT_ZERO = True # ResBlock starts as identity; head begins as a copy of NTP
class ResBlock(nn.Module):
"""Hidden-to-hidden residual block: x -> x + SiLU(Linear(x)).
Args:
hidden_size: dimensionality of the backbone's hidden state.
"""
def __init__(self, hidden_size: int) -> None:
super().__init__()
self.linear = nn.Linear(hidden_size, hidden_size)
self.act = nn.SiLU()
if HIDDEN_INIT_ZERO:
# zero-init so the block starts as an identity map; the head's
# initial predictions match the frozen backbone's own NTP logits
nn.init.zeros_(self.linear.weight)
nn.init.zeros_(self.linear.bias)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: (..., hidden_size) -> (..., hidden_size)."""
return x + self.act(self.linear(x))
class MTPHead(nn.Module):
"""One multi-token-prediction head: ResBlock followed by a shared unembedding.
Args:
hidden_size: backbone hidden dimensionality.
unembedding: frozen module mapping hidden_size -> vocab_size (typically
the backbone's own lm_head). Shared by reference across all heads
for a given condition; this module does not own or train it, so
callers must exclude its parameters from any optimizer.
"""
def __init__(self, hidden_size: int, unembedding: nn.Module) -> None:
super().__init__()
self.resblock = ResBlock(hidden_size)
self.unembedding = unembedding
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""hidden_states: (batch, seq, hidden_size) -> logits (batch, seq, vocab_size)."""
return self.unembedding(self.resblock(hidden_states))
def trainable_parameters(self):
"""Parameters to hand to an optimizer: the ResBlock only, never the shared unembedding."""
return self.resblock.parameters()