Skip to content
← writing

How to read a paper (DeepSeekV3)

Jan 6, 2026 · 18 min read · llm, papers

contents
  1. 1DeepSeekv3
  2. 2key takeaways on first glance
  3. 3architecture
  4. 4multi-head latent attention
  5. 5let's look at the code for MLA
  6. 6MoE
  7. 7how routing decides which experts to use
  8. 8let's look at the code for MoE
  9. 9multi-token prediction
  10. 10let's look at the code for MTP
  11. 11summary
  12. 12references

DeepSeekV3: what it does and why it works.

DeepSeekv3

  • First off, this is a heavy ass paper: 53 pages, the same length as Roald Dahl's Esio Trot. That's a book, not a research paper.
  • This is off first read of the paper and how I usually read papers.
    • Step 1: Skim abstract + figures + tables + read conclusion
    • Step 2: First glance -> read and think about it
    • Step 3: Look at the formulas, upload them to GPT and explain in the easiest way, upload the paper to NotebookLM, ask questions (all stupid questions you have after first read)
    • Step 4: Second read -> to make sure you read it right the first time.
    • Step 5: Third read -> probably read a blog post on it, and write something about it explaining same stuff to yourself

breaking it down using this paper

Better than the open models it tests against (LLaMA-3.1 405B, Qwen2.5 72B), and comparable to GPT-4o and Claude-3.5-Sonnet. Trained on 2048 H800 GPUs. Pre-training took less than 2 months. Full training cost 2.788M GPU hours, about $5.6 million at 2 dollars per GPU hour.

key takeaways on first glance

major innovations I see as soon as I read this paper:

  • Cheap as hell
  • Performs well
  • Mixture-of-Experts (MoE) large language model (LLM) scaled to 671B parameters with only 37B active per token
  • Auxiliary-loss-free load-balancing for MoE routing (keeps experts balanced without hurting performance)
  • Multi-Token Prediction

For DeepSeek-V3, the core ideas are:

  1. Multi-Head Latent Attention (MLA) → fixes the key-value (KV) cache / inference memory
  2. DeepSeekMoE with aux-loss-free balancing → fixes MoE instability
  3. Multi-Token Prediction (MTP) → denser training signal + faster inference
  4. FP8 (8-bit floating point) training + DualPipe (a pipeline schedule that overlaps compute and communication) → makes all of this feasible at scale

Some results for motivation: results

architecture

arch

Before reading text, pause here.

Ask:

  • What replaces attention? → MLA
  • What replaces the feed-forward network (FFN)? → MoE
  • What’s new vs standard transformer? → both attention and FFN are modified

At this point, you already know where to zoom in.

  • Mixture of Experts

  • Multi-Head Latent Attention

  • Pretraining on 14.8T tokens with a 4K context length

  • Context extension after pretraining, in two stages

    • First stage: max context length = 32K
    • Second stage: max context length = 128K
  • Post-training: supervised fine-tuning (SFT) + reinforcement learning (RL) on the DSv3 base model (alignment to human preferences)

    • During post-training, they use distillation ("teacher" model transfers its learned knowledge to a "student" model) from R1 models.
      • The teacher is a long Chain-of-Thought (CoT) model from the DeepSeek-R1 series. The student is DeepSeek-V3.
  • Load Balancing Strategy and Multi-Token-Prediction Objective (MTP) for performance + inference speed

  • FP8 mixed precision training

multi-head latent attention

