Rúben GalvãoThe Rabbit Hole

The Rabbit Hole / AI and machine learning / Language models / Remembering context efficiently

Heavily compressed attention (HCA): keeping a compressed history

Keep recent tokens individually, learn what to preserve from each older block, and discover heavily compressed attention.

Multi-query attention (MQA) lets all query heads read the same keys and values. We no longer keep a separate cache for every head. But that shared cache still adds a key and a value for every token. A later query can request information from any of them; the stored list keeps growing.

Sliding-window attention bounds that list by keeping only the newest tokens. As a new entry arrives, the oldest leaves. Memory stays bounded, but information from outside the window is no longer available to that attention layer.

Could we keep the recent window at full resolution, and retain a compressed view of the older history? We would still lose detail about older tokens, but we would no longer discard their information entirely.

A window with a longer view

Compare the three caches as the same tokens arrive. The third keeps a 128-token recent window and builds one compressed entry per 128-token block.

Full attention, sliding window, and sliding window with compressed historyFull attentionSliding-window attentionRecent detail + compressed historyCompressed historyRecent windowCompression workspaceEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.127 entries512Earlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.127 entries512Older entries discardedEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.127 entries512No completed entriesEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.127 × 2 × 512

New tokens fill the recent window and the compression workspace.

Three cache choices as groups of 16 new tokens arrive. Each column is an entry; table dimensions show entry count × coordinate width. The smaller workspace holds content and scores until a complete block produces one compressed entry.

The compressed entry is ready just before its oldest individual entry leaves the window. When a block reaches 128 tokens, it produces one compressed entry. When the next token arrives, the oldest individual entry leaves the window, but its contribution remains in the compressed history. The same pattern repeats for each block.

This gives older history a cheaper representation while preserving individual access to recent tokens. There is some overlap: a compressed entry is available while many of its source tokens are still in the window. We do not wait for the entire block to become old before storing its summary.

Try combining the entries

We have made room for compressed history, but have not yet decided what to put in it. The simplest attempt is to average the entries in each block. Here is that operation with just two entries:

pool averageTwo separate entries2860Average the entries4422Reverse their order6028Average the entries4422
Both orders produce [4, 4]. Averaging has saved an entry, but the later query cannot tell these two histories apart from that average alone.

We have saved an entry, but both orders now look identical. Averaging also forces every position to contribute equally: a useful feature from one token can be diluted by all the others. Keeping the recent window protects local detail; it does not solve what to preserve in the compressed history.

Let some contributions matter more

Could we change the mixture? Rather than taking half of every coordinate from each entry, we could give a larger share to one and a smaller share to the other. Different coordinates could favour different positions:

pool exampleEntry 1Amounts280.750.25×1.52Entry 2Amounts600.250.75×1.50+32222
Multiply coordinate by coordinate, then add the products: [1.5, 2] + [1.5, 0] = [3, 2]. The amounts are calculated data and sum to 1 across positions for each coordinate.

The amounts in this example illustrate the operation; choosing them by hand would not work for arbitrary text. We need the model to calculate them from the incoming representations.

A learned projection can produce a score for each coordinate at each position. Softmax across the positions turns those scores into contribution amounts that sum to 1. Now training can change which features survive the mixture. This score projection is the matrix labelled Wg below.

The average also lost order. If the score depends only on a token’s representation, it has no explicit indication of that token’s place within this compression block. Adding a learned bias for each block position gives the mixture that extra information.

Give compression its own content

We could use those amounts to combine the existing K/V entries. That would share the recent window’s projection with compression. But the same representation would have to serve two purposes: remain useful as an individual entry, and remain useful after being mixed with many others.

Could we let the model prepare content specifically for that mixture? A separate learned projection gives it that freedom. It reads the same incoming representation as the recent-window projection, but can learn different features to retain through compression. This is Wc, the content projection. The window keeps its own key and value projections.

We now have two things to calculate for each incoming token: what it can contribute, and how strongly each coordinate contributes. Multiply the content by those amounts, then add across positions. That gives us learned pooling:

