TransMLA and Sparse Attention

TransMLA rewrites an already trained Llama 2 7B into Multi-head Latent Attention. It cuts the KV cache by 92.97%. Then 6 billion training tokens, 0.3% of its 2 trillion pretraining tokens, win back an average of 58.68 against the original 59.85.

Pick a compression rung, then switch the fine-tune on. Watch the cache shrink and the score fall and come back. Then we build it piece by piece: the head merge, the rotation that moves position into one head, and the balanced compression. Then the speed test and DeepSeek's sparse indexer.

You need a little Python and what attention computes. Session 3 counts MLA's cache; we build the rest from zero.

Session 9 of Georgia Tech CS 8803, LLM seminar. It rests on two papers: Meng, Tang, Tang, Yao, Sun and Zhang, TransMLA: MLA Is All You Need (2025), and DeepSeek-AI, DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models (2025), section 2. Every idea is re-taught here in our own words and devices.

Convert a trained model

Scores: average of six benchmarks, TransMLA Table 1 (Llama 2 7B). Cache: 2 × 32 heads × 128 numbers = 8,192 per token per layer, from Llama 2's public shape; one cell is 16 numbers. Fine-tune budgets: 500M, 3B and 6B tokens.

Chapter 0

The Sunk Cost

See why a trained model cannot switch to MLA by a config change, and what TransMLA does instead

You serve Llama 2 7B. Its makers pretrained it on 2 trillion tokens. It uses plain Multi-Head Attention (MHA): every head stores its own key and value for every past token. That store, the KV cache, fills your GPUs first.

A colleague read Session 3 and wants Multi-head Latent Attention (MLA). MLA caches one small latent vector per token and rebuilds keys and values from it with learned matrices. Your checkpoint has no such matrices. The usual way to get them is to pretrain again.

TransMLA takes another way. It builds the MLA matrices from the trained key and value weights, compresses them, and trains a little to recover.

Price the two paths

Each bar is a count of training tokens on a log scale: one step right is ten times more. Pick a rung and compare.

Token counts from TransMLA Table 1 (Llama 2 7B: 2T pretraining; 500M, 3B, 6B fine-tune).

The worked number: 6 billion / 2 trillion = 0.003, so the largest fine-tune is 0.3% of the original run.

A second wall waits behind the first. A small cache stores less per token, but each new token still scores every cached token. At DeepSeek-V3.2's 128K context that is up to 131,072 tokens per step. Its DeepSeek Sparse Attention (DSA) reads 2,048 of them.

Failure. You load the old weights into an MLA config. The output is noise, because the latent matrices were never in the checkpoint. Measure: perplexity on held-out text. Fix: build those matrices from the old key and value weights, as Chapter 2 does.

  1. GQA, one knob: the group count that every open model sets.
  2. Merge the heads: GQA rewritten exactly as MLA.
  3. Why MLA can do more: the paper's order of expressive power.
  4. Move position into one head: RoRoPE and FreqFold.
  5. Balance, then compress: the PCA that makes the latent small.
  6. The compression ladder: the hero's rungs and scores.
  7. Faster on real GPUs: vLLM throughput and the memory wall.
  8. Read fewer tokens: DeepSeek's lightning indexer and top-k.
  9. Train the indexer: copy the model's own attention.
  10. Field guide: numbers, code, links and the credit.
Why can a trained MHA or GQA model not switch to MLA by changing a config?

Chapter 1

GQA, One Knob

Write grouped-query attention precisely, so that you can check "a special case of MLA" by hand

Most open models use Grouped-Query Attention (GQA). It keeps h query heads but only g key heads and g value heads. Each query head belongs to one group and reads that group's key and value. Each head has d numbers.

The knob g has two named ends. With g = h every group holds one head: that is MHA, and Llama 2 7B is this case. With g = 1 all heads share one key and one value: Multi-Query Attention (MQA).

Group the heads

Top: 32 query heads, boxed by group. Bottom: one cached key and value per group. Drag the groups, then pick a head and follow its arrow.

8
5

h = 32 heads of d = 128 numbers, the width of Llama 2 7B. Cache count 2 × g × 128 per token per layer.

Which key does query head i read? Name the query head i, the head count h, the group count g, and the group it reads j.

Say it aloud

j equals the ceiling of i over, h over g.

