Two 2024 papers push a wide representation through a small learned latent. DeepSeek-V2 caches 34,560 numbers per token where standard attention caches 1,966,080, and still scores higher. NV-Embed pools a whole document through a 512-entry learned dictionary.
Pick an attention type, then drag the traffic. Watch how many GPUs the cache alone fills. Then we build, piece by piece, the cache count, the latent, the decoupled position key, and NV-Embed's pooling and training.
You need a little Python and what a matrix product is. We build the rest from zero.
Session 3 of Georgia Tech CS 8803, LLM seminar. It rests on two papers: DeepSeek-AI, DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (2024), and Lee, Roy, Xu, Raiman, Shoeybi, Catanzaro and Ping, NV-Embed: Improved Techniques for Training LLMs as Generalist Embedding Models (ICLR 2025). Every idea is re-taught here in our own words and devices.
Cache counts are the formulas of DeepSeek-V2 (Table 1) on its own shape: 60 layers, 128 heads of 128 numbers, latent 512, RoPE key 64; GQA at 8 groups as in its Table 8. The paper counts numbers; bytes here assume 2 per number (BF16), and 1 GB = 1,024 MB. The labels Strong, Moderate, Weak and Stronger are the paper's Table 1.
Chapter 0
See why serving a chat model runs out of memory before it runs out of compute
You serve DeepSeek-V2: 236 billion parameters, of which 21 billion work on each token, with a 128K-token context. Users open long chats and paste long files. One number on your dashboard climbs faster than all the others. It is not the weights.
To write token t, attention needs a key and a value vector for every earlier token, in every layer. Recomputing them at every step would waste work, so the server stores each pair once. That store is the KV cache. Each open chat has its own, and it grows by one token at every step.
Serving has two phases. Prefill reads the whole prompt in one parallel pass and builds the cache. Decode then writes one token at a time, and each step reads the entire cache back from GPU memory. Decode does about one multiply per number it reads, so memory traffic, not arithmetic, sets its speed.
Each column is one cached token, as tall as its cache. Press Step: the new token reads every column. Switch the attention type and step again.
Per-token cache from DeepSeek-V2's shape at 2 bytes per number: 3.75 MB for MHA, 67.5 KB for MLA. The 20-token chat is illustrative.
How big does the cache get? Name four things. The numbers cached per token, across all layers: C. The tokens each chat holds: T. The open chats: U. The bytes per number: b.
M equals C times T times U times b.
Take the cache of one token, C. Multiply by the tokens in a chat, T, and by the open chats, U. Multiply by the bytes per number, b. That is M.
Standard attention on DeepSeek-V2's shape has C = 1,966,080. With T = 4,096, U = 100 and b = 2: M = 1,966,080 × 4,096 × 100 × 2 bytes = 1,500 GB. MLA has C = 34,560 and needs 26.4 GB for the same traffic.
Turn that into users. Say 40 GB of a GPU is free for cache and each chat holds 2,048 tokens. Under standard attention a chat costs 2,048 × 3.75 MB = 7,680 MB, so 40,960 / 7,680 = 5 chats fit. Under MLA a chat costs 135 MB, so 303 fit.
Failure. The server rejects new chats while the GPU's compute sits idle. Measure: cache per token times live tokens, against free memory. Fix: store fewer numbers per token. Storing each number in fewer bits helps 2 to 4 times; changing what you store helped 57 times here.
Chapter 1
Derive what standard attention stores per token, and what head sharing saves
A token enters a layer as a hidden state h, a vector of d = 5,120 numbers in DeepSeek-V2. Multi-Head Attention (MHA) multiplies h by three learned matrices to get a query, a key and a value. It cuts each into nh = 128 heads of dh = 128 numbers. Each head scores its query against the keys of earlier tokens and mixes their values.
Each query serves one step only. Every later step needs the keys and values of past tokens, so the server caches them: one key and one value per head, per layer. Name the parts: heads nh, numbers per head dh, layers l.
C-M-H-A equals two times n-h times d-h times l.
Each head stores a key and a value of d-h numbers. Multiply by the heads, n-h, and by the layers, l. That is C-M-H-A.
2 × 128 = 256; 256 × 128 = 32,768 per layer; 32,768 × 60 = 1,966,080 numbers. At 2 bytes each, one token costs 3.75 MB.
Two older fixes share keys between heads. Grouped-Query Attention (GQA) splits the heads into ng groups; every head in a group uses one key and one value. Multi-Query Attention (MQA) is one group for all. The formula keeps its shape with ng in place of nh.
Each dot is one of 128 query heads. Dots of one colour share a key and a value. Drag the groups and watch the cache count.
Counts from 2 × ng × 128 × 60 on DeepSeek-V2's shape. Accuracy figures: the paper's Table 8 (7B dense models, 1.33T tokens).
| Type | Keys per layer | Cache per token | MMLU (Table 8) |
|---|---|---|---|
| MHA | 128 | 1,966,080 | 45.2 |
| GQA, 8 groups | 8 | 122,880 | 41.2 |
| MQA | 1 | 15,360 | 37.9 |
Failure. You switch to MQA and the cache drops 128 times, but hard benchmarks drop too. Measure: compare on hard tasks, not perplexity alone. Fix: keep each head's view and shrink how you store it. That is the next chapter.
Chapter 2
Compress each token into one small vector, then fold the expansion into the query weights
MHA caches 256 vectors per token per layer. All of them come from one hidden state h by linear maps. So store something smaller that the keys and values can be rebuilt from. Multi-head Latent Attention (MLA) does this. Call the small stored vector the latent c, of width dc = 512.
c-K-V of t equals W-D-K-V times h-t.
Multiply the hidden state h-t by the down-projection W-D-K-V. Keep the 512 numbers that come out, c-K-V of t, in the cache.
With made-up numbers at toy size: h = [1, 0.5, −0.5, 0.2] and WDKV = [[1, 1, 0, 0], [0, 0, 1, 1]]. Then c = [1 + 0.5, −0.5 + 0.2] = [1.5, −0.3]. Four numbers in, two stored.
When attention runs, an up-projection WUK rebuilds the key: k = WUK c. A second one, WUV, rebuilds the value. Each is 16,384 rows by 512 columns. In the toy, WUK = [[1, 0], [1, 0], [0, 1], [0, 1]] gives k = [1.5, 1.5, −0.3, −0.3].
Rebuilding every past key at every step would cost a lot. MLA never does it. The score is a query times a key, and you can regroup a matrix product.
q-transpose k equals q-transpose times W-U-K c, which equals q-transpose W-U-K, times c.
Instead of building each key k from its latent c, multiply the query by W-U-K once. Then score that fused query straight against every cached c. Because the query weights also feed q, the paper folds W-U-K into them before serving ("absorbs" it). W-U-V folds into the output weights the same way.
With made-up q = [2, 1, 2, 1]. Route one: k = [1.5, 1.5, −0.3, −0.3], and q · k = 3 + 1.5 − 0.6 − 0.3 = 3.6. Route two: qTWUK = [3, 3], and [3, 3] · [1.5, −0.3] = 3.6. Same score, and route two built no key.
Drag the cached latent's two numbers. Top: rebuild the key, then score. Bottom: fuse the query once, then score the latent. Pick a query and compare.
Toy sizes and made-up weights. The real-size counts per cached token and head are exact arithmetic: rebuilding a 128-number key from a 512-number latent takes 65,536 multiply-adds; the fused score takes 512.
MLA also compresses the query, to width dc′ = 1,536. Queries are never cached, so this saves activation memory in training, not cache.
Failure. The memory saving never shows up. Measure: print the shape of what goes into the cache; it must be 512 numbers per layer, not 16,384. Fix: append c to the cache, never the rebuilt k or v.
Chapter 3
See why a rotation blocks the fused query, and carry position in a small separate key
DeepSeek-V2 uses RoPE (Rotary Position Embedding). It rotates each query and key by an angle set by the token's position. Their product then depends on the distance between them. The RoFormer lesson builds it from zero.
Put RoPE on MLA's rebuilt key and the rotation lands between WUK and the query. The rotation depends on the token being written now, and matrix products do not commute. So the server can no longer fold WUK in ahead of time. It must rebuild every past key at every step. The paper says this outright.
The fix is a decoupled key. The content part stays as Chapter 2 built it, with no position. A second, small part carries RoPE. It is a key kR of dhR = 64 numbers, computed from h and shared by all 128 heads. Each head also gets a 64-number RoPE query.
Each head joins its content part and its RoPE part end to end. The cache holds the latent and the shared RoPE key.
C-M-L-A equals, d-c plus d-h-R, times l.
In each layer, store one latent of d-c numbers and one RoPE key of d-h-R numbers. No head count appears. Multiply their sum by the layers, l.
(512 + 64) × 60 = 576 × 60 = 34,560 numbers, or 67.5 KB at 2 bytes. MHA's 1,966,080 / 34,560 = 56.9 times more. GQA would match it with 34,560 / (2 × 128 × 60) = 2.25 groups, a group count GQA cannot use.
Drag the number of cached tokens. With RoPE on the rebuilt key, every one must be rebuilt at each step. Switch to the decoupled key.
Rebuild work per layer per step: cached tokens × 16,384 × 512 multiply-adds, exact arithmetic on DeepSeek-V2's shape. The cache split is (512 + 64) per layer.
The joined query and key are now 128 + 64 = 192 numbers wide, so the paper scales scores by √192 ≈ 13.86, not √128 ≈ 11.31. The split pays a second time. DeepSeek-V2 stretches its context from 4K to 128K with YaRN, a rescaling of RoPE angles, and applies it only to kR.
Failure. Your port runs, but its scores are 22% too large and quality slips. Measure: compare attention logits with a reference on one batch. Fix: divide by √(dh + dhR).
Chapter 4
Read the paper's two ablations, then keep the production numbers apart from them
A small cache means nothing if answers get worse. MQA is smaller still and it lost 7.3 MMLU points. The paper's Appendix D trains models that differ only in attention and scores them on four hard benchmarks: BBH, MMLU, C-Eval and CMMLU.
Pick a comparison. Bars are the paper's scores; the strip on top is the cache per token. Look for the one cell where MLA loses.
DeepSeek-V2 (arXiv v5), Table 8: dense models of about 7B parameters, 1.33T tokens, sizes matched by layer count. Table 9: small MoE (15.8B and 15.7B total) on 1.33T tokens; large MoE (250.8B and 247.4B total) on 420B tokens. Table 8 gives no cache sizes.
Two readings. In Table 8, MHA beats GQA and MQA on all four benchmarks: head sharing costs quality. In Table 9, MLA beats MHA on every benchmark at large scale, and on three of four at small scale. At small scale, C-Eval is 50.9 for MLA and 51.6 for MHA.
The worked number. The large models cache 860.2K numbers per token with MHA and 34.6K with MLA. 860.2 / 34.6 = 24.9 times smaller, or 4% of MHA's cache. At small scale it is 15.6 / 110.6 = 14%. These ablation models have their own shapes, so their counts differ from the 1,966,080 of Chapter 1.
The paper also reports the shipped system against its older dense model, DeepSeek 67B. DeepSeek-V2 cuts the KV cache by 93.3% and reaches 5.76 times the top generation throughput. That is over 50K tokens per second on one node of 8 H800 GPUs. That deployment also stores weights in FP8 and quantizes the cache to about 6 bits per number.
| Kind of number | Example | What it isolates |
|---|---|---|
| Derived | 34,560 numbers per token | arithmetic on a fixed shape |
| Ablation | 24.9× smaller, higher scores (Table 9) | attention type only |
| Production | 93.3% less cache, 5.76× throughput | nothing: MoE, MLA, FP8 and cache quantization together |
Failure. A slide credits MLA alone with the 5.76 times speed-up. Measure: ask what else changed between the two systems. Fix: quote Table 9 for MLA's effect and the deployment number for the whole system.
Chapter 5
Pool a sequence of token vectors through a small learned dictionary before you average
New problem. You build search over a million documents. Each document and each query must become one vector, so that cosine similarity can rank documents. Session 2 showed why a decoder LLM such as Mistral 7B makes a strong embedder. But it outputs one vector per token. Pooling turns that sequence into one vector.
| Pooling | Rule | Weakness (paper's words) | MTEB (Table 2) |
|---|---|---|---|
| <EOS>-last | take the last token's vector | recency bias | 67.85 |
| Mean | average every token's vector | dilutes key phrases | 68.97 |
| Self-attention | one more self-attention layer, then mean | adds little to a model that has many | 69.10 |
| Latent attention | attend to a learned dictionary, then mean | an extra layer to run | 69.32 |
NV-Embed's latent attention layer works like this. The decoder's last-layer vectors form a matrix Q: one row per token, l rows of d = 4,096 numbers. A trainable matrix of r = 512 rows serves as both keys K and values V. The paper calls it a dictionary.
O equals softmax of Q K-transpose, times V.
Score each token row of Q against every dictionary entry. Turn each row of scores into weights with softmax. Replace the token by the weighted mix of entries from V. The paper then runs a small MLP (two linear layers, GELU between) and averages the rows of O.
With made-up numbers: one token [1, 0], entries [2, 0] and [0, 2]. Scores: [2, 0]. Softmax: e2 / (e2 + 1) = 0.88 and 0.12. Output row: 0.88 × [2, 0] + 0.12 × [0, 2] = [1.76, 0.24]. The token now leans on entry one.
Orange arrows are the tokens; two are filler. Purple dots are three dictionary entries. Pick a pooling rule, then sharpen the dictionary match.
Illustrative 2-number toy: made-up tokens and entries, one head, no MLP. Sharpness multiplies the scores. The real layer: 512 entries of 4,096 numbers, 8 heads, then an MLP (paper Section 3.2, Table 11).
Failure. Long documents with one key sentence rank low. Measure: retrieval score on a split with buried answers. Fix: a pooling rule that can weight content; on the paper's 15 retrieval tasks latent attention scores 59.36, mean 58.71 and self-attention 58.64.
Chapter 6
Remove the causal mask so every token reads the whole document
A decoder LLM trains with a causal mask: token i may attend only to tokens 1 to i. That keeps next-token prediction honest. An embedder predicts nothing; the whole document is already there. Under the mask, token 5 of 50 never learns what tokens 6 to 50 say.
NV-Embed removes the mask during contrastive training, and every token attends to every token. Other work adds more: LLM2Vec trains an extra masked-token phase first, and GRIT mixes two objectives. NV-Embed reports that the plain switch works well.
How much does the mask hide? Name the sequence length N. Row i of the attention grid shows i cells out of N.
f of N equals one half plus one over two N.
Count visible cells: 1 + 2 + … + N = N(N + 1) / 2. Divide by all N × N cells. The result is f of N.
N = 10: 55 of 100 cells, f = 0.5 + 0.05 = 55%. N = 512, NV-Embed's length cap: f = 0.5 + 0.001 = 50.1%. Token 1 sees 1 of 512 tokens.
Rows are tokens reading; columns are tokens read. A lit cell means the row's token may read the column's token. Switch the mask, then grow the sequence.
The grid is exact for any Transformer with these masks. The gains are NV-Embed Table 2, stage 2, MTEB average over 56 tasks.
| Pooling | Bidirectional | Causal | Gain |
|---|---|---|---|
| <EOS>-last | 67.85 | 66.50 | +1.35 |
| Mean | 68.97 | 68.13 | +0.84 |
| Latent attention | 69.32 | 68.47 | +0.85 |
| Self-attention | 69.10 | 68.16 | +0.94 |
Every pooling rule gains from the switch, by 0.8 to 1.4 points. The best pair, latent attention with no mask, is NV-Embed-v1's 69.32.
Failure. Offline tests look fine, but live retrieval is worse. Measure: check that the serving code builds the same attention mask as training. Fix: one config flag for the mask, shared by both paths.
Chapter 7
Use free in-batch negatives for retrieval, then switch them off when they start to lie
NV-Embed trains with a contrastive loss: pull a query toward its right document, the positive, and push it away from wrong ones, the negatives. The contrastive learning Gleam builds the loss. Each example is an instructed query, one positive and 7 hard negatives (wrong documents that look right). A batch holds 128 examples.
The query gets a task instruction; documents get none. The instruction tokens are masked out of the pooled vector, but they still shape it through attention.
In-batch negatives reuse the batch: every other query's positive becomes a negative for your query. With B queries you score B × B pairs from B passes, 16,384 pairs at B = 128. For retrieval, another query's passage is almost always wrong. For classification it may not be. How many lie? Name the batch size B and the number of classes k, all equally common.
F equals B minus one, over k.
Each query has B minus one other examples in the batch. Each one shares its class with chance one over k. Multiply: that is F.
A two-class task (True or False) with B = 128: F = 127 / 2 = 63.5. Half the free negatives tell the model to separate texts that belong together.
Rows are queries, columns are their documents; colour stripes show each class. Green is the positive. Turn in-batch negatives on, then lower the class count.
A 12-example toy batch with classes dealt in turn. The real batch is 128 (paper Table 11). The paper's argument is the same: few-class labels make in-batch negatives wrong.
So NV-Embed trains in two stages. Stage 1: retrieval data only, with in-batch and hard negatives, 20k steps at learning rate 2e-5. Stage 2: retrieval blended with classification, clustering and similarity data, in-batch negatives off, 18k steps at 1.5e-5. Training uses LoRA (rank 16) on Mistral 7B.
| Score (Table 2, latent attention) | After stage 1 | After stage 2 | Gain |
|---|---|---|---|
| Classification (12) | 73.93 | 87.35 | +13.42 |
| Clustering (11) | 45.44 | 52.80 | +7.36 |
| Retrieval (15) | 59.00 | 59.36 | +0.36 |
| Average (56) | 64.18 | 69.32 | +5.14 |
Retrieval did not suffer when in-batch negatives went off; it rose. For NV-Embed-v2 (Table 4), one stage with in-batch negatives scores 70.83, one stage without scores 71.94, and two stages score 72.31.
Failure. One mixed stage with in-batch negatives, and classification lags. Measure: per-category scores, not the average. Fix: retrieval with in-batch negatives first, then the blend without.
Chapter 8
Name what both papers do, and choose how narrow the channel can be
Both papers take something wide or long, force it through a narrow channel, and let training decide what the channel keeps. They differ on everything else.
| MLA | NV-Embed latent attention | |
|---|---|---|
| Squeezes | one token's keys and values | a whole token sequence |
| Channel | a 512-number latent, new for each token | a 512-entry dictionary, shared by all documents |
| Motive | save memory | spend a little compute for quality |
| Fixed rule it replaces | cache every head's key | average every token, or take the last |
The channel also shrinks the weights. A matrix of m rows and n columns has m × n numbers. Replace it with two thin matrices through a channel of width r.
P equals r times, m plus n.
The down matrix has r times n numbers; the up matrix has m times r. Add them: r times, m plus n. That is P, against m times n for the full matrix.
MHA's key and value matrices: 2 × 16,384 × 5,120 = 167,772,160 numbers per layer. MLA's three: 512 × 5,120 + 2 × 16,384 × 512 = 19,398,656. That is 8.65 times fewer, beside the cache saving.
How narrow can r go? That depends on how many directions the data uses. The toy below builds keys from 3 hidden directions plus noise, then keeps the best r directions.
Bars show how much of the toy keys each width keeps; the yellow line is storage. Drag the width and find the knee.
Illustrative: 40 made-up keys of 12 numbers, built from 3 directions plus small noise, compressed by the best rank-r fit (principal directions). DeepSeek-V2 chose 512 = 4 × dh; the paper does not report a sweep of widths.
A bottleneck needs training. MLA learns its matrices together with the model. Turning a trained MHA or GQA model into MLA takes extra training; Session 9, TransMLA, does that. Without data to shape the channel, a fixed rule such as GQA or mean pooling is the safer choice.
Failure. Too narrow a channel, and quality falls off a cliff. Measure: held-out quality at several widths. Fix: pick the width past the knee, as the toy shows at r = 3.
Chapter 9
Keep the terms, the numbers, the code and the open questions in one place
MLA caches one 512-number latent and one 64-number position key per token per layer. It folds the key and value expansions into the query and output weights. On DeepSeek-V2's shape that is 56.9 times fewer cached numbers than MHA; in a controlled test it scored higher. NV-Embed pools a decoder's token vectors through a 512-entry learned dictionary and removes the causal mask. It trains in two stages so that free negatives never lie.
| Term | Meaning | Number to remember |
|---|---|---|
| KV cache | stored keys and values of past tokens | MHA 1,966,080 numbers (3.75 MB) per token |
| GQA, MQA | heads share keys in groups, or all share one | 122,880 and 15,360; MMLU 41.2 and 37.9 vs 45.2 |
| Latent cKV | the small vector MLA caches | dc = 512 = 4 × dh |
| Absorption | fold WUK into the query weights | score cost 512 vs 65,536 to rebuild a key |
| Decoupled RoPE | a small shared key that carries position | 64 numbers; scale by √192 |
| MLA cache | (dc + dhR) × l | 34,560 (67.5 KB); equals GQA with 2.25 groups |
| Ablation (Table 9, large) | MLA vs MHA, all else equal | 860.2K vs 34.6K; BBH 46.6 to 50.7 |
| Production | DeepSeek-V2 vs DeepSeek 67B | 93.3% less cache, 5.76× throughput |
| Latent attention layer | tokens attend to a learned dictionary, then mean | r = 512, d = 4,096, 8 heads |
| Bidirectional mask | every token reads every token | +0.84 to +1.35 MTEB |
| Two-stage training | in-batch negatives on, then off | 64.18 to 69.32; classification +13.42 |
| NV-Embed-v1, v2 | MTEB average, 56 tasks | 69.32 and 72.31 |
pythonimport torch def kv_cache_per_token(n_h=128, d_h=128, l=60, d_c=512, d_r=64, n_g=8): return {"MHA": 2 * n_h * d_h * l, "GQA": 2 * n_g * d_h * l, "MQA": 2 * d_h * l, "MLA": (d_c + d_r) * l} print(kv_cache_per_token()) # MHA 1966080, GQA 122880, MQA 15360, MLA 34560 # MLA: what one layer caches for one token, and the fused score W_dkv = torch.randn(512, 5120) # down-projection W_uk = torch.randn(128, 512) # up-projection, one head's key h = torch.randn(5120) c = W_dkv @ h # (512,) this goes in the cache q = torch.randn(128) # one head's content query assert torch.allclose(q @ (W_uk @ c), (q @ W_uk) @ c, rtol=1e-3) # absorption # NV-Embed: latent attention pooling (one head, no MLP, for clarity) def latent_pool(Q, D): # Q: (l, d) token vectors, D: (r, d) dictionary, K = V = D O = torch.softmax(Q @ D.T, dim=-1) @ D # (l, d) return O.mean(dim=0) # (d,) one vector per document
DeepSeek-V2 does not report a sweep of latent widths, so 512 is a chosen point, not a measured optimum. NV-Embed trains and tests at 512 tokens, so its pooling results say nothing about book-length text. Neither paper compares its learned channel with the best hand-tuned rule, such as IDF-weighted pooling. Nobody here tests the two ideas together.
Credit: Session 3 of Georgia Tech CS 8803, LLM seminar. Papers: DeepSeek-V2 (DeepSeek-AI, arXiv 2405.04434, checked against v5) and NV-Embed (Lee et al., ICLR 2025, arXiv 2405.17428, checked against v3). The toy vectors, batches and keys are ours.
Teach it back: open Present or Teach and explain absorption and the decoupled key to a friend. Then go back to the GPUs and predict how many MLA fills at 200 chats of 32K tokens before you drag.