pool blockBuild one compressed entry128WcWgContentScores+Position bias128Softmax over 128Contribution amounts×Weighted contentAdd 128 positionsEarlier context is dimmed; outlined columns are current.Current token computation.Pooled contentRMSNormRoPEEarlier context is dimmed; outlined columns are current.Current token computation.Compressed entry7,1687,1681287,168128128128128128128128128
The non-overlapping pooling pattern used by HCA: project content and gate scores, add learned position biases, normalise scores across the 128 positions, multiply and sum. The compressed entry is then normalised and given position information.

The block becomes one 512-coordinate entry. RMSNorm controls its scale, and position information gives it a place in the sequence. It can then provide information to future attention reads.

This is still a compromise. Learned contributions and a separate content projection can change what survives, but they cannot preserve every distinction between the original entries. And pooling happens before future queries arrive, so it cannot tailor each summary to what those queries will ask.

Prepare the summary while keeping recent detail

We want the compressed entry ready when individual entries begin leaving the recent window. Each arriving token can therefore feed both paths: keep its individual K/V entry, and calculate its content and scores for the compression workspace.

Once that workspace holds a complete block, we can finish the mixture, store the compressed entry, and clear the workspace for the next block. The recent window continues to slide independently.

Before drawing those projections, there is one further saving we can make. MQA shares keys and values across heads, but still stores a separate key and value for each position. Could the same vector serve both roles? That is the shared K/V representation: one entry to score as a key and collect as a value. DeepSeek-V4 uses it for both recent entries and summaries. It makes each stored position cheaper; compression reduces how many positions we keep.

The next diagrams use that storage choice. Wkv makes the recent entries, while Wc and Wg prepare the compression content and scores. The learned position bias feeds pooling alongside the buffered content and scores:

Every token enters both histories; full blocks emit compressed entriesNew token representationEarlier context is dimmed; outlined columns are current.Current token computation.WkvWcWgRecent individual K/V entriesPooling buffer: content + scoresEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.Earlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.127 individual entries127 / 128 records in the next blockPool 128 records → 1 entryPosition bias128Compressed historyNo completed block yetCompleted summaries: 07,1687,1681287,1681287,168128entry width: 128content + scores: 2 × 128128128

The first block is one token short. No compressed entry exists yet.

Every token feeds both paths. A full 128-token block produces a compressed entry; the recent window keeps individual entries until they slide out. The recent path shares its key and value projection (Wkv). The position-bias weights feed the pooling operation. The animation follows a block filling and the next tokens arriving. Hover or focus to pause.

Read the recent entries and the summaries together

A query now has two kinds of entry available. It can request information from individual recent tokens, or from a compressed entry that combines a whole block. We can put both into the same attention read: score them together, apply one softmax, and collect a weighted mixture of their values.

Just after the first window advance, that means 128 individual entries and one summary. The newest token has no summary yet because its block is unfinished. The completed summary remains available, although its source tokens cannot be retrieved separately from it.

With S completed summaries, the combined history contains S + 128 entries, each still 512 coordinates wide. We join along the positions, not the feature dimension.

Join the recent window and compressed history along the token axisCompleted summariesEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Recent windowEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.S entries128 entriesEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Earlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.S + 128 entriesOne history available to attention128128
Place completed summaries before the recent entries. Joining the histories adds positions, not coordinates: every entry is still 512 wide.

Joining the two histories does not require a new kind of attention read. The query forms an attention map over the combined keys. One softmax gives contribution amounts across both histories, and those amounts weight the combined values. Since this model shares K/V representations, the same combined entries supply both roles:

One query head reads recent and compressed entries with ordinary attentionQuery / headEarlier context is dimmed; outlined columns are current.Current token computation.Combined entries (K = V)Earlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Earlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.S + 128 entriesAttention mapS + 128 keysSame history as V×Earlier context is dimmed; outlined columns are current.Current token computation.Collected result / head192128128
The same combined history supplies K and V. Each query head forms its own attention map; the highlighted last row weights both recent and compressed values.

