Macalinao StudioLearnAll enriched lessons ↗
College path · 7 sectionsSwitch to high school ↗

College / LONGER LESSON latent

Latent attention: store a compact representation

Trace joint KV compression, verify a small projection identity, and understand positional and quality constraints.

Preparation: KV caching; vectors and matrix multiplication; weighted sums.

Plan 25–40 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.

Section 01 / 07

A latent is a learned code, not a text summary

College path. Trace joint KV compression, verify a small projection identity, and understand positional and quality constraints. Preparation: KV caching; vectors and matrix multiplication; weighted sums. Move between Signal Room, Workbench and Field Notes without losing your section. Pause before each worked solution.

A latent representation is a set of numbers learned to carry information useful for later computation. In multi-head latent attention, a token’s hidden state is projected into a smaller vector used to produce keys and values. The cache can store that compact vector instead of all expanded key-value heads. This is not summarizing a paragraph into fewer words, and it is not lossless file compression of arbitrary arrays. The model is trained to use the constrained representation. Whether it retains the needed information is an empirical question.

In column-vector notation, c_t=W_D h_t, with c_t in a lower-dimensional space. Content keys and values are K_t=W_UK c_t and V_t=W_UV c_t. The joint latent shares a source for both projections. Rank is bounded by the latent width; an arbitrary full-rank mapping cannot always be represented exactly. MLA is an architectural factorization, not a universal post-hoc compression guarantee.

Worked example. Imagine a hidden vector with four coordinates and a latent with two. A learned projection maps the four numbers into two, and separate projections turn those two into keys and values. Different inputs can map to the same latent when information is discarded. The model must learn which distinctions matter for its task.

c = W_D h; K = W_UK c; V = W_UV c

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Does storing fewer latent coordinates guarantee that every original hidden vector can be recovered?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. A lower-dimensional linear map generally loses information over the full input space. Useful learned representations need not be invertible for every possible input.

Section 02 / 07

Trace a small code into keys and values

Use a two-number latent, a and b, and define a toy key as a, b, a plus b. Define a toy value as a minus b, two times a, b. These are fixed teaching projections, not trained weights from a real model. The example lets you see exactly what is stored and what can be reconstructed. A single latent supplies both arrays. You should count its two numbers once, not twice merely because it serves keys and values. Other required cache components must still be counted separately.

Here U_K has rows [1,0], [0,1], [1,1], while U_V has rows [1,−1], [2,0], [0,1]. Both map a two-dimensional column vector into three dimensions. Their outputs lie in restricted subspaces. The toy does not include multiple heads, normalization or position encoding, so it illustrates factorization rather than the complete MLA architecture.

Worked example. For c=[2,1], the key is [2,1,3] and the value is [1,4,1]. The expanded arrays hold six numbers; the latent holds two. If c changes to [1,2], the key becomes [1,2,3] and the value becomes [−1,2,2]. Workbench lets you change both latent coordinates and inspect these exact arrays.

K=[a,b,a+b]; V=[a−b,2a,b]

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Why is the latent counted once even though two projection matrices use it?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

The same stored vector is reused by both projections. The projection weights belong to the model, while the per-token latent belongs to the cache.

Section 03 / 07

Move a projection to the query side

Reconstructing every expanded key for every new query could waste much of the benefit. Linear algebra offers another route. A query dotted with an expanded key can be rewritten by projecting the query into the latent space first, then dotting it with the stored latent. The two paths give the same score for this factorized model under exact arithmetic. This identity does not say that a newly compressed model matches an unrelated original model. It says that two ways of evaluating the same specified factorization agree.

With K=U_K c and query q, q-transpose U_K c equals (U_K-transpose q)-transpose c by associativity and transpose identities. Absorbing the up-projection into the query path can avoid reconstructing content keys. Floating-point operation order may change rounding. Position-dependent transformations require separate analysis and can obstruct a fixed absorbed projection.

Worked example. For q=[1,2,−1] and c=[2,1], the expanded key is [2,1,3]. Direct scoring gives two plus two minus three, or one. The absorbed query is [0,1], so its dot product with the latent is zero times two plus one times one: also one. Workbench calculates both routes and their difference.

qᵀ(U_K c) = (U_Kᵀ q)ᵀc

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Does agreement between these two routes prove that a rank-two model matches every rank-three model?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. It proves an identity within the chosen rank-two factorization. Model capacity and approximation quality are separate questions.

Section 04 / 07

Combine values before expanding them

Linearity also helps on the value side. If all value vectors use the same up-projection for a head, a weighted sum of expanded values equals the up-projection of the weighted sum of latents. You can therefore combine compact representations before expanding the result. The attention weights themselves still depend on queries and keys. Moving the value projection does not remove softmax or allow arbitrary reordering of nonlinear operations. This distinction helps separate valid algebraic rearrangements from changes to the model.