introduced in DeepSeek-v2 paper, fraction of resources + outperforms standard multi-head attention (MHA)

  • Multi-Head attention works, but the KV cache is enormous. MLA compresses it.
  • This is what attention scores look like for a normal MHA
    • attention_scores
      • i = i-th attention head, j = indexes over all previous tokens in sequence (from 1 -> t)

      • dh = dimension of each attention head = ( total embedding dimension of model ) / number_of_heads

      • softmax = attention score (converts logits to [0-1] probability ensuring they sum to 1) ~ normalisation

      • outputs from all attention heads are concatenated to a single vector * Weight matrix WoW_o

        • Converts back to original embedded dimension (so that attention input = output dimension)
      • The model keeps KtK_t and VtV_t in a cache. When a new token comes in, it doesn't recalculate K and V for all previous tokens. Each step adds only a new Q, and K and V stay the same for previous tokens. This is smart, but we do need to store this K and V for previous tokens somewhere right? We store it in a cache. KV-Cache 101.

      • Storing KV Cache for every token = memory bottleneck

      • Don't just believe what you read. What do we mean by a memory bottleneck here? How to compute memory for this?

        • For each token:
          • [K1, K2, K3, .. K_number_of_heads] = number_of_heads * dimension_head for keys
          • [V1, V2, V3, .. V_number_of_heads] = number_of_heads * dimension_head for values
        • Total: 2 * number_of_heads * dimension_head
        • Sequence Length = L
        • Total Memory per layer -> (2 * number_of_heads * dimension_heads * Length)
          • As Length grows -> 2 * number_of_heads * dimension_heads per token becomes LARGEEE.
      • Suffers from high KV-Cache requirements (inference bottleneck)

      • MLA solves this with Low Rank Key-Value Joint Compression

  • Instead of storing full key-value pairs, MLA compresses them into a shared latent space and reconstructs K and V only when needed
python
  # Original MHA
key = Weight_K @ input_token      # Full size key
value = Weight_V @ input_token         # Full size value
 
# MLA Compression:
compressed_kv = Weight_down @ input_token  # Compressed latent vector (store only this) low dim repre that stores only essential info
    # Weight_down = down projection matrix of Weight that reduces the dimension
 
# when needed -> reconstruct key and values
key = Weight_up_k @ compressed_kv  
value = Weight_up_v @ compressed_kv
 
# These can also be applied to queries to reduce memory usage
  • What are these Weight_down and Weight_up? Projections. Instead of storing K, V, store a small compressed vector.

You project the K and V vectors down to a smaller dimension, store that, and project back up when you need them. Standard linear algebra, nothing fancy..

  • How to do this? Store weight_up_key, weight_up_val (Fixed weights of model, one-time storage cost)
  • MLA does have large projection matrices. They’re part of the model parameters (stored once), not a per-token memory cost.
  • Per-token memory (what we need to cache during inference) is only the small d_c-dimensional vector called compressed_kv
  • At inference you don't even need to rebuild K and V. Matrix multiplication is associative, so you can fold Weight_up_k into the query matrix WQW_Q and Weight_up_v into the output matrix WOW_O:
  • cl
python
# d_c = compressed latent dimension (much smaller than number_of_heads * dimension_heads)
 
# fixed weights of the model:
Weight_up_k: (number_of_heads * dimension_heads) × d_c
Weight_up_v: (number_of_heads * dimension_heads) × d_c
 
# caching per token
compressed_kv: dimension d_c only
 
# DIFFERENCE
# mha
mha_tokens_memory = sequence_length * (2 * number_of_heads * dimension_heads)
 
# mla
mla_tokens_memory = sequence_length * d_c  # Much smaller!
model_params = 2 * (number_of_heads * dimension_heads * d_c)   # Fixed, one-time cost
  • Only storing small compressed vectors for each token instead of full key-value pairs. The DeepSeek-V2 paper reports a 93.3% smaller KV cache than DeepSeek 67B.

one problem: rotary position embedding (RoPE) is incompatible with the naive low-rank compression approach since RoPE = position sensitive to keys and queries making absorption impossible

RoPE is position-sensitive
Low-rank compression is linear algebra

Traditional RoPE applies position encoding to both K and Q

So in MLA, we can’t merge RoPE with compressed representations efficiently

RoPE is sensitive to the exact position of a token. With RoPE on the keys, a position-dependent rotation matrix sits between WQW_Q and Weight_up_k. Matrix multiplication is not commutative (A×B ≠ B×A), so you can't move that rotation out of the way and fold Weight_up_k into WQW_Q. You would have to rebuild the keys of every cached token at each step.

To solve this, DeepSeek decouples it: they keep the compressed part free of RoPE and add a small separate part that carries RoPE. Each final key and query is the two parts concatenated.

  • Decouple positional and compressed components
  • Apply RoPE only to the small separate part (64 numbers per head in DeepSeek-V3)

