Macalinao StudioLearnAll enriched lessons ↗
High school path · 7 sectionsSwitch to college ↗

High school / LONGER LESSON gqa

Grouped-query attention: many questions, shared memory

Map query heads to shared cache heads, compute distinct attention outputs, and budget memory without promising speed.

Preparation: Queries, keys and values; division; the KV caching lesson.

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

Separate the question from the reference material

High-school path. Map query heads to shared cache heads, compute distinct attention outputs, and budget memory without promising speed. Preparation: Queries, keys and values; division; the KV caching lesson. Move between Signal Room, Workbench and Field Notes without losing your section. Pause before each worked solution.

An attention head uses a query to compare against keys, then mixes values according to the resulting weights. Different questions can use the same reference material. Grouped-query attention applies that idea to a Transformer: several query heads share a key-value head. The queries remain separate, so their scores and outputs can differ. Sharing does not mean copying one head’s answer to the others. The goal is to reduce the repeated key-value state that must be stored and read during generation, while retaining multiple learned query projections.

Worked example. Four students ask different questions of one shared table. They may select different rows and produce different summaries. In the numerical analogy, two scalar queries, plus one and minus one, read keys zero and one and values two and eight. The same stored table can therefore support different weighted averages.

scores_head = query_head × shared_keys_transposed

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

Try it yourself. If two query heads share keys and values, must their attention weights match?

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

Reveal worked solution

No. Different queries can produce different scores against the same keys. Identical weights require additional conditions, such as identical relevant query projections.

Section 02 / 07

Place MHA, GQA and MQA on one scale

In multi-head attention, each query head has its own key-value head. In multi-query attention, all query heads share one key-value head. Grouped-query attention uses an intermediate number of shared heads. These are architectural choices, not three different levels of intelligence. A smaller cache can be useful, but the model must learn to work with the chosen sharing. You cannot safely take an arbitrary trained model, delete some heads and assume its answers remain unchanged. Model conversion and further training are separate from the arithmetic of counting heads.

Worked example. Thirty-two query heads with eight key-value heads make eight groups of four queries. With four key-value heads, each group has eight queries. With one, all thirty-two share. Our Workbench restricts the head choices to divisors of thirty-two so every selected configuration has equal-sized groups.

Queries per group = H_Q / H_KV

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

Try it yourself. With thirty-two query heads and two key-value heads, how many queries share each cache head?

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

Reveal worked solution

Sixteen. Divide thirty-two by two. The sequence length and the number of query heads have not changed.

Section 03 / 07

Follow the shapes through the operation

A shape is a bookkeeping description of an array. Keep requests, heads, positions and feature width separate. In one decode step, each query head has one current query. The cache contains keys and values for the visible positions. A shared cache head supplies data to several queries, but each query still makes its own weighted sum. After attention, the head outputs are combined by an output projection. Sharing cache heads does not force the final representation to become narrower.

Worked example. Use one request, thirty-two query heads, eight cache heads, ten visible tokens and width four. Each key array holds 320 numbers. The value array holds another 320. The score rows contain 320 numbers in total: thirty-two queries times ten positions. Equal counts here are coincidental; changing width or token count affects different factors.

Q: B×H_Q×1×d; K,V: B×H_KV×N×d; scores: B×H_Q×1×N

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

Try it yourself. Should the score tensor have only eight rows because there are eight cache heads?

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

Reveal worked solution

No. There are thirty-two query heads, each producing its own score row. Cache sharing changes the storage heads, not the number of questions.

Section 04 / 07

Compute two different answers from one cache

Turn attention into a small calculation. Use keys zero and one and values two and eight. A positive query prefers the second key; a negative query prefers the first. Softmax converts scores into positive weights that sum to one. The output is the weighted average of the values. This example deliberately uses a head width of one, so the usual square-root scaling factor is one. It demonstrates that shared keys and values do not erase query diversity. It does not model learned language features.