For fixed attention weights alpha_j, sum_j alpha_j U_V c_j = U_V sum_j alpha_j c_j. Head-specific projections must remain associated with their own attention weights. Output-projection fusion can exploit the resulting linear structure. The identity assumes the same linear U_V is used across positions in that sum; a nonlinear position-dependent map would require different reasoning.

Worked example. Take latents [2,1] and [0,3] with weights three quarters and one quarter. The mixed latent is [1.5,1.5]. Expanding it gives [0,3,1.5]. Expanding each first gives [1,4,1] and [−3,0,3]; their weighted sum is also [0,3,1.5]. Both routes can be checked coordinate by coordinate.

Σ_j alpha_j U_V c_j = U_V(Σ_j alpha_j c_j)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Can you move softmax through an arbitrary projection using the same argument?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. The argument uses linearity of a fixed value projection. Softmax is nonlinear, so the same distributive identity does not generally apply.

Section 05 / 07

Position information needs its own accounting

Word order matters. Rotary position embeddings, often called RoPE, rotate parts of queries and keys according to position. If a position-dependent rotation lies between two projections, you cannot freely swap its order with them. The original DeepSeek MLA design uses a separate positional component alongside the compressed content representation. That positional key also has to be cached. A memory estimate that counts only the latent is incomplete. The exact layout depends on the model version, so read the architecture before borrowing a number.

DeepSeek-V2 uses decoupled rotary queries and a shared rotary key. Content and positional score contributions are combined. Its per-token per-layer cache counts the KV latent width plus the positional-key width. A fixed absorption of all key computation is obstructed by position-dependent rotations because matrix multiplication is not commutative. This is an implementation constraint, not a claim that no architecture can combine compression with positional information.

Worked example. Suppose a teaching layout stores 512 latent numbers and 64 positional-key numbers, each using two bytes. The cache stores 576 numbers, or 1,152 bytes per token per layer. It is not 1,024 bytes, and it is not twice 576 numbers. The joint latent already supplies both content keys and values.

Cache bytes = L × B × N × (latent_width + positional_key_width) × bytes

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. Why must the positional key appear in the memory budget?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

It is additional per-token state required by this layout. A small content latent does not make positional information free.

Section 06 / 07

Compression width is a tradeoff, not a quality score

A larger latent can represent a wider set of linear transformations, but it uses more cache space. A smaller latent reduces storage under a fixed layout, but it may discard distinctions the model needs. These facts do not tell us a universal best width. Training data, architecture and optimization all affect quality. The Workbench budget uses illustrative widths and compares them with a dense cache. It is a transparent accounting exercise, not a reproduction of a named model’s benchmark or a promise that its outputs stay unchanged.

The rank of U W_D cannot exceed the latent dimension. This provides a structural capacity bound, not a complete prediction of nonlinear network expressivity. Compare equal precision and include positional state when computing cache ratios. Quantization scales, alignment and layer-specific layouts may add overhead. Do not confuse latent compression with fewer sequence positions or with grouping query heads.

Worked example. For thirty-two layers, 4,096 tokens, one request, a 512-wide latent, a 64-wide positional key and two-byte numbers, the payload is 144 mebibytes. A dense cache with thirty-two heads and width 128 for both keys and values is 2,048 mebibytes. Their ratio is 576 divided by 8,192, or 0.0703125. This comparison alone says nothing about answer quality.

Payload ratio = (r + d_position) / (2 H_KV d)

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. If the latent width doubles but the positional width stays fixed, does the total payload exactly double?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

No. Only the latent component doubles. The unchanged positional component means the total grows by less than a factor of two.

Section 07 / 07

Test identities, then test the trained model

Use two different kinds of evidence. First, verify that an efficient implementation agrees numerically with a reference implementation of the same architecture. Second, evaluate whether the trained model serves the intended task well. The first catches programming mistakes; the second studies learned behavior. Include long contexts, changed positions and cache resumption in tests. Keep storage estimates separate from measured latency. Fewer cached numbers may help bandwidth or capacity, but other costs can dominate.

Test projection shapes, direct versus absorbed scores, value aggregation, positional terms and cache append behavior under explicit tolerances. Compare real attention outputs, not only isolated matrix identities, before claiming implementation equivalence. For model comparisons, hold evaluation conditions visible and distinguish cache compression from weight compression or sparse token selection.

Worked example. Change the latent coordinates in Workbench and verify that direct and absorbed toy scores still agree. Then change only the budget width. The cache estimate changes while the fixed two-dimensional algebra example stays the same. These are intentionally separate fixtures: changing a budget number does not retrain the toy matrices or measure a real model.

Same-architecture correctness and trained-model quality need separate tests

The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.

Try it yourself. What does a zero score difference in this experiment establish?