This is a classic example of:

A practical hack driven by math constraints

  • The model projects the compressed query to get the decoupled queries, one per head
  • It applies RoPE to them. Result: a set of positional queries across all attention heads
  • It projects the input token to get one decoupled key, shared by all heads, and applies RoPE to it
  • It concatenates each compressed part with its positional part, for queries and for keys
  • Then it calculates the attention score

So MLA caches two things per token per layer: the compressed vector (512 numbers) and the shared RoPE key (64 numbers).

python
# New approach - Decoupled RoPE:
# 1. Separate position-aware queries
query_R = RoPE(Weight^QR @ compressed_query)    # Position-aware queries
key_R = RoPE(Weight^KR @ input_token)    # Position-aware shared key
 
# 2. Split into heads and concatenate
query_t,i = [query_R_1, query_R_2, ..., query_R_no_of_heads] 
key_t = [key_R_1, key_R_2]            
 
# 3. Concatenate for final attention
query_full = [query_t, 1; query_t,2]              
key_full = [key_t,1; key_t,2]        
  • drope

memory requirements summary

With DeepSeek-V3's sizes (128 heads, 128 numbers per head, dcd_c = 512, RoPE key = 64), the per-token cache looks like this:

input ht 7168 numbers KV cache latent ct 512 numbers RoPE key kt 64 numbers WDKV RoPE keys 128 heads × 128 values 128 heads × 128 WUK WUV rebuilt when needed, or folded into WQ and WO Cache per token, per layer standard MHA: 2 × 128 heads × 128 = 32,768 numbers MLA: 512 + 64 = 576 numbers 576 / 32,768 = 1.8% of the MHA cache 98.2% smaller, for the same 128 heads

The table below comes from the DeepSeek-V2 paper. There ll = 60 layers; DeepSeek-V3 has 61.

comp

let's look at the code for MLA

