File size: 2,302 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
"""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()