How does Multi-Head Latent Attention work?

Authors
How does Multi-Head Latent Attention work?

Multi-Head Latent Attention (MLA) is a way of doing attention in an LLM where, instead of saving full keys and values for every head, the model saves one small compressed note per token and rebuilds the keys and values from it when needed. This makes the memory used while generating text many times smaller, while keeping the quality of full multi-head attention.

In this blog, we will learn about how Multi-Head Latent Attention works. We will also see why the KV cache becomes a big memory problem, how Multi-Query and Grouped-Query Attention tried to solve it, how MLA compresses keys and values into a small latent vector, the weight-merging trick that keeps it fast, how decoupled RoPE handles position information, and where it works well and where it has trade-offs.

We will cover the following:

  • What is attention?
  • What is multi-head attention?
  • The problem: the KV cache becomes huge
  • Earlier fixes: Multi-Query and Grouped-Query Attention
  • What is Multi-Head Latent Attention?
  • How does MLA work step by step?
  • How much memory does MLA save?
  • Merging the weights
  • The position problem and decoupled RoPE
  • MLA in code
  • MHA vs MQA vs GQA vs MLA
  • Where it works well and where it has trade-offs

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

What is attention?

Before jumping into Multi-Head Latent Attention, we must know what attention is.

An LLM (Large Language Model) works on small pieces of text called tokens. Inside an LLM, every token is stored as a list of numbers. This list of numbers is called a vector.

Attention is the step where each token looks at the earlier tokens and decides which of them matter for understanding it.

Let's take an example. In the sentence "The cat sat on the mat because it was tired", the word "it" must look back and find "cat". Attention is what lets "it" connect to "cat".

To do this, every token makes three vectors:

  • Query (Q): "What am I looking for?"
  • Key (K): "What do I contain?" It works like a label.
  • Value (V): "What information do I give if someone picks me?"

Think of a library. We walk in with a question, which is our query. Every book has a title on its spine, which is the key. The content inside the book is the value. We match our question with the titles, pick the best matching books, and read their content.

In the same way, the query of the current token is compared with the keys of all earlier tokens. The better the match, the higher the score. Then, the values are mixed together based on these scores. This mix becomes the new, richer understanding of the current token.

We have a detailed blog on the math behind Q, K, and V that explains this step by step.

What is multi-head attention?

One attention step can only focus on one kind of relationship at a time. But language has many relationships at once. One part should track grammar, another part should track meaning, another should track who did what.

So, the LLM runs many small attention steps side by side. Each one is called a head.

Multi-Head Attention (MHA) means many attention heads working in parallel, each with its own queries, keys, and values.

Let's visualize it as below:

                     Token vector
                          ↓
        +--------+--------+--------+--------+
        ↓        ↓        ↓        ↓        ↓
      Head 1   Head 2   Head 3    ...    Head N
     (Q,K,V)  (Q,K,V)  (Q,K,V)          (Q,K,V)
        ↓        ↓        ↓        ↓        ↓
        +--------+--------+--------+--------+
                          ↓
                   Combined output

Here, we can see that every head gets its own Q, K, and V. Then, all the heads' results are joined together.

This works very well. But every head has its own keys and values, and that becomes a memory problem.

To master the Attention Mechanism and Multi-Head Attention, and build a Large Language Model (LLM) from scratch, check out our AI and Machine Learning Program at Outcome School.

The problem: the KV cache becomes huge

An LLM writes one token at a time. For each new token, attention must compare it with the keys and values of all earlier tokens.

Computing those keys and values again and again for every new token is a waste of time. So, the model saves them in memory after computing them once. This saved memory is called the KV cache (Key-Value cache).

The KV cache works like the model's notebook. Each token writes its keys and values in the notebook once, and future tokens just read from it.

Now, let's see how big this notebook becomes. For every token, in every layer, for every head, we save one key vector and one value vector.

   KV cache size =  2 (key + value)
                  x number of heads
                  x size of each head
                  x number of layers
                  x number of tokens