j
j the group whose key and value head i reads, from 1 to g.
⌈ ⌉
the ceiling of round up to the next whole number.
i
i the query head, from 1 to h.
h
h query heads per layer: 32 here.
g
g groups, and so key heads, per layer.
In plain words

Divide h by g to get the heads in each group. Divide i by that number and round up. The result is the group j.

With numbers

With h = 32 and g = 8, each group has 32 / 8 = 4 heads. Head i = 5 gives 5 / 4 = 1.25, rounded up to j = 2. Head 5 is the first head of group 2.

Each layer caches one key and one value per group: 2 × g × d numbers per token. With d = 128, g = 32 caches 8,192, g = 8 caches 2,048 and g = 1 caches 256. Session 3 counts this in full, over all layers.

Failure. You lower g to save memory and hard benchmarks drop. The TransMLA paper says it plainly: GQA and MQA shrink the cache at the cost of quality. Measure on hard tasks, not perplexity alone. Fix: keep the cache small without forcing heads to share one key. That is where the next two chapters go.

With h = 32 and g = 4, which group does query head 17 read?

Chapter 2

Merge the Heads

Rewrite a GQA layer as an MLA layer that computes exactly the same thing

MLA caches one latent per token and rebuilds each head's key from it with an up-projection, a matrix per head. TransMLA's first step shows that GQA already has this shape, if you choose the latent well.

Choose the latent to be every key and every value of the token, stacked. Call it ct: g keys then g values, so 2gd numbers. Its down-projection is the old WK stacked on WV. The merge computes nothing new and stores nothing new.

Now build an up-projection for query head i. Call it WiUK: d rows by gd columns, all zeros except a d × d identity block in the columns of group j. Call the key half of the latent ctK.

Say it aloud

k-hat t i equals W-i-U-K times c-t-K, which equals k t j.

k̂t,i
k-hat t i the key that head i rebuilds for token t.
WiUK
W-i-U-K head i's up-projection: zeros, with one identity block over group j.
ctK
c-t-K the key half of the latent: g keys stacked, gd numbers.
kt,j
k t j the GQA key of group j for token t, the one head i read before.
In plain words

Multiply the stacked keys c-t-K by the selector W-i-U-K. The zeros cancel every group except j. The identity block copies group j's key unchanged, so head i sees the same key as before.

With numbers

With made-up numbers: h = 4, g = 2, d = 2, keys k1 = [3, 1] and k2 = [0, 5], so cK = [3, 1, 0, 5]. Head 3 is in group 2, so W3UK = [[0, 0, 1, 0], [0, 0, 0, 1]]. The product is [0, 5] = k2, exactly.

Step through the selectors

Top: the latent, keys then values. Middle: one head's selector, teal cells are 1. Bottom: what it rebuilds. Press Next head, or switch to values.

Toy sizes and made-up keys and values: h = 4, g = 2, d = 2. The construction is TransMLA section 4.1.

Two more details. WiUV picks values the same way. RoPE turns every head by the same rule, so the merged key gets one RoPE repeated every d numbers.

The cache is still 2gd numbers, the same as GQA. The paper says so: this step alone saves nothing, and the selectors add multiplies. What it buys is the shape. The selectors can later become dense, compressed matrices.

Failure. Your rebuilt keys differ from GQA's. The usual cause is an off-by-one: Python counts heads from 0. Measure: the largest difference between rebuilt and original keys on one batch must be 0. Fix: j = i // (h // g) with i counted from 0.

After the merge, why is the cache the same size as before?

Chapter 3

Why MLA Can Do More

See what a dense up-projection can build that a selector cannot, at the same cache size

The paper proves an order at equal cache size and equal query heads: GQA < MLAFactorized < MQA (Appendix A). MLAFactorized means MLA with low-rank keys and values and a full query. The order is about which functions each layer can compute.

The first step is Chapter 2: every GQA layer is an MLA layer with selector blocks. The step is strict because a selector can only copy one group's key. A dense up-projection can mix groups.

Mix two groups

Blue rings: the only two keys a selector can give a head. Teal dot: the key a dense row gives. Drag the mix.

0.50

Toy keys k1 = [3, 1] and k2 = [0, 5], as in Chapter 2. A dense matrix can reach any key in the plane; the line is the part this one slider shows.