Worked example. The positive query produces about 6.38635: two times 0.26894 plus eight times 0.73106. The negative query produces about 3.61365. If the query is zero, both scores are zero, both weights are one half, and the output is five. Workbench shows the positive and negative query outputs together.

output(q) = 2/(1+exp(q)) + 8 exp(q)/(1+exp(q))

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

Try it yourself. If the query changes sign, did the stored values change?

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

Reveal worked solution

No. The weighting changed because the question changed. The same values two and eight were reused in both calculations.

Section 05 / 07

Budget the cache, not the whole machine

For a simple dense cache, count keys and values, layers, requests, tokens, cache heads, head width and bytes per number. Replacing thirty-two cache heads with eight divides this payload by four when the other factors stay fixed. Model weights, temporary activations and runtime buffers are not included. A fourfold smaller cache therefore does not prove a fourfold reduction in total device memory. Nor does it prove fourfold faster decoding: some work still scales with query heads and other layers are unchanged.

Worked example. At thirty-two layers, one request, 4,096 tokens, width 128 and two-byte numbers, thirty-two cache heads need two gibibytes. Eight need half a gibibyte. One needs one sixteenth of a gibibyte. The queries remain thirty-two in every case. Change cache heads in Workbench and check the ratio before reading the result.

Cache ratio to MHA = H_KV / 32

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

Try it yourself. Why can a model with a fourfold smaller cache still need almost as much total memory?

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

Reveal worked solution

If weights or other allocations dominate, reducing the cache changes only a small part of the total. Always identify the component whose size was reduced.

Section 06 / 07

Conversion, training and kernel choices

Architectural savings become useful only when the trained model and implementation support them. Converting a checkpoint may initialize shared projections from several original heads, then use further training to adapt. Averaging weights is not the same as averaging the original attention outputs, because softmax is nonlinear. During deployment, kernels must read the shared data efficiently. A design can look efficient on paper but spend time expanding tensors or moving data. Evaluate the trained model and the serving implementation together.

Worked example. Suppose two key projection scalars are one and three. Their mean is two. Applying a query to the pooled key and then softmax generally differs from computing attention separately with each original key and averaging the final outputs. The pooling step creates an initialization that can be adapted, not a proof that the networks are identical.

softmax(mean(scores)) is generally not mean(softmax(scores))

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

Try it yourself. Does a successful tensor-shape check prove that a converted model retained its language quality?

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

Reveal worked solution

No. Shapes establish structural compatibility. Quality requires evaluation after the intended conversion and training procedure.

Section 07 / 07

Choose a comparison that answers the right question

A useful experiment states what stays fixed. Compare cache payload at fixed layers, query heads, context length and precision. Then separately compare trained-model quality and measured serving cost. Include long-context tasks and different request counts. Record time to first token, decode latency and throughput, because each exposes a different part of the system. Keep your Workbench prediction and result in Field Notes. Explain which result comes from arithmetic and which would require running a real trained model.

Worked example. Save the eight-cache-head baseline. Predict the change when selecting four heads, then run it: payload halves while queries per group double. Move the scalar query from one to zero. The toy attention outputs become five even though the memory budget does not change. These controls deliberately separate storage structure from attention weighting.

Separate architecture arithmetic, numerical correctness and task evaluation

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

Try it yourself. Name one result demonstrated here and one claim still requiring evidence.

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

Reveal worked solution

The experiment demonstrates the payload ratio and different query outputs from shared data. It cannot prove that a particular GQA model is faster or more accurate on your tasks.

Final checkpoint. Eight KV heads serve 32 query heads. How many query heads share each KV head? Option 1: Four. Option 2: Eight. Option 3: Thirty-two.

Pause and choose an answer before continuing.

Reveal worked solution

Option 1 is correct. Divide 32 query heads by eight KV heads. Each query still computes its own weights.

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
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.

Sources and further investigation

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

Open the focused reading page →

Reset this high school path?

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