Let's take numbers from the DeepSeek-V2 model, which is the model that introduced MLA. It has 128 heads, each head has size 128, and there are 60 layers.

If it used normal multi-head attention, then for one token in one layer, it would save:

   2 x 128 heads x 128 = 32,768 numbers

That is for one token in one layer. Multiply by 60 layers and by thousands of tokens of text, and then by many users at the same time. The notebook becomes so big that it fills the GPU memory, which is limited and expensive.

When the memory is full, we can serve fewer users at once and support shorter texts. So, the KV cache becomes the main bottleneck. We have a detailed blog on KV Cache Compression that covers the different ways to shrink it end to end.

Earlier fixes: Multi-Query and Grouped-Query Attention

Before MLA, people tried two fixes.

Multi-Query Attention (MQA): All the heads share one single key and one single value. Each head still has its own query. This shrinks the cache a lot. But, the heads lose their own private view, and the quality drops.

Grouped-Query Attention (GQA): A middle path. The heads are split into a few groups, and each group shares one key and one value. For example, 32 heads in 8 groups. This saves memory and keeps quality better than MQA.

Let's visualize it as below:

   MHA:  Q1 Q2 Q3 Q4        MQA:  Q1 Q2 Q3 Q4       GQA:  Q1 Q2   Q3 Q4
         ↓  ↓  ↓  ↓               \  ↓  ↓  /              \ /     \ /
         K1 K2 K3 K4                  K                   K1      K2
         (4 KV pairs)              (1 KV pair)          (2 KV pairs)

Here, we can see that MQA and GQA save memory by throwing away some keys and values and making heads share them.

The issue with this approach is that sharing reduces how different the heads can be, so quality can drop. We need a solution that saves memory without throwing away the variety of the heads. Let's see how MLA solves this issue.

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

What is Multi-Head Latent Attention?

Multi-Head Latent Attention is an attention method where each token stores one small compressed vector, called a latent vector, in the KV cache. The full keys and values for every head are rebuilt from this small vector whenever they are needed.

The word latent means hidden or compressed. A latent vector is a small vector that holds the important information in a squeezed form.

Suppose we attend a long lecture. Writing down every word the teacher says takes a huge notebook. Instead, we write a short summary of the key points. Later, from this summary, we can rebuild whatever detail we need. MLA does the same. The latent vector is the short summary, and the keys and values are rebuilt from it.

The key difference from MQA and GQA is this: MQA and GQA share keys and values between heads. MLA compresses them. Every head still gets its own different keys and values. They are all just rebuilt from the same small summary.

This idea was introduced in the DeepSeek-V2 paper in 2024, and it is also used in DeepSeek-V3 and DeepSeek-R1.

How does MLA work step by step?

Now, let's understand the working of MLA step by step.

Let the token vector be h.

Step 1: We compress the token vector with a down-projection.

The model multiplies h with a weight matrix to make a small vector c. A weight matrix is just a table of learned numbers that turns one vector into another vector. Here, it turns a big vector into a small one, so we call it a down-projection.

c = W_down * h

Here, c is small, for example 512 numbers.

Step 2: We save only c in the KV cache.

We do not save the keys and values. We save only the small c.

Step 3: We rebuild the keys and values with up-projections.

When attention needs the keys and values, the model multiplies c with two other weight matrices. These turn the small vector into big ones, so we call them up-projections.

keys for all heads = W_up_key * c

values for all heads = W_up_value * c

Each head gets its own part of these keys and values, so each head still has its own view.

Step 4: We do normal attention.

Now, the queries are compared with these keys, and the values are mixed, exactly like normal multi-head attention.