The worked number: take the latent [3, 1, 0, 5]. A dense row [0.5, 0, 0.5, 0] gives 0.5 × 3 + 0.5 × 0 = 1.5. The second row [0, 0.5, 0, 0.5] gives 0.5 × 1 + 0.5 × 5 = 3. The key [1.5, 3] is 2.5 away from both copies, so no selector makes it.

MQA sits above both. Give MQA one head of 2gd numbers so its cache matches. Its query and key can then interact at rank up to 2gd. Each MLA head's interaction has rank at most d (Appendix A.2).

What the order buys is room. A converted layer starts at exactly GQA's function, inside a larger set. The fine-tune can then move into the larger set at no extra cache.

Failure. You expect the merge alone to raise quality and it does not. That is the correct result: identity blocks compute the same function. Measure: outputs before and after the merge match to rounding. Fix: none needed; the gain needs dense matrices and training.

What makes "GQA < MLAFactorized" a strict inequality?

Chapter 4

Move Position Into One Head

Rotate the heads so that one carries the position signal and the rest can drop RoPE

MLA's speed comes from absorb: fold WUK into the query weights and score the cached latent directly (Session 3, Chapter 2). RoPE breaks absorb, because a turn that depends on position sits in between. DeepSeek trains a small separate RoPE key; a converted model has RoPE in every head.

TransMLA's fix is RoRoPE. RoPE works on pairs of numbers, a real part and an imaginary part, one pair per frequency. Take one frequency pair l and gather it from all g heads. RoPE turns every head's pair at that frequency by the same angle.

So mix the heads with an orthogonal matrix Ul, the same way in both halves. Call the query's numbers at pair l ql, the key's kl, and RoPE's turn Rt.

Say it aloud

The inner product of R-t U-l q-l with R-s U-l k-l equals the inner product of R-t q-l with R-s k-l.

⟨ , ⟩
the inner product of multiply matching numbers and add: the attention score's share from pair l.
Rt, Rs
R-t, R-s RoPE's turn for the query's position t and the key's position s, the same angle for every head.
Ul
U-l a g by g orthogonal matrix that mixes the heads, applied the same way to real and imaginary parts.
ql
q-l the query's numbers at pair l, from all g heads.
kl
k-l the key's numbers at pair l, from all g heads.
In plain words

Mix the heads of q-l and k-l with U-l. RoPE still turns each head's pair by the same angle, so it does not notice the mix. A rotation does not change inner products, so the score stays the same.

With numbers

With made-up numbers: g = 2, both tokens at position 0 (no turn), imaginary parts 0. Then q = [1, 2] and k = [3, 1] score 3 + 2 = 5. With U = [[0.6, 0.8], [−0.8, 0.6]]: Uq = [2.2, 0.4], Uk = [2.6, −1.8], and the score is 5.72 − 0.72 = 5.0.

RoRoPE picks a useful Ul. It runs PCA (principal component analysis) on the keys of a small dataset, one frequency at a time. The chosen Ul pushes most key energy into the first head, which keeps RoPE. The other heads drop RoPE and lose little.

Rotate the heads

Each dot is one token's key at one frequency: its head 1 part across, its head 2 part up. Turn the axes. Press PCA for the best turn.

0°

Illustrative keys for two heads, real parts only. The real method runs PCA over all g heads for each of the d/2 frequencies (TransMLA section 4.2, Figure 2).

FreqFold treats a few neighbouring RoPE frequencies, which turn at almost the same speed, as one for PCA. On Llama 3 8B with RoPE removed from 90% of dimensions, RoRoPE with 4D FreqFold keeps WikiText-2 log-perplexity near 2. MHA2MLA, which picks dimensions by norm, reaches nearly 6 (Figure 3b). Folding 8 is worse than 4.

Failure. You rotate real parts with one U and imaginary parts with another, and scores change. Measure: compare scores at two positions before and after the rotation. Fix: one Ul per frequency, used on both halves.

Why does RoRoPE's rotation leave every attention score unchanged?

Chapter 5

Balance, Then Compress

Shrink the keys and values into one small latent with PCA, after making them equally loud

After RoRoPE, one head of keys keeps RoPE. The other key heads, the NoPE keys (no position), and all the values get compressed together. TransMLA stacks them and runs PCA on their activations over a small calibration set, WikiText-2. It keeps the top rkv directions. That basis becomes the new down- and up-projections, and the rkv-number latent is what the cache stores.

