20.5 Multi-Token Prediction (MTP)
Multi-token prediction (MTP) adds training losses for additional future positions. The architectures below differ in which tokens each prediction can use. Next-token prediction (NTP) can already learn long-range dependencies; MTP does not uniquely make planning possible. The practical question is whether extra supervision improves representations and downstream behavior for a particular model, dataset and budget. [1] [2]
1. The Architectural Evolution
MTP is a training objective; its future predictions can also supply inference-time drafts. Evaluate these two uses separately. Auxiliary modules can be used during training and removed for ordinary inference.
Where each training target gets its context
Observed prefix x₁:ₜ causal decoder output head loss against xₜ₊₁
Parallel MTP: separate future offsets
Gloeckle et al. (2024) · three offsets shown
All three heads use the same prefix representation. A later-offset head does not receive an earlier head’s sampled token. Head blocks have separate parameters; Wᵤ is shared.
Sequential MTP: extend the training context
DeepSeek-V3 · first auxiliary depth shown
Emb and OutHead are shared with the main model. M₁ and TRM₁ belong to this auxiliary depth. Further depths repeat with the next ground-truth token; they are not successive layers of the main decoder.
Meta’s Parallel Heads (Gloeckle et al., 2024)
Meta FAIR’s reported architecture uses a shared causal Transformer trunk, separate Transformer heads, and one shared vocabulary projection [2]. Each head reads the trunk’s prefix representations and predicts its own future offset at position : . A later head does not receive an earlier head’s sampled token. Here, “parallel” describes the independent prediction paths; the paper schedules head computations sequentially during training to limit peak logit memory.
DeepSeek-V3’s Sequential Auxiliary Modules
DeepSeek-V3 uses sequential auxiliary modules, separate from the main model’s stack of decoder layers [1]. At the first auxiliary depth, it takes the main-model state at position and the embedding of the ground-truth token . It applies RMSNorm to each input, concatenates them, and uses a depth-specific projection and causal Transformer block. The resulting state predicts through the same output head as the main model. The token embedding is shared too; the auxiliary projection and Transformer block have their own parameters.
For an illustrative token sequence [A, B, C, D], the parallel heads at B predict C and D from [A, B]. DeepSeek’s first auxiliary module at that position also receives the observed C during training and predicts D. Seeing C is valid for this later target; the main next-token path must still predict C without seeing it. At inference, future ground-truth tokens are unavailable: using auxiliary modules for drafts is a separate choice that requires verification, as discussed below.
2. Mathematical Formulation and PyTorch Implementation
Let’s formalize the parallel MTP approach. In standard NTP, the cross-entropy loss at step is:
For predicted offsets, Gloeckle et al. sum the per-offset losses [2]. We write optional weights to make the educational code’s choice explicit; setting every gives the unweighted sum at position :
The educational variant below shares a vocabulary projection and uses an MLP projection for each future offset. It does not reproduce the paper’s head architecture or throughput results. Materializing all output logits also has a separate memory cost.
Educational heads and loss. This is not a reproduction of the paper’s Transformer heads or a complete trainer. It materializes logits, increasing memory with ; real implementations should bound this through sequential heads or fused loss. The backbone must use causal attention and isolate packed segments; the loss mask alone does not prevent attention leakage.
import torch
import torch.nn as nn
import torch.nn.functional as F
class ParallelMTPModule(nn.Module):
"""
Educational parallel MTP head sketch; not a paper reproduction.
"""
def __init__(self, d_model: int, vocab_size: int, num_future_tokens: int = 4):
super().__init__()
if num_future_tokens < 1:
raise ValueError("at least one prediction head required")
self.num_future_tokens = num_future_tokens
# Shared LM head for all predictions to conserve VRAM
self.shared_lm_head = nn.Linear(d_model, vocab_size, bias=False)
# MTP projection blocks (for k=2 to n)
# k=1 is the standard next-token prediction, handled directly by the trunk
self.mtp_projections = nn.ModuleList([
nn.Sequential(
nn.RMSNorm(d_model),
nn.Linear(d_model, d_model * 2, bias=False),
nn.SiLU(),
nn.Linear(d_model * 2, d_model, bias=False)
) for _ in range(num_future_tokens - 1)
])
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""
hidden_states: [batch_size, seq_len, d_model] from the main trunk
Returns: logits of shape [batch_size, num_future_tokens, seq_len, vocab_size]
"""
# 1. Standard next-token prediction (k=1)
logits_k1 = self.shared_lm_head(hidden_states) # [B, S, V]
all_logits = [logits_k1]
# 2. Future token predictions (k=2 to n)
for proj in self.mtp_projections:
# Project the trunk's hidden state for the k-th future token
# We use a residual connection to anchor the representation
z_k = proj(hidden_states) + hidden_states
logits_k = self.shared_lm_head(z_k)
all_logits.append(logits_k)
return torch.stack(all_logits, dim=1) # [B, n, S, V]
def compute_mtp_loss(logits, targets, loss_weights, response_mask, segment_ids):
# logits [B,n,S,V]; targets, response_mask, segment_ids [B,S].
# Segment IDs are unique contiguous conversation IDs within each row.
B, n, S, V = logits.shape
if targets.shape != (B,S) or response_mask.shape != (B,S) or segment_ids.shape != (B,S):
raise ValueError("target/mask/segment shape mismatch")
if len(loss_weights) != n or any(not 0 <= w < float("inf") for w in loss_weights):
raise ValueError("one finite nonnegative weight per head required")
total = torch.zeros((), device=logits.device, dtype=torch.float32)
used = False
for k in range(n):
shift = k + 1
if shift >= S or loss_weights[k] == 0:
continue
tgt = targets[:, shift:]
valid = response_mask[:, shift:].bool() & (tgt != -100)
valid &= (segment_ids[:, :-shift] == segment_ids[:, shift:])
valid &= segment_ids[:, shift:] >= 0
if not valid.any():
continue
# Each head averages over its valid target tokens; then weighted sum.
total = total + loss_weights[k] * F.cross_entropy(
logits[:, k, :-shift, :][valid].float(), tgt[valid])
used = True
if not used:
raise ValueError("no valid weighted future targets")
return total
The Target Alignment Challenge
Notice the shift = k + 1 logic in the loss function. In standard autoregressive training, the logits at index t are evaluated against the target at t+1. For the second MTP head (), the logits at index t are evaluated against the target at t+2. This shifting means that as increases, we lose valid training positions at the end of the sequence. For sequences of length 4096 and , this truncation is negligible, but it requires careful tensor slicing to avoid out-of-bounds errors.
3. Using the heads as inference drafts
Auxiliary heads can propose candidates without a separate draft model, but incur nonzero compute and memory. Shared representations do not guarantee acceptance. Parallel marginal predictions also differ from sequential predictions conditioned on earlier draft tokens.
Preserving the target distribution requires verification, correct acceptance/rejection sampling, and rollback of rejected KV/recurrent state. Compare with ordinary decoding at matched temperature, filters, output lengths and load, including drafting, verification and restoration costs.
Draft acceptance versus overhead
An illustrative exact speculative round drafts three tokens, accepts a prefix, then emits one correction/bonus token. The three-token MTP head layout is only one possible design.
4. Scale and task tradeoffs
Gloeckle et al. report coding gains at 13B, contradicting a rule that MTP only helps above 70B. [2] Small-model outcomes also depend on tasks and settings. Do not assume a fixed capacity threshold or an inevitable reasoning-versus-fact-retrieval tradeoff.
Compare against NTP with matched data and compute budgets. Ablate future offsets, loss weights, head architecture and training length. Track token-normalized loss by head, base-capability retention and held-out code, reasoning and knowledge slices.
5. Run contract and takeaway
Pin base/tokenizer/chat template and data manifests. For assistant-only adaptation, mask the future target position. Verify BOS/EOS, truncation, padding and variable-length reduction, and do not cross packed-conversation boundaries. Pretraining instead uses all targets admitted by its data policy. Explicitly record that this objective has no reference model if none is used.
Record future-head count/weights, optimizer/learning rate, batch and context length. Budget parameters, gradients, optimizer states, activations, temporary logits, collectives, checkpoints and evaluation with precision/sharding/recomputation assumptions. Observe token-normalized losses, valid target counts per head, nonfinite values, gradient/activation norms, throughput, MFU, data wait and stragglers with reconstructable batch IDs.
Predefine numerical and retention abort thresholds. Atomically save model including heads, optimizer, scheduler/scaler, RNG, sampler/exact data cursor and hashes, and rehearse restoration. Gate release on untouched domain, retention, safety, format/tool, latency, cost and error-rate evaluations with uncertainty. Retain the artifact bundle and rollback to a last-known-good version.
Additional supervision and native drafting can each be useful; establish training quality and serving speed through separate experiments.
Quizzes
Quiz 1: Why does MTP require shifting the target sequences differently for each projection head during loss computation?
Because each head predicts a token at a different future offset. The next-token head at position predicts , so we shift targets by 1. The first auxiliary head at position predicts , so we compare its output against targets shifted by 2. A wrong shift trains a different target relationship, even when tensor shapes still match.
Quiz 2: How does DeepSeek-V3’s sequential MTP architecture conceptually differ from Meta’s parallel MTP architecture?
Meta’s separate Transformer heads read the same prefix representations and share the vocabulary projection. The later-offset head does not receive an earlier head’s sampled output. DeepSeek-V3’s first auxiliary module also receives the ground-truth token at during training to predict ; its projection and Transformer block have separate parameters, while embedding and output-head parameters are shared with the main model. Future ground truth is unavailable at inference.
Quiz 3: Why are MTP drafts neither free nor universally superior?
Auxiliary heads, verification and state restoration cost resources, and acceptance is not guaranteed. Compare total latency, memory and throughput with a separate drafter under matched quality and load.
Quiz 4: Why is “MTP only helps above 70B” unsupported?
The cited study includes coding gains at 13B. Results depend on model, data, task and objective, so they do not establish a universal parameter threshold.
References
- DeepSeek-AI. (2024). DeepSeek-V3 Technical Report. arXiv:2412.19437.
- Gloeckle, F., et al. (2024). Better & Faster Large Language Models via Multi-token Prediction. Meta FAIR. arXiv:2404.19737.