Let's see the full flow as below:

   Token vector h (big)
            ↓
   W_down (compress)
            ↓
   +----------------+
   |    latent c    |
   +----------------+
   (only c is saved in the KV cache)
            ↓
   W_up_key, W_up_value (rebuild)
       ↓          ↓
     Keys       Values
   (for all 128 heads)
       ↓          ↓
   Normal multi-head attention

Here, we can see that the big keys and values exist only for a moment during computation. What stays in memory is only the small latent vector.

The weight matrices W_down, W_up_key, and W_up_value are learned during training. So, the model itself learns what to keep in the summary and how to rebuild from it.

Note: DeepSeek-V2 also compresses the queries in a similar way. This does not shrink the KV cache, because queries are not cached. It only saves memory during training.

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

How much memory does MLA save?

Let's compare using the DeepSeek-V2 numbers, per token, per layer:

   Normal MHA:   2 x 128 heads x 128   = 32,768 numbers
   MLA:          512 (latent) + 64     =    576 numbers

Here, we have 512 numbers for the latent vector, and 64 numbers for a small extra position key. We will learn about this extra 64 soon.

So, MLA stores about 57 times fewer numbers than normal MHA for the same model shape. The DeepSeek-V2 paper says that its cache is about the same as GQA with only 2.25 groups, but the quality is stronger than normal MHA in their tests.

The paper also reports that, compared with their older DeepSeek 67B model, DeepSeek-V2 reduces the KV cache by 93.3% and increases the maximum generation speed by 5.76 times.

Merging the weights

Now, a question arises. If we must rebuild the keys and values from c for every earlier token at every step, are we not doing a lot of extra work? We saved memory, but did we lose speed?

The answer is no, because of a math trick.

Let's understand it with the keys first. To score a token, attention computes the query multiplied by the key:

   score = query . key
         = query . (W_up_key x c)
         = (query x W_up_key) . c

Here, we can notice that we can move W_up_key from the key side to the query side. So, instead of making the big key from c, we change the query once so that it can talk directly to the small c.

And since the query itself is made by a weight matrix, W_up_key can be merged into that matrix ahead of time. This is called absorbing the weight.

The same trick works for the values. The value up-projection W_up_value can be merged into the output matrix that comes after attention.

So, at inference time, the model never needs to build the full keys and values. It works directly with the small latent vectors.

If we want to go deep into KV Cache, Grouped Query Attention, and LLM Inference Engineering, check out our AI and Machine Learning Program at Outcome School.

The position problem and decoupled RoPE

There is one thing that breaks the merging trick.

An LLM must know the order of the words. "Dog bites man" and "Man bites dog" use the same words, but mean very different things. Many modern LLMs add the position information using a method called RoPE (Rotary Position Embedding).

RoPE rotates the query and key vectors by an angle that depends on the position of the token. Tokens at different positions get rotated differently.

The problem is that this rotation sits between the query and W_up_key, and it changes with every position. So, we can no longer move W_up_key into the query matrix ahead of time. The merging trick breaks.

So, here comes decoupled RoPE to the rescue.

DeepSeek splits the job into two parts:

  • Content part: The normal keys and queries made from the latent vector. No rotation is applied here. So, the merging trick still works.
  • Position part: A small extra key of 64 numbers that carries the rotation. This extra key is shared by all heads, and it is saved in the cache next to the latent vector. Each head also gets a small extra query part with rotation.

Then, for each head, the content part and the position part are joined together before computing the score.

   Key for a head   = [ content key (from c, no rotation) | shared position key (rotated) ]
   Query for a head = [ content query (no rotation)       | position query (rotated)      ]

This is why the cache holds 512 + 64 = 576 numbers per token per layer.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

MLA in code

Now, let's see a simplified version of the MLA idea in PyTorch-style Python. Here, I have kept only the important lines of the code and removed RoPE and other lines for brevity.

import torch
import torch.nn as nn