The recent window and unfinished workspace stay bounded. The summary list keeps growing by one entry per 128 tokens. We have reduced memory growth, rather than produced linear attention’s fixed-size state.

This combination—a recent window plus a learned summary for every 128-token block—is Heavily Compressed Attention (HCA) in DeepSeek-V4. Each query can read every completed summary alongside the recent individual entries.

Put the query heads back in

As in MQA, every query head reads the same stored history. Each has its own query, attention map and collected result; we share the cache, not the requests made to it. The full diagram adds those heads and the input and output projections around the cache and read we just built.

The query and output projections are factorised in DeepSeek-V4. On the output side, grouping alone preserves the width. In Flash, 64 heads × 512 coordinates = 32,768, split into 8 groups of 4,096. Each group’s Woa projects 4,096 → 1,024. Concatenating those smaller results gives 8 × 1,024 = 8,192 coordinates, which Wob projects back to the 4,096-coordinate token width. The DeepSeek-V4 model architecture develops these factorised projections.

What if a head has little useful information to collect? Softmax would still divide all its attention among the available entries. DeepSeek-V4 gives each head one learned sink score, labelled Sink score / head below. It joins the softmax alongside the query–key scores, but supplies no value to collect. Attention assigned to it therefore reduces the total weight given to the cached values. The sink is a learned scalar, so it uses the violet weight colour.

Complete HCA attention with shared caches and per-head readsNew token representationEarlier context is dimmed; outlined columns are current.Current token computation.4,096Wqa4,0961,024Wk = Wv4,096512Wc4,096512Wg4,096512RMSNormRMSNormEarlier context is dimmed; outlined columns are current.Current token computation.1,024Shared query latentRoPEShared recent entriesEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.128 entries512Earlier context is dimmed; outlined columns are current.Current token computation.512ContentEarlier context is dimmed; outlined columns are current.Current token computation.512ScoresCompression workspace128 × 512128 × 512+Position bias128512Softmax over 128512×Add 128 positionsRMSNormRoPEShared compressed entriesEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.51264 headsWqb / head1,024512RMSNormRoPEEarlier context is dimmed; outlined columns are current.Current token computation.512q / headRecent + compressedEarlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Earlier columns are cached; outlined columns are newly computed.Cached positions from earlier decoding steps.Current token computation.128 + S entriesAttention map / head128 + S keysOne learned scalar per head joins the softmax denominator. Its attention weight contributes no value to the result.Sink score / head×Same entries as VEarlier context is dimmed; outlined columns are current.Current token computation.512Inverse RoPEEarlier context is dimmed; outlined columns are current.Current token computation.512Head resultConcatenate head resultsEarlier context is dimmed; outlined columns are current.Earlier context is dimmed; outlined columns are current.Earlier context is dimmed; outlined columns are current.Earlier context is dimmed; outlined columns are current.Current token computation.51264 heads64 × 512 = 32,768Split into 8 groups8 heads × 512 = 4,096 / group8 groupsWoa / group4,0961,024Earlier context is dimmed; outlined columns are current.Current token computation.1,024Projected group resultConcatenate group resultsEarlier context is dimmed; outlined columns are current.Earlier context is dimmed; outlined columns are current.Earlier context is dimmed; outlined columns are current.Earlier context is dimmed; outlined columns are current.Current token computation.1,0248 groups8 × 1,024 = 8,192Wob8,1924,096Earlier context is dimmed; outlined columns are current.Current token computation.4,096Attention output
The full HCA attention path: shared projections, compression and caches outside the head stack, then separate query-head reads and grouped output projections.

We have kept a longer view without storing every earlier token individually. The remaining limitation is the mixture itself: a later query may need a distinction that did not survive 128-to-1 compression. Could we keep more detail without reading every entry?

Sources and assumptions

The numeric pooling examples use two coordinates. The worked Pro and Flash diagrams use 128-position blocks and 512-coordinate entries. Content and scores for the unfinished block are buffered separately from the readable cache. Recent entries and summaries overlap; individual entries leave only when the local window advances. The model ties K and V, but sequence compression and that storage choice are separate ideas.

← Browse all subjectsBack to the beginning ↑