Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 26

Grouped Query Attention: Memory Efficiency Through K/V Head Sharing

Recommended resources

Welcome to our next lesson in the "Efficient Attention" module.

In our previous session, we established a crucial foundation: we quantified the memory cost of the standard Multi-Head Attention (MHA) KV cache. You learned that its size grows linearly with sequence length and can often dwarf the memory required for the model weights themselves. This memory bottleneck is a primary obstacle to building models with very long context windows, which has motivated a series of architectural innovations.

Today, we will dissect one of the most successful and widely adopted of these innovations: Grouped-Query Attention (GQA). Our learning outcome is to describe Grouped Query Attention (GQA) and how sharing key-value heads reduces memory usage. By the end of this lesson, you will understand the mechanics of GQA, how it strikes a balance between computational efficiency and model performance, and be able to calculate its memory savings compared to standard MHA.


1. The Attention Efficiency Spectrum: MHA, MQA, and GQA

The challenge of optimizing the attention mechanism can be seen as a trade-off between two competing goals:

  • Model Expressiveness (Performance): The ability of the model to learn complex patterns. In attention, this is maximized when each query head can learn its own unique key and value projections, allowing it to "look" for different types of information in the sequence.
  • Memory Efficiency: The amount of GPU memory required, dominated by the size of the KV cache during inference.

Let's place three key architectures on this spectrum.

  1. Multi-Head Attention (MHA): This is the original architecture we've studied. Each query head has its own dedicated key (K) and value (V) head. With N query heads, there are N corresponding K/V heads. This provides maximum expressiveness but also incurs the maximum KV cache memory cost.

  2. Multi-Query Attention (MQA): At the opposite extreme lies MQA. Here, all query heads share a single K/V head. This is maximally memory-efficient, as you only need to cache one set of K and V vectors. However, it can degrade model quality because all query heads are forced to use the same key and value representations, limiting the diversity of information they can extract.

  3. Grouped-Query Attention (GQA): GQA provides a practical and effective compromise. It organizes the query heads into groups, and all heads within a single group share one K/V head. Instead of having N K/V heads (like MHA) or just 1 (like MQA), GQA has g K/V heads, where 1 < g < N.

This diagram provides a clear visual summary of the three approaches.

Comparison of Multi-head, Grouped-query, and Multi-query Attention
This diagram from Klu.ai illustrates the architectural differences. MHA has a one-to-one mapping of Q to K/V heads. MQA has a many-to-one mapping. GQA has a many-to-few mapping, with query heads organized into groups.

To solidify this high-level understanding, please review the following text, which provides a concise summary of this trade-off.

Understanding Grouped-Query Attention: A Practical Guide with ...

The article 'Understanding Grouped-Query Attention' by Saeed Mehrang provides an excellent schematic and summary of these three attention variants.

Please read the section 'In a Nutshell'. Focus on how the diagram and text position GQA as a balance between the extremes of MHA and MQA.



2. The GQA Mechanism Explained

Now, let's dive into the mechanics of GQA. The core idea is simple: if you have N query heads and g key-value heads, you create g groups. The size of each group is N / g. All query heads within one group will share the same key and value projections.

The following video explains this grouping strategy and its implications.

Understand Grouped Query Attention (GQA) | The final frontier before latent attention

The video 'Understand Grouped Query Attention (GQA)' from the Vizuara channel provides a clear, step-by-step explanation of the GQA mechanism.

Please watch from 11:57 to 15:53. Pay close attention to how the key and value heads are shared within groups but differ across groups.

As the video explains, GQA maintains more diversity than MQA because different groups still have different K/V heads, allowing them to capture different perspectives. However, it achieves significant memory savings over MHA by not requiring a unique K/V head for every single query head.

From Concept to Code

To see how this is implemented in practice using PyTorch, the key operation is to project the input to a smaller K and V dimension and then "repeat" those K and V tensors to match the number of query heads.

Let's look at the implementation details in the article we viewed earlier.

Understanding Grouped-Query Attention: A Practical Guide with ...

We'll now examine the PyTorch implementation of GQA from the same article, 'Understanding Grouped-Query Attention'.

Please read the sections 'Grouped-Query Attention: The Best of Both Worlds' and 'Side-by-Side Comparison'. Focus on the 'PyTorch Implementation' of GQA. The most important part is the repeat_interleave function, which is how the smaller number of KV heads are broadcast to be shared by their respective query head groups. Compare this to the MHA implementation, which does not have this step.

This implementation makes the mechanism concrete:

  1. Project the input x into Q, K, and V. The q_proj is to the full dimension (d_model), but k_proj and v_proj are to a smaller dimension (kv_dim).
  2. Reshape K and V to have num_kv_heads.
  3. Use K.repeat_interleave(self.num_queries_per_kv, dim=1) to duplicate the K heads for each query head in the group. The same is done for V.
  4. The rest of the attention calculation proceeds identically to MHA.


3. Quantifying the Memory Reduction

Now we can update our KV cache formula from the previous lesson to account for GQA.

Recall the MHA formula:

Here, N is the number of query heads, and since it's MHA, it's also the number of K/V heads.

The GQA formula:
In GQA, we are no longer storing N key-value heads. We are storing g key-value heads (where g = num_kv_heads). The formula becomes:

The memory reduction is therefore a factor of N / g.

The video you just watched provides a concise explanation of this exact point.

Understand Grouped Query Attention (GQA) | The final frontier before latent attention

Let's revisit the Vizuara video to see the quantification of this memory saving.

Watch from 19:53 to 21:26. The video directly compares the KV cache size formulas for MHA, MQA, and GQA, showing how the factor 'n' (number of query heads) is replaced by 'g' (number of groups).

Worked Example: Llama 3

Many modern models, like Meta's Llama 3, use GQA. The Llama 3 8B model uses:

  • N (num_query_heads) = 32
  • g (num_kv_heads) = 8

The memory reduction factor is N / g = 32 / 8 = 4. This means GQA reduces the KV cache size by 4x compared to a standard MHA implementation, while maintaining much of the model's performance. This significant saving is what allows models like Llama 3 to handle longer context lengths more efficiently.



Conclusion

In this lesson, we dissected Grouped-Query Attention, a crucial optimization for modern Transformers.

Key Takeaways:

  • GQA is an efficient attention mechanism that provides a balance between the expressiveness of Multi-Head Attention (MHA) and the extreme memory efficiency of Multi-Query Attention (MQA).
  • The core mechanism of GQA involves organizing query heads into groups, where each group shares a single set of Key (K) and Value (V) heads.
  • This sharing mechanism reduces the size of the KV cache by a factor of N / g, where N is the number of query heads and g is the number of K/V heads (groups).
  • GQA has been widely adopted in state-of-the-art LLMs (like Llama and Mistral) to enable faster inference and support for longer context windows.

Preview of the Next Lesson:
We have now seen how to make the KV cache more efficient by reducing the number of key and value heads we need to store. But what if we could reduce the size of the K and V vectors themselves? In our next lesson, we will explore Multi-head Latent Attention (MLA), the key innovation in the DeepSeek models. MLA takes a different approach by using low-rank compression to shrink the K and V vectors, pushing the boundaries of memory efficiency even further.