There is a catch. The paper measures that NoPE keys are far longer than values in Llama 3 8B (Figure 4a). PCA keeps the directions of largest variance, so it keeps key directions and drops value directions.

The fix is Balanced Key-Value (BKV): divide the NoPE key projection by a factor α and multiply WUK by α. Call the NoPE key of token t WDKNoPExt and its value WDVxt.

Say it aloud

Alpha equals the average over t of the norm of W-D-K-NoPE x-t, divided by the average over t of the norm of W-D-V x-t.

α
alpha the balancing factor: how many times longer keys are than values.
Et
the average over t over the tokens of the calibration set.
‖ ‖
the norm of the length of a vector.
WDKNoPExt
W-D-K-NoPE x-t token t's NoPE key: every key head except the RoPE head.
WDVxt
W-D-V x-t token t's value, all g heads.
In plain words

Measure the average length of the NoPE keys and of the values over the calibration tokens. Divide the first by the second to get alpha. Shrink the keys by alpha before PCA and grow W-U-K by alpha, so every rebuilt key stays the same.

With numbers

With made-up numbers: keys average length 12, values 1.5, so α = 12 / 1.5 = 8. A key of length 12 enters PCA at length 1.5. The rebuilt key is WUK times the latent, and 8 × (1 / 8) = 1, so attention sees the same key.

Keep 2 of 4 directions

Four directions, two from keys (solid) and two from values (outlined). PCA keeps the two tallest. Drag the balance and watch which survive.

0%

Toy variances 100, 64, 1 and 0.81 on independent directions, so PCA keeps the largest bars. At 100% balance the device divides the keys by α ≈ 9.5. The real effect is TransMLA Figure 4.

The paper tests two choices on Llama 3 8B (Figure 4b). Balancing lowers perplexity after compression, for PCA on weights and on activations. PCA on activations beats PCA on weights.

Failure. After compression the model loses facts, yet key reconstruction looks fine. Measure: the reconstruction error of keys and of values, separately. Fix: balance before the joint PCA.

Why does TransMLA divide the NoPE keys by α before the joint PCA?

Chapter 6

The Compression Ladder

Count what each rung caches, then read what it costs in score and in training tokens

Llama 2 7B caches a key and a value for 32 heads of 128 numbers: 8,192 numbers per token per layer. TransMLA keeps a share of them: the RoPE part plus the latent. Call the cut fraction r, the head count h, the head width d, and the count that stays C′.

Say it aloud

C-prime equals one minus r, times two h d.

C′
C-prime numbers cached per token per layer after the cut.
r
r the cut fraction: 0.6875, 0.875 or 0.9297 on the paper's ladder.
2
two one key and one value.
h
h heads: 32.
d
d numbers per head: 128.
In plain words

Count the original cache, two times h times d. Keep the share one minus r of it. That is C-prime.

With numbers

The top rung keeps 7.03%: C′ = 0.0703 × 8,192 = 576 numbers. At 2 bytes over 32 layers: 576 × 2 × 32 = 36,864 bytes, or 36 KiB per token. The original needs 512 KiB.

Climb the ladder

Bars are the six-benchmark average. The blue line is the original model. Pick a rung, then switch training on.

All scores from TransMLA Table 1, Llama 2 7B. MHA2MLA's trained scores use 6B tokens and come from its own paper, as Table 1 notes. MHA2MLA has no −92.97% row.

RungKept per layerTransMLA, no trainingTransMLA, trainedMHA2MLA, no trainingMHA2MLA, 6B
−68.75%2,56058.2059.82 (500M)37.9059.51
−87.50%1,02451.1959.36 (3B)32.7058.96
−92.97%57643.2658.68 (6B)——

Read three things. Without training, TransMLA at −68.75% loses 1.65 points where MHA2MLA loses 21.95. TransMLA at −92.97% untrained, 43.26, still beats MHA2MLA at −68.75%, 37.90. Trained, TransMLA used 500M tokens where MHA2MLA used 6B. On SmolLM 1.7B at −68.75%, TransMLA needed 4.9% of MHA2MLA's data and about 2 hours of training.

These scores belong to the whole recipe: merge, RoRoPE, FreqFold, BKV and the fine-tune. Table 1 does not remove one piece at a time; Figures 3b and 4b test pieces only by perplexity. The 6B budget is two runs, 5B then 1B (Table 3).