python
'''
Replace normal multi-head attention, Reduce KV cache size, Share latent representation
 
Standard Attention
  Q = X * Wq
  K = X * Wk
  V = X * Wv
  Attention(Q, K, V)
 
MLA
  Q = X Wq
  Latent = X * W_latent
  K = Latent * Wk_recon
  V = Latent * Wv_recon
  Attention(Q, K, V)
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
 
class MLA(nn.Module):
    def __init__(self, d_model, n_heads, d_latent, dropout=0.1):
        super().__init__()
        assert d_model % n_heads == 0
        self.h = n_heads
        self.dh = d_model // n_heads
 
        self.q = nn.Linear(d_model, d_model, bias=False)
        self.z = nn.Linear(d_model, d_latent, bias=False)
        self.kv = nn.Linear(d_latent, 2 * d_model, bias=False)
 
        self.out = nn.Linear(d_model, d_model)
        self.drop = nn.Dropout(dropout)
 
    def forward(self, x):
        B, T, D = x.shape
 
        q = self.q(x)
        k, v = self.kv(self.z(x)).chunk(2, dim=-1)
 
        def split(t):
            return t.view(B, T, self.h, self.dh).transpose(1, 2)
 
        q, k, v = map(split, (q, k, v))
 
        attn = (q @ k.transpose(-2, -1)) / (self.dh ** 0.5)
        attn = self.drop(attn.softmax(dim=-1))
 
        out = (attn @ v).transpose(1, 2).reshape(B, T, D)
        return self.out(out)
 
class MLABlock(nn.Module):
    def __init__(self, d_model, n_heads, d_latent):
        super().__init__()
        self.attn = MLA(d_model, n_heads, d_latent)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, 4 * d_model),
            nn.GELU(),
            nn.Linear(4 * d_model, d_model)
        )
        self.n1 = nn.LayerNorm(d_model)
        self.n2 = nn.LayerNorm(d_model)
 
    def forward(self, x):
        x = self.n1(x + self.attn(x))
        return self.n2(x + self.ffn(x))
 
# transformer
class MLATransformer(nn.Module):
    def __init__(self, vocab, d_model=4096, n_heads=32, d_latent=512, n_layers=24):
        super().__init__()
        self.embed = nn.Embedding(vocab, d_model)
        self.blocks = nn.ModuleList(
            [MLABlock(d_model, n_heads, d_latent) for _ in range(n_layers)]
        )
        self.head = nn.Linear(d_model, vocab)
 
    def forward(self, ids):
        x = self.embed(ids)
        for b in self.blocks:
            x = b(x)
        return self.head(x)
 
# MLA compresses keys and values through a shared latent space, reducing KV-cache memory from O(2·d_model) to O(d_latent) per token, without changing the attention equation.
 
# let embed_dim = 4096 and latent_dim = 512
 
# | Method       | Stored per token |
# | ------------ | ---------------- |
# | Standard MHA | `2 × 4096`       |
# | MLA          | `512`            |
# 8192 / 512 = 16× KV memory reduction in this toy example (DeepSeek-V3's config: 576 vs 32,768 numbers, 98.2% smaller) :: this is HUGE.

MoE

MoE: in the DeepSeekMoE paper, a 145B MoE model matches the dense DeepSeek 67B with only 28.5% (maybe even 18.2%) of the computations

  • Instead of one huge brain doing everything, MoE uses many small specialist brains, and a router that decides which ones to consult for each token.

How standard transformer works (recap) Token → Attention → Feed-Forward Network (FFN) → Next layer

  • Every token uses the same FFN
  • Compute cost grows linearly with model size
  • Bigger model = slower + more expensive

Q. What are dense models? dm

Q. What are sparse models? sm sm2

  • In Mixture of Experts, the FFN is replaced with many FFNs (experts)

replace

Token → Attention → Router → Selected Experts → Combine → Next layer

Instead of 1 FFN for all tokens we get N experts from which only K experts are used per token. DeepSeek-V3 has 256 routed experts and K = 8, plus 1 shared expert that every token uses.

Routing is per-token, not per-sequence. Different tokens in the same input can go to different experts.

token 1 token 2 router score + bias, keep top-8 shared expert every token uses it 256 routed experts Token 1: the router picks 8 of the 256 routed experts. The shared expert runs as well. Token 2 gets a different set of 8. Routing is per token, not per sequence. Each token: 1 shared + 8 routed experts 37B of 671B parameters active per token (5.5%)

Intuition

In a hospital, we have

  • Cardiologist
  • Neurologist
  • Orthopedic
  • Dermatologist

We don’t send every patient to all doctors. A nurse (router) decides who sees whom

  • MoE = hospital
  • Experts = doctors
  • Router = triage nurse
  • Token = patient

Similarly DeepSeekv3 uses:

  • 1 shared expert and 256 routed experts per MoE layer (the first three layers keep a dense FFN)
  • Sparse activation: Only the top-8 routed experts are active per token

Experts are:

  • Independent FFNs
  • Same input/output shape

Outputs are weighted and summed

Examples

So for a token like "gradient":

  • Expert #17 (math)
  • Expert #42 (ML) might get activated (top K here is 2)

For "Shakespeare":

  • Expert #3 (literature)
  • Expert #91 (language style) might get activated

These labels are made up to build intuition. Real experts tend to specialize in token-level patterns (punctuation, verbs, numbers), not in whole subjects. The second figure under "architecture of MoE" shows this.

How is this better than vanilla dense model?

ModelTotal ParamsActive Params per token
Dense (LLaMA-3.1 405B)405B405B
MoE (DeepSeek-V3)671B37B
  • Knowledge of a 671B model
  • Compute per token of a 37B model

moe Switch Transformer: the router sends each token to 1 of 4 FFN experts. DeepSeek-V3 does the same with 8 of 256, plus the shared expert.

architecture of MoE

MoE architecture consists of two components:

  • Experts
  • Gating Network / Router

The token embedding goes into the router. The router scores all experts and selects the top-K (sparse activation). Each selected expert processes the input independently. The layer weights the expert outputs by their gating scores and sums them. That sum replaces the standard FFN output and goes on to the next layer.

moe2

Where can this be a problem? Router collapse (same expert always picked)

  • expert1: 5%
  • expert2: 2%
  • expert3: 1%
  • expert4: 6%
  • expert5: 86%

This is not balanced at all. Workload isn't being distributed properly. If the same experts get picked:

  • Others don’t train
  • Capacity is wasted
  • Performance drops

Q. What is the problem? Not only will there be an uneven distribution of experts chosen, but some experts will hardly be trained at all. This results in issues during both training and inference.

Instead, we want equal importance among experts during training and inference. How to prevent overfitting on the same experts?

How to solve this? Load Balancing!!!!

  • DeepSeek v3 does Bias-Based Routing for DeepSeekMoE
    • bias
    • score_for_routing = original_score + bias (original_score is the router's affinity score, see how routing decides which experts to use)
    • For each expert after each training step:
      • If expert is overloaded:
        • bias -= γ (make them less likely to get picked next time)
      • If expert is underloaded:
        • bias += γ (make them more likely to get picked next time)

Each expert has a bias term bib_i. After each training step, bib_i goes down or up by γ (the bias update speed: 0.001 for the first 14.3T tokens, then 0), based on whether the expert is over- or under-loaded. The bias only decides which experts get picked. The gating weight still comes from the original affinity score. So you keep quality (original affinity scores) and get balance (through bias adjustments).

Instead of adding a big auxiliary loss (which hurts quality), they:

  • Add a bias term to routing scores
  • Adjust it based on expert load

They keep only a tiny sequence-wise balance loss (weight α = 0.0001) to avoid extreme imbalance inside one sequence.

The result:

  • Routing stays mostly semantic

  • Balance improves in small steps

  • For each token:

    • We want many experts available, but we want to run only a few & combine their outputs by weight.
  • Routing answers two questions:

    • Which experts should run?
    • How much should each selected expert contribute?

Let utu_t (everything the model knows so far about this token) be the embedding of the t-th token coming into the FFN/MoE layer

DeepSeek-style MoE splits experts into:

  • A. Shared experts (always on)

    • Capture general-purpose transformations
  • B. Routed experts (conditionally on)

    • Only a few are activated, captures specialized behavior
  • Shared experts → no gating weights

  • Routed experts → weighted by routing scores

output = input + shared expert outputs + routed expert outputs

The formula: input + shared expert FFN outputs + routed expert FFN outputs, each routed output scaled by its gate gi,tg_{i,t} (the next section shows how the router computes gi,tg_{i,t}). formula

how routing decides which experts to use

Step 1: Compute an affinity score for each routed expert

For each routed expert i, compute:

  • s(i, t) = sigmoid (input.T * eie_i) where eie_i = learned vector representing expert i (dot product here means similarity and sigmoid squashes score to [0,1])

The core of this formula is the dot product input.T * eie_i. In vector math, a dot product is a measure of similarity.

This step asks: 'How similar is the current token's meaning to the specialty of expert i?' The result is a similarity score.

Meaning: How suitable is expert i for token t?

Step 2: Sparsity: only keep the top-K experts Instead of using all routed experts:

  • Select the top K experts with highest scores (DeepSeek-V3: K = 8, ranked by si,t+bis_{i,t} + b_i with the load-balancing bias)
  • Set all others to zero

sparsity

Step 3: Normalize the selected experts (soft weighting) normalise

So they sum up to 1 (makes outputs stable, prevents exploding activations)

Step 4: Apply routed experts routed

Final MoE output:

  • Start with the original input (residual)
  • Add shared expert outputs
  • Add weighted routed expert outputs

Each token asks a few experts “how would you process this?”, weighs their answers, and combines them, instead of asking the entire model.

Design choiceReason
Dot product with e_iLearn expert specialization
SigmoidStable scores
Top-KSparsity & efficiency
NormalizationStable training
Weighted sumSmooth expert blending
Residual connectionTraining stability

let's look at the code for MoE

python
'''
In a Mixture-of-Experts layer, each token is routed to only a small subset of experts (top-k) instead of all parameters being activated. A lightweight router assigns tokens to experts, and only the selected experts process that token. This keeps compute roughly constant while allowing the total parameter count to scale.
 