class SimpleMLA(nn.Module):
    def __init__(self, d_model=4096, n_heads=32, d_head=128, d_latent=512):
        super().__init__()
        self.down = nn.Linear(d_model, d_latent)              # compress
        self.up_k = nn.Linear(d_latent, n_heads * d_head)     # rebuild keys
        self.up_v = nn.Linear(d_latent, n_heads * d_head)     # rebuild values
        self.q    = nn.Linear(d_model, n_heads * d_head)      # queries

    def forward(self, h, cache):
        c = self.down(h)               # small latent vector for the new token
        cache.append(c)                # save ONLY the latent vector
        all_c = torch.cat(cache, dim=1)  # latent vectors of all tokens so far
        k = self.up_k(all_c)           # rebuild keys for all heads
        v = self.up_v(all_c)           # rebuild values for all heads
        q = self.q(h)
        return attention(q, k, v)      # normal multi-head attention

Here, we have:

  • self.down, which compresses the big token vector of 4096 numbers into a latent vector of 512 numbers.
  • cache.append(c), which saves only this small vector. This is where the memory saving comes from.
  • self.up_k and self.up_v, which rebuild the full keys and values for all heads from the saved latent vectors.
  • attention(q, k, v), which is a helper function (not shown here) that does the normal multi-head attention.

Note: For the sake of understanding, this code rebuilds the keys and values directly. Real fast implementations use the merging trick that we learned above, so they never build the full keys and values.

MHA vs MQA vs GQA vs MLA

Let me tabulate the differences between MHA, MQA, GQA, and MLA for your better understanding.

MethodWhat is cached per token per layerKV cache sizeEach head has its own keys and values?Quality
MHAKeys and values for every headVery largeYesHigh
MQAOne shared key and valueVery smallNoLower
GQAOne key and value per groupMediumShared within a groupClose to MHA
MLAOne small latent vector + small position keyVery smallYes, rebuilt from the latentMatches or beats MHA in DeepSeek's tests

Here, we can see that MLA gets a cache size close to MQA and small GQA setups, while still giving every head its own keys and values.

Where it works well and where it has trade-offs

Where it works well:

  • Long texts: A small cache lets the model handle much longer inputs on the same GPU.
  • Many users at once: More users fit in memory at the same time, which lowers the cost per user.
  • Large models: The bigger the model, the bigger the KV cache problem, and the bigger the saving.

Trade-offs:

  • More complex: It needs extra matrices, the merging trick, and decoupled RoPE. It is harder to build than GQA.
  • Extra math per step: Working with the compressed form adds some computation, so we trade a lot of memory for a bit more math. Since generating text is usually limited by memory, this trade is worth it.
  • Needs support in tools: Inference engines need special code for MLA. Several inference engines support it, but not every tool does.
  • Hard to add later: It is best to train a model with MLA from the start. Converting an existing model needs extra work.

Now, we must have understood how Multi-Head Latent Attention works.

Frequently Asked Questions

Does Multi-Head Latent Attention lower the quality of the model?

No. In DeepSeek's tests, MLA matches or even beats the quality of normal multi-head attention. Unlike MQA and GQA, it does not make heads share keys and values. Every head still gets its own keys and values, which are rebuilt from the small latent vector, so the heads keep their variety.

Does MLA also compress the queries?

Yes. DeepSeek-V2 also compresses the queries in a similar way to the keys and values. But this does not shrink the KV cache, because queries are not cached. Compressing the queries only saves memory during training.

Can we add MLA to an already trained model?

Not easily. It is best to train a model with MLA from the start. During training, the model learns what to keep in the latent vector and how to rebuild the keys and values from it. Converting an existing model to MLA needs extra work.

Which models use Multi-Head Latent Attention?

MLA was introduced in the DeepSeek-V2 paper in 2024. It is also used in DeepSeek-V3 and DeepSeek-R1. In DeepSeek-V2, MLA stores only 576 numbers per token per layer in the KV cache, compared with 32,768 numbers for normal multi-head attention.

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.