code-switch-mtp / src /train /model.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
2.78 kB
"""Multi-token-prediction and next-token-prediction stacks over a frozen backbone.
The backbone is frozen, so the only trainable capacity is what sits between
its hidden states and the (also frozen) unembedding. That placement is not
cosmetic: with independent per-head ResBlocks and nothing shared, head 1's
loss term is the only term containing head 1's parameters, so its gradients
are bit-identical to a standalone next-token head's and D = BPB(MTP) -
BPB(NTP) is exactly zero by construction, whatever the data. Multi-token
prediction only has a cost to measure when the k objectives compete for
shared capacity -- "a shared trunk with k parallel heads" -- so the trunk
here is a trainable adapter that every head reads through.
USE_SHARED_TRUNK=False reproduces the no-shared-capacity arrangement and is
retained to demonstrate that degenerate case empirically rather than only
assert it.
"""
import torch
import torch.nn as nn
from src.models.heads import MTPHead, ResBlock
class MTPStack(nn.Module):
"""Trainable shared trunk feeding n_heads parallel heads over a frozen unembedding.
Head k (0-indexed) predicts the token at offset k+1 from the position
whose hidden state it reads.
Args:
hidden_size: backbone hidden dimensionality.
unembedding: the backbone's frozen lm_head, shared by every head and
never handed to an optimizer.
n_heads: number of prediction heads (1 gives the NTP control).
use_shared_trunk: if False, the trunk is an identity map with no
parameters, which removes all shared capacity between heads.
"""
def __init__(self, hidden_size: int, unembedding: nn.Module, n_heads: int, use_shared_trunk: bool = True) -> None:
super().__init__()
self.n_heads = n_heads
self.use_shared_trunk = use_shared_trunk
self.trunk = ResBlock(hidden_size) if use_shared_trunk else nn.Identity()
self.heads = nn.ModuleList([MTPHead(hidden_size, unembedding) for _ in range(n_heads)])
def trunk_states(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""hidden_states: (batch, seq, hidden) -> trunk output of the same shape."""
return self.trunk(hidden_states)
def head_logits(self, trunk_states: torch.Tensor, head_index: int) -> torch.Tensor:
"""trunk_states: (batch, seq, hidden) -> logits (batch, seq, vocab) for one head."""
return self.heads[head_index](trunk_states)
def trainable_parameters(self) -> list:
"""Trunk plus every head's ResBlock; never the shared frozen unembedding."""
params = list(self.trunk.parameters()) if self.use_shared_trunk else []
for head in self.heads:
params += list(head.trainable_parameters())
return params