x_after_mla ──► router scores ─────────► top-k experts selected
                 │  (gating network)
                 ▼
        selected experts compute
    weighted outputs → aggregated
 
g_i' = Router(x)       # raw scores for each expert
g_i  = top-k + normalize
output = Σ (g_i * Expert_i(x))
 
for token:
    pick top-k experts
    run only those
'''
 
# Top-K MOE
import torch
import torch.nn as nn
import torch.nn.functional as F
 
class MoE(nn.Module):
    def __init__(self, d_model, n_experts=8, k=2):
        super().__init__()
        self.k = k
        self.router = nn.Linear(d_model, n_experts, bias=False)
        self.experts = nn.ModuleList([
            nn.Sequential(
                nn.Linear(d_model, 4 * d_model),
                nn.GELU(),
                nn.Linear(4 * d_model, d_model)
            )
            for _ in range(n_experts)
        ])
 
    def forward(self, x):
        B, T, D = x.shape
        scores = self.router(x)                # (B,T,E)
        probs = scores.softmax(dim=-1)
 
        topk_val, topk_idx = probs.topk(self.k, dim=-1)
 
        out = torch.zeros_like(x)
 
        for i in range(self.k):
            expert_ids = topk_idx[..., i]
            expert_wts = topk_val[..., i].unsqueeze(-1)
 
            for e, expert in enumerate(self.experts):
                mask = (expert_ids == e)
                if mask.any():
                    out[mask] += expert(x[mask]) * expert_wts[mask]
 
        return out
 
# MOE
class MoEBlock(nn.Module):
    def __init__(self, d_model, n_heads, n_experts, k):
        super().__init__()
        self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
        self.moe = MoE(d_model, n_experts, k)
        self.n1 = nn.LayerNorm(d_model)
        self.n2 = nn.LayerNorm(d_model)
 
    def forward(self, x):
        x = self.n1(x + self.attn(x, x, x)[0])
        return self.n2(x + self.moe(x))
 
# model
class SimpleMoE(nn.Module):
    def __init__(self, vocab, d_model=512, n_heads=8,
                 n_layers=6, n_experts=8, k=2):
        super().__init__()
        self.emb = nn.Embedding(vocab, d_model)
        self.layers = nn.ModuleList([
            MoEBlock(d_model, n_heads, n_experts, k)
            for _ in range(n_layers)
        ])
        self.head = nn.Linear(d_model, vocab)
 
    def forward(self, ids):
        x = self.emb(ids)
        for l in self.layers:
            x = l(x)
        return self.head(x)

joining the dots

  • How does transformer for DSv3 look like?
  • FFN -> MoE
  • Attention -> MLA (low rank key-val joint compression)
text
Input
  ↓
MLA (attention)
  ↓
MoE (FFN replacement)
  ↓
Output

Final optimisation in DSv3:

multi-token prediction

  • Standard language models (GPT, LLaMA, etc.) train with next-token prediction (NTP)
  • Autoregressive means one token at a time
  • Multi-token prediction predicts multiple future tokens at once (the next n tokens) from the same input context
    • Instead of p(xt+1∣x1:t)p(x_{t+1} \mid x_{1:t}), we do p(xt+1,xt+2,…,xt+n∣x1:t)p(x_{t+1}, x_{t+2}, \dots, x_{t+n} \mid x_{1:t})
    • Each head predicts one future token. These predictions are trained jointly.
  • During training, the model predicts multiple future tokens. At inference, you can throw the extra prediction heads away, or use them for speculative decoding to speed up generation.
  • Shared embedding layer and output head. In DeepSeek-V3, each extra prediction depth adds one transformer block
  • Works best with long sequences

Q. Why?

  • Denser learning signal
    • With next-token prediction, each position gives one prediction loss.
    • With multi-token prediction, each position gives n prediction losses at the same time.
    • More gradient signal per token (faster learning per example)
  • Inference acceleration
    • If you can predict multiple tokens in one pass, you reduce the number of sequential forward passes needed
    • Fewer sequential decoding steps

Q. How does this speed up inference?

  • A standard autoregressive model needs one full forward pass per token. 100 tokens = 100 sequential passes.
  • With MTP, if the model predicts 3 tokens per pass, you need ~33 passes for 100 tokens. Fewer sequential steps, direct acceleration.
  • DeepSeek-V3 predicts 1 extra token. The paper reports that the extra token is accepted 85-90% of the time, which gives 1.8x more tokens per second.

DeepSeekV3 trains on both objectives: next-token prediction plus MTP from each position.

how is it different than original MTP

  • The original academic MTP proposal predicts all future tokens in parallel using independent heads at each position.

    • For example, head_1 predicts token t+1, head_2 predicts token t+2, and so on, all from the same hidden state.
  • DeepSeek’s implementation is different. It predicts the extra tokens one after another, with sequential MTP modules

    • MTP module k takes the hidden state from depth k-1 and the embedding of token t+k. Its transformer block then predicts token t+k+1.
    • This keeps the full causal chain at each prediction depth.
    • Each module shares the embedding layer and the output head with the main model.
  • DeepSeek-V3 sets the MTP depth to 1: besides the next token, each position predicts one more token

  • Advantages

    • Because the model learns to anticipate more outcomes from a single context position, it gets more training signal per token seen
    • In the paper's ablation, MTP improves most benchmarks, including code (HumanEval, MBPP) and math (GSM8K, MATH)
    • The image below shows the original MTP loss:
    • loss
    • DeepSeek-V3 computes one cross-entropy loss per depth, averages them, and multiplies the result by λ (0.3 for the first 10T tokens, then 0.1). This MTP loss is added to the main next-token loss.

let's look at the code for MTP

This code is the simpler parallel-heads version (one linear layer predicts K future tokens), not DeepSeek's sequential modules.

python
'''
hidden_t ── linear ──► [P(t+1), P(t+2), P(t+3)]
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
 