Failure. You take −92.97% with no training budget. The average drops 16.59 points, and text wanders: "Hello, my name is Katiu, my father's dog, the pet of the 3600 year-old tribe" (Table 5). Fix: with no budget, stay at −68.75%.

How many numbers per token per layer does the −87.50% rung cache for Llama 2 7B?

Chapter 7

Faster on Real GPUs

Read the vLLM throughput table and see why the gain grows with context

A smaller cache matters only if tokens come out faster. The paper serves the −92.97% model and the original with vLLM, an open serving engine. It uses three accelerators: 165.2 TFLOPS with 24 GB, 312 TFLOPS with 40 GB, and 320 TFLOPS with 64 GB. Half of each context is input and half is output. Throughput is output tokens per second (Appendix F, Table 4).

Serve both models

Pairs of bars, one pair per context length, on a log scale. Blue is the original, teal is TransMLA. Pick a card and a context.

8K

Throughput from TransMLA Table 4. Requests: 1,000 at 1K, 100 elsewhere. The 64 GB runs use a development build of vLLM.

The worked number: at 8K on the 24 GB card, 832.69 / 85.80 = 9.7 times more tokens per second. At 16K the original runs out of memory; TransMLA gives 414.41 tokens per second.

Why does the gain grow with context? Each decode step reads the whole cache. A cache of 8,192 tokens is 8,192 × 512 KiB = 4 GiB for the original. For TransMLA it is 8,192 × 36 KiB = 288 MiB, 14.2 times less. The longer the context, the larger that read is next to the fixed work.

More memory gives a smaller gain. At 32K the ratio is 6.4 times on the 40 GB card and 5.0 times on the 64 GB card. The abstract's 10.6 times comes from Figure 5, at 8K on the 24 GB card, for the version that also compresses queries (low-rank Q = 512). Table 4 gives 9.7 times for that cell and does not say which query version it ran.

Failure. You test at 1K on a big card and see 1.4 times. That card was not short of memory at 1K. Measure at the context lengths you serve. Fix: compress for long-context traffic.

Why does TransMLA's speed-up grow with context length?

Chapter 8

Read Fewer Tokens

Score every cached token cheaply, then run real attention on the best 2,048

A small cache does not change how many tokens each step scores: at step t, dense attention scores all t earlier tokens. DeepSeek-V3.2 runs at 128K context. Its only architecture change over DeepSeek-V3.1-Terminus is DeepSeek Sparse Attention (DSA), added by continued training.

DSA has two parts. A lightning indexer gives each earlier token s a cheap score It,s. Then top-k selection keeps the k best, and MLA attention runs over those only. The indexer has HI heads; each has a query and a weight from token t, and token s has one key.

Say it aloud

I t s equals the sum over j from 1 to H-I of w-I t j times ReLU of q-I t j dot k-I s.

It,s
I t s the index score: how much token t should read earlier token s.
Σj=1HI
the sum over j from 1 to H-I add one term per indexer head; HI = 64 in the released config.
wIt,j
w-I t j a weight for head j, computed from token t.
ReLU
ReLU keep a positive number, turn a negative one into 0.
qIt,j
q-I t j head j's indexer query from token t: 128 numbers.
kIs
k-I s token s's indexer key, shared by all heads: 128 numbers.
In plain words

For each indexer head j, take the dot product of token t's query with token s's key. Turn a negative result into 0. Multiply by the head's weight and add over heads to get I t s. Keep the k tokens with the largest scores.

With numbers

With made-up numbers: two heads, q1 = [1, 0], q2 = [0, 1], w = [0.5, 1], ks = [2, −1]. The dot products are 2 and −1. ReLU gives 2 and 0. I = 0.5 × 2 + 1 × 0 = 1.0.

The paper picks ReLU for speed and runs the indexer in FP8, an 8-bit format.

Pick the tokens to read

Green dots mark the tokens this query needs. Compare a window of the last k with the indexer's top k.

6

Illustrative scores and needs. At real size DSA keeps k = 2,048 of up to 131,072 tokens.

Count the work over a sequence of L tokens. Each token reads all earlier tokens until there are k, then exactly k. Call the total PDSA.

Say it aloud

P-DSA equals k times k plus one over two, plus L minus k, times k.