Pause the narration and explain your reasoning before continuing to the worked solution.

Reveal worked solution

It establishes the projection identity for the displayed toy matrices and coordinates. It does not establish the quality, speed or complete numerical correctness of a deployed MLA model.

Final checkpoint. Which equality supports absorbed scoring for the stated factorization? Option 1: q transpose U c equals (U transpose q) transpose c. Option 2: Any rotation commutes with every projection. Option 3: Any dense model can be compressed exactly.

Pause and choose an answer before continuing.

Reveal worked solution

Option 1 is correct. Associativity gives the first equality. It does not establish lossless compression of an arbitrary model.

LONGER TRANSFORMER SYSTEMS LESSONS

Follow the mechanism in depth

Worked examples, local narration and connected learning modes at your level.

Continue the learning path

Sources and scope

Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.

EXTENDED FIELD NOTES

What stays in memory while a model answers?

Separate permanent weights from conversation state, and connect memory use to time.

Additional reading · original lesson audio remains unchanged.

Read the full explanation · 579 words + college extension
Two kinds of stored information

A new token reuses cached keys and values; reading that state still costs time and memory.

  1. Weights: learned settings
  2. Prompt: prefill
  3. KV: retained state
  4. New token: decode

Weights: learned settings

The workshop and the work in progress

A useful way to distinguish model weights from a cache is to imagine a workshop. The tools and their settings are available for many jobs. The current project also occupies space: notes, measurements, and partly completed work. Weights are the learned settings reused across requests. Cached attention state belongs to a particular sequence or reusable prefix. The analogy stops short of literal memory or understanding; it simply separates persistent parameters from temporary computation.

When a decoder processes a prompt, it performs a prefill pass over the input. When it continues the answer, it generates tokens through decoding steps. In ordinary causal attention, earlier token positions cannot attend to later positions. This allows previously computed keys and values to remain useful as the sequence grows. A KV cache stores those representations so the system can reuse them rather than recomputing all earlier projections at every step.

Reusing work is not making it free

A new query still needs to interact with the relevant cached information. Reading the cache takes bandwidth, and a longer sequence can require more attention work. The cache also occupies memory. Caching changes the balance between recomputation and retained state; it does not remove every cost associated with a long conversation. This explains why a model can generate a short answer quickly yet struggle with a very long prompt or many concurrent users.

Suppose a toy model has two layers, two key/value heads per layer, four values per head, and a sequence of one hundred tokens. Storing both keys and values at two bytes per value requires 2 × 2 × 2 × 4 × 100 × 2 = 6,400 bytes. The first factor accounts for keys and values. This deliberately small example ignores allocator overhead and other state. Doubling the sequence length doubles this simple cache estimate; doubling independent sequences does the same.

Architectures change what needs to be retained

Grouped-query attention allows multiple query heads to share fewer key/value heads. That changes the number of cached heads while allowing distinct queries. Latent attention can retain a compact representation and use architecture-specific transformations to recover or compute what attention needs. Sliding windows can limit which recent positions remain relevant to a particular attention layer. These are distinct mechanisms, not interchangeable names for compression.

Do not apply one cache formula to every modern model without checking its architecture. Some systems contain multiple types of attention, shared memory, compressed representations, or other persistent state. A published bytes-per-token figure may cover only one component. Ask whether it includes all layers, scales, local windows, batches, and additional model-specific structures. A precise label such as “global cache component” is more useful than a large unqualified claim about total memory.

Measure the experience, not only a rate

Latency is the time a user waits for an event, such as the first token or the complete answer. Throughput is the amount of work completed over time, often across several requests. Batching can improve aggregate throughput while changing an individual user’s waiting time. Faster arithmetic does not guarantee lower latency when communication, cache reads, or scheduling dominate the workload.

Using the cache calculation above, vary sequence length while keeping other quantities fixed, then vary concurrency. Explain which quantities should change and which should remain constant. Finally, consider an answer that is twice as long. Even if each decoding step has the same cost, more steps take more time. A responsible performance report states the model revision, numerical format, hardware, prompt and output lengths, concurrency, and the metric being measured. Those details turn a speed claim into something another person can interpret and attempt to reproduce.

College extension · make the assumptions explicit

For a conventional cache with uniform layers, an estimate is M = 2LBTHkv db, where L is layer count, B batch size, T retained tokens, Hkv key/value head count, d head dimension and b bytes per element. The result is bytes. It is not a universal equation for latent or heterogeneous architectures. Separate allocated capacity from live occupancy, and separate weight memory from KV state and temporary buffers. Prefix sharing can reduce duplication when supported, but cache validity depends on matching the computation that produced it.

Sources and further investigation

Source review: October 28, 2026. Model-release claims are attributed to their publishers.

Open the focused reading page →

Reset this college path?

This removes only this path’s notes, progress and experiments from this browser.