class MTPTransformer(nn.Module):
    def __init__(self, vocab, d_model=512, n_layers=6, n_heads=8, K=3):
        super().__init__()
        self.K = K
 
        self.tok = nn.Embedding(vocab, d_model)
        self.pos = nn.Embedding(2048, d_model)
 
        layer = nn.TransformerEncoderLayer(
            d_model=d_model, nhead=n_heads, batch_first=True
        )
        self.encoder = nn.TransformerEncoder(layer, n_layers)
 
        # One projection predicts K future tokens
        self.head = nn.Linear(d_model, K * vocab)
        self.vocab = vocab
 
    def forward(self, ids):
        B, T = ids.shape
        pos = torch.arange(T, device=ids.device).unsqueeze(0)
 
        x = self.tok(ids) + self.pos(pos)
        h = self.encoder(x)                          # (B,T,D)
 
        logits = self.head(h)                        # (B,T,K·V)
        return logits.view(B, T, self.K, self.vocab) # (B,T,K,V)
 
 
# loss
def mtp_loss(logits, ids):
    """
    logits: (B, T, K, V)
    ids:    (B, T)
    """
    B, T, K, V = logits.shape
    loss = 0.0
 
    for k in range(K):
        pred = logits[:, :-k-1, k]     # predict t+k+1
        tgt  = ids[:, k+1:]            # ground truth
        loss += F.cross_entropy(
            pred.reshape(-1, V),
            tgt.reshape(-1)
        )
    return loss
 
# usage
model = MTPTransformer(vocab=32000, K=3).cuda()
opt = torch.optim.AdamW(model.parameters(), 3e-4)
 
ids = torch.randint(0, 32000, (8, 128)).cuda()
 
logits = model(ids)
loss = mtp_loss(logits, ids)
 
loss.backward()
opt.step()
 
print(loss.item())
 

summary

Always look for:

  • Ablations (does removing X hurt?)
  • Costs (not just accuracy)
  • Stability (loss spikes, divergence)

DeepSeek-V3 shows:

  • MTP improves downstream performance
  • Auxiliary-loss-free balancing beats a pure auxiliary-loss baseline on most benchmarks
  • FP8 does not cause instability at scale

Every good paper has limits.

DeepSeek-V3:

  • Requires massive infra (2048 H800s)
  • Custom kernels are non-trivial to reproduce
  • Deployment unit is still large
  • Inference speed ≠ solved forever
text
Input
↓
MLA → fixes memory
↓
MoE → fixes compute
↓
MTP → fixes learning signal
↓
FP8 + DualPipe → makes it trainable

references

reply by email

related