PDSA
P-DSA query-key pairs the main attention scores over the whole sequence.
k(k + 1)/2
k times k plus one over two the first k steps read everything: 1 + 2 + ... + k.
(L − k)
L minus k the steps after the first k; L is the sequence length.
k
k tokens kept per step: 2,048.
In plain words

The first k steps read every earlier token. Each of the L minus k later steps reads k. Add both parts. Dense attention reads L times L plus one over two.

With numbers

L = 131,072 and k = 2,048: 2,098,176 + 129,024 × 2,048 = 266,339,328 pairs. Dense: 131,072 × 131,073 / 2 = 8,590,000,128. That is 32.3 times fewer; the last step alone reads 64 times fewer.

The indexer still scores every pair, but far more cheaply than MLA (section 2.3). The paper plots cost per million tokens on H800 GPUs (Figure 3), not one speed-up.

Failure. A short chat gets no faster: below 2,048 tokens top-k keeps everything, and the indexer still runs. Measure cost at your real lengths. Fix: a dense path for short sequences, as DeepSeek uses for short prefill.

What does DSA reduce, and what does it leave the same?

Chapter 9

Train the Indexer

Teach the indexer to copy the model's own dense attention, in two stages

The indexer needs a target: which earlier tokens should token t read? The model already answers that. Its dense attention says it.

Dense warm-up. Start from DeepSeek-V3.1-Terminus, already extended to 128K. Keep dense attention and freeze everything except the indexer. For token t, add the main attention weights over all heads and divide by their total. Call that target pt,:, and the indexer's scores for token t It,:.

Say it aloud

L-I equals the sum over t of the K-L divergence between p-t and the softmax of I-t.

LI
L-I the indexer's loss.
Σt
the sum over t add one term per query token.
DKL
the K-L divergence add p times the log of p over the indexer's probability, over earlier tokens. It is 0 when they agree.
pt,:
p-t the target: dense attention summed over heads, made to add up to 1.
Softmax(It,:)
the softmax of I-t the indexer's scores turned into probabilities.
In plain words

Turn token t's index scores into probabilities. For each earlier token, multiply p-t by the log of p-t over that probability, and add. Add that over all t to get L-I. The indexer lowers L-I by moving its weight to where dense attention puts it.

With numbers

With made-up numbers: p = [0.7, 0.2, 0.1]. A flat indexer, [0.34, 0.33, 0.33], scores 0.29 nats. A trained one, [0.65, 0.22, 0.13], scores 0.0066 nats, 43 times lower. The 0.7 term is most of the loss: it cares most where attention is strongest.

Train toward dense attention

Blue outlines: dense attention over 8 earlier tokens. Teal bars: the indexer. Press Train. In the sparse stage the loss compares only the indexer's top 3.

Toy target and learning rate. Each step moves the indexer's scores by the softmax minus the target, the exact gradient of this loss.

StageTrainsAttentionSteps × batchTokensLearning rate
1. Dense warm-upindexer onlydense1,000 × 16 of 128K2.1B10−3
2. Sparse trainingeverythingtop 2,04815,000 × 480 of 128K943.7B7.3 × 10−6

In stage 2 the KL runs over the selected set only. The paper detaches the indexer's input: the indexer learns only from its KL loss, the main model only from the language-modelling loss.

Did quality hold? DeepSeek-V3.2-Exp shows similar benchmark scores to V3.1-Terminus and closely matched ChatbotArena Elo. On AA-LCR, an independent long-context test, it scores 4 points higher in reasoning mode (section 2.2).

Failure. If the KL gradient reached the main model, the model could bend its attention to be easy to copy. Measure: check that the indexer's input carries no gradient back. Fix: detach it, as the paper does.

Why does the warm-up keep dense attention and freeze the main model?

Chapter 10

Field Guide

Keep the terms, the numbers, the code and the open questions in one place

TransMLA rewrites a trained GQA or MHA layer as MLA with selector up-projections, which changes nothing. It rotates the heads so one head carries position, balances keys against values, and compresses both with PCA. A short fine-tune recovers the score. DSA attacks the other cost: a trained indexer picks 2,048 tokens for each step to read.

TermMeaningNumber to remember
GQA group maphead i reads group ⌈i / (h/g)⌉g = h is MHA, g = 1 is MQA
Head mergelatent = all keys and values; selector up-projectionscache unchanged, 2gd
Expressive orderat equal cacheGQA < MLAFactorized < MQA
RoRoPE, FreqFoldPCA per frequency puts position in one headlog-ppl about 2 vs nearly 6 at 90% removal
BKVdivide NoPE keys by α before joint PCAoutput unchanged
Ladder (Llama 2 7B)kept per layer of 8,1922,560, 1,024, 576
Scoressix-benchmark average, original 59.8558.20 untrained at −68.75%; 58.68 at −92.97% after 6B
Rival, untrainedMHA2MLA at −68.75%37.90
ThroughputvLLM, 24 GB card, 8K85.80 to 832.69 tokens/s (9.7×); Figure 5: 10.6×
Lightning indexerReLU score per head, weighted sum, FP864 heads of 128 numbers
Top-ktokens main attention reads per step2,048 of up to 131,072; 32.3× fewer pairs
Indexer trainingKL to summed dense attention; detached input2.1B warm-up, 943.7B sparse
LeverWhat shrinksWhat staysRelieves
Latent (MLA, TransMLA)numbers stored per tokenevery token is still readGPU memory and bytes read
Sparse (DSA)tokens read per stepevery token is still storedattention work at long context

Checklist

  1. Check the merge first: rebuilt keys and values must equal GQA's exactly.
  2. Use one rotation per frequency on both halves of each RoPE pair; check scores at two positions.
  3. Balance keys against values before the joint PCA, and run PCA on activations.
  4. Pick the rung from your training budget: none, 500M, 3B or 6B tokens.
  5. Measure speed at the context lengths you serve, on the card you serve.
  6. For sparse attention, detach the indexer and keep a dense path for short sequences.
  7. Quote a score as the result of the whole recipe, not of one piece.
pythonimport torch

def selector(i, h, g, d):                       # head i (0-based) copies group j
    j = i // (h // g)
    W = torch.zeros(d, g * d); W[:, j*d:(j+1)*d] = torch.eye(d)
    return W

h, g, d = 32, 8, 128
cK = torch.randn(g * d)                           # the key half of the merged latent
assert torch.equal(selector(4, h, g, d) @ cK, cK[d:2*d])   # exact copy of group 1

def balanced_pca(K_nope, V, r_kv):                  # rows = calibration tokens
    alpha = K_nope.norm(dim=1).mean() / V.norm(dim=1).mean()
    X = torch.cat([K_nope / alpha, V], dim=1)
    X = X - X.mean(0)
    U, S, Vh = torch.linalg.svd(X, full_matrices=False)
    return Vh[:r_kv].T, alpha                       # basis R_KV and the factor

def index_scores(qI, wI, kI):                     # qI (H, dI), wI (H,), kI (L, dI)
    return (wI[:, None] * torch.relu(qI @ kI.T)).sum(0)   # (L,)

def pairs(L, k):                                   # main-attention pairs per sequence
    return L * (L + 1) // 2, k * (k + 1) // 2 + (L - k) * k
print(pairs(131072, 2048))   # (8590000128, 266339328): 32.3x fewer

What the papers leave open

TransMLA calls its balancing step "relatively trivial" and asks for better tools that would make conversion work with no training at all. It tests two models, SmolLM 1.7B and Llama 2 7B, and asks for wider checks. It also suggests combining with pruning, quantization and token selection, which is DSA's lever, but it does not try. DeepSeek-V3.2 reports cost curves and parity checks, not an ablation of the indexer's size.

Keep going

Credit: Session 9 of Georgia Tech CS 8803, LLM seminar. Papers: TransMLA (Meng et al., 2025, arXiv 2502.07864, checked against v5) and DeepSeek-V3.2 (DeepSeek-AI, 2025, arXiv 2512.02556, section 2, checked against v1). The indexer's 64 heads of 128 numbers come from the released DeepSeek-V3.2-Exp config. The toy keys, clouds and targets are ours.

The takeaway. Before you retrain, ask whether the old model is already a special case of the new one. If it is, write it in the new form exactly, then compress and fine-tune from there.

Teach it back: open Present or Teach and explain the head merge and RoRoPE to a friend. Then go back to the converter and predict the −87.50% score with no training before you press it.

CS 8803 LLM Seminar, Session 09: TransMLA and Sparse Attention
TransMLA paper · DeepSeek-V3.2 paper · Back to Gleams