How does Linear Attention work?
- Authors
- Name
- Amit Shekhar
- Published on
Linear Attention is a faster form of attention where the work grows in a straight line with the length of the text, instead of growing with the square of the length. It does this by first summarizing all the words into a small fixed-size memory, and then letting each word read from that summary instead of comparing itself with every other word.
In this blog, we will learn about how Linear Attention works. We will also see how normal attention works with queries, keys, and values, why it becomes slow on long text, how a small change in the order of multiplication removes that slowness, how Linear Attention becomes a running memory while generating text, what we lose in the process, and how modern versions fix these problems.
We will cover the following:
- What is attention?
- Query, Key, and Value
- How does normal attention work?
- The problem: quadratic cost
- The key idea behind Linear Attention
- What is a feature map?
- How does Linear Attention work?
- Linear Attention as a running memory
- Linear Attention in code
- Normal Attention vs Linear Attention
- What do we lose?
- Modern versions of Linear Attention
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 Linear Attention, we must know about normal attention, because Linear Attention is a changed version of it.
LLMs (Large Language Models) are built on an architecture called the Transformer. The core part of the Transformer is attention.
Attention is the step where every word looks at the other words in the text to understand its own meaning better.
Let's say the model is reading:
I went to the bank to deposit money.
The word "bank" can mean a river bank or a money bank. To decide, "bank" looks at the other words. It finds "deposit" and "money", and now it knows that this is a money bank.
Attention lets each word ask, "Which other words matter to me, and how much?"
Note: Models actually work on tokens, which are words or pieces of words. For the sake of understanding, we will just say "words" in this blog.
Query, Key, and Value
To do attention, the model turns every word into three lists of numbers. A list of numbers is called a vector.
- Query (Q): What this word is looking for.
- Key (K): What this word offers, like a label.
- Value (V): The actual information this word carries.
Let's understand this with a library analogy.
Suppose we go to a library with a question in mind. That question is our query. Every book has a title on its cover. That title is the key. The content inside the book is the value.
We compare our question with every title. Books whose titles match our question well get more of our attention. Finally, we read from those books, giving more weight to the better matches.
This is exactly what attention does.
We have a detailed blog on Math behind Attention - Q, K, and V that explains this step by step with real numbers.
How does normal attention work?
Normal attention works in three steps.
Step 1: The query of a word is compared with the key of every word. The comparison is a dot product, which means multiplying matching numbers and adding them up. A bigger result means a better match.
For example, if the query is [1, 2] and a key is [3, 1], the dot product is 1*3 + 2*1 = 5.
Step 2: The scores are turned into weights. They go through a function called softmax. Softmax turns any list of scores into positive weights that add up to 1. For example, scores [5, 1, 0] become roughly [0.98, 0.02, 0.01]. The best match gets most of the weight.
Step 3: The word takes a weighted mix of all the values using those weights. This mix is the new version of the word, which now carries information from the other words.
In the form of a formula, it looks like below:
Attention = softmax(Q x K^T) x V
Here, K^T means the keys are flipped so that every query can be compared with every key in one big multiplication.
To learn the Attention Mechanism, Self-Attention and Multi-Head Attention, and Transformer Architecture in depth, check out our AI and Machine Learning Program at Outcome School.
The problem: quadratic cost
Step 1 compares every word with every word. So, the model builds a table of scores with one row and one column for each word.
If the text has N words, the table has N x N entries.
word1 word2 word3 word4
word1 5.0 1.2 0.3 2.1
word2 0.7 4.4 1.9 0.2
word3 ... ... ... ...
word4 ... ... ... ...
Let's see how this table grows:
| Words (N) | Table size (N x N) |
|---|---|
| 1,000 | 1,000,000 |
| 10,000 | 100,000,000 |
| 100,000 | 10,000,000,000 |
Means, when the text becomes 10 times longer, the work becomes 100 times bigger. This is called quadratic cost.
So, normal attention becomes very slow and needs a lot of memory for long documents, long chats, or whole codebases. We need a way to avoid building this huge table.
We have a blog on Sliding Window Attention that covers one way to cut this cost by letting each word look only at its nearby words.
The key idea behind Linear Attention
Here comes Linear Attention into the picture. It was made popular by the 2020 paper "Transformers are RNNs" by Katharopoulos and others.
The idea comes from a simple fact about multiplication: the order in which we group multiplications does not change the answer.
Let's take plain numbers:
(2 x 3) x 4 = 6 x 4 = 24
2 x (3 x 4) = 2 x 12 = 24
The answer is the same. Only the grouping changed.
The same is true for matrices. A matrix is just a table of numbers. So, if there was no softmax in the middle, we could write:
(Q x K^T) x V = Q x (K^T x V)
Note: With matrices, we cannot swap the order of the items, but we can always move the brackets. Here, the order Q, K^T, V stays the same. Only the brackets move.
Now, let's see why this matters. Let say we have N words, and each word has d numbers in its vector. Usually, d is small, like 64 or 128, and N can be huge, like 100,000.
- Left side:
Q x K^Tbuilds the N x N table. That is the huge table we wanted to avoid. - Right side:
K^T x Vbuilds a d x d table. With d = 64, this is just 64 x 64 = 4,096 numbers, no matter how long the text is.
Normal grouping: (Q x K^T) x V -> builds N x N table (grows with text)
New grouping: Q x (K^T x V) -> builds d x d table (fixed size)
Here, we can notice that the new grouping never compares every word with every word. It first squeezes all the keys and values into a small summary table, and then each query reads from that summary.
But softmax sits between Q x K^T and V. Softmax works on each row of the N x N table as a whole, so we cannot move the brackets across it. The trick breaks.
So, how can we remove softmax but still keep its good parts? The answer is a feature map.
What is a feature map?
Let's first see what softmax was giving us:
- All weights were positive. A word never gets negative attention.
- The weights were normalized, which means they were divided by their total so that they add up to 1.
Linear Attention keeps both of these properties without using softmax.
A feature map is a simple function, written as phi, that is applied to each query and each key separately, and turns their numbers into positive numbers.
A common choice from the paper is:
phi(x) = elu(x) + 1
Here, elu is a common function used in neural networks. elu(x) + 1 keeps a positive number almost as it is (it adds 1), and turns a negative number into a small positive number between 0 and 1. So, the output is always positive.
Now, the similarity between a query and a key becomes:
similarity(q, k) = phi(q) . phi(k)
Since both sides are positive, the similarity is always positive. This replaces the softmax score.
The feature map phi is applied to each query and each key on its own. It does not need to see the whole row of scores, unlike softmax. Because of this, nothing blocks us from moving the brackets anymore.
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.
How does Linear Attention work?
Now, let's put everything together.
For a word with query q, normal attention computes:
output = sum over all words j of [ weight(q, k_j) x v_j ]
With Linear Attention, the weight is phi(q) . phi(k_j), divided by the total of all such weights. So, the output becomes:
phi(q) x [ sum of phi(k_j) x v_j ]
output = -----------------------------------
phi(q) . [ sum of phi(k_j) ]
Here, we can notice that the two parts inside the brackets do not depend on the query at all. They depend only on the keys and the values. So, we can compute them once and reuse them for every query.
Let's give these two parts names:
- S = sum of
phi(k_j) x v_jfor all words. This is the d x d summary table, our memory. - z = sum of
phi(k_j)for all words. This is a running total used for dividing, so that the weights add up to 1.
So, the full process is:
Step 1: Apply phi to all queries and keys.
Step 2: Build the summary S and the total z from all the keys and values. The cost is N x d x d, which grows in a straight line with N.
Step 3: For each word, compute phi(q) x S and divide by phi(q) . z. This is also N x d x d.
The total work is about N x d x d instead of N x N x d. Since d is fixed and small, the work grows in a straight line with the length of the text. This is called linear cost, and this is why it is called Linear Attention.
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.
Linear Attention as a running memory
Now, let's see how Linear Attention works while generating text.
When a language model generates text, a word can look only at the words before it, not the words after it. This is called causal attention.
In normal attention, to generate each new word, the model keeps the keys and values of all the earlier words in memory. This memory is called the KV Cache. It grows with every new word. So, generating the 100,000th word is much slower than generating the 10th word.
In Linear Attention, the summary S and the total z can be updated one word at a time:
For each new word t:
S = S + phi(k_t) x v_t <- write this word into the memory
z = z + phi(k_t) <- update the running total
output_t = (phi(q_t) x S) / (phi(q_t) . z) <- read from the memory
Let's understand this with an analogy.
Suppose a shopkeeper keeps a daily total instead of keeping every bill. When a new customer pays, the shopkeeper just adds the amount to the running total. The shopkeeper never needs to look at old bills again.
The summary S is like that running total. Each new word is added to it, and the old words are never visited again.
word1 --> [S] --> word2 --> [S] --> word3 --> [S] --> ...
fixed size memory, updated at every step
So, the memory stays the same size forever, and every new word costs the same time. This is why the paper is named "Transformers are RNNs". An RNN, which stands for Recurrent Neural Network, is an older type of model that reads one word at a time and keeps a fixed-size memory. Linear Attention behaves exactly like that while generating, and it can still be trained in parallel like a Transformer, because during training all the words are available at once.
If we want to go deep into Causal Masked Attention, KV Cache, and LLM Internals, and build a Large Language Model (LLM) from scratch, we cover all of it in our AI and Machine Learning Program at Outcome School.
Linear Attention in code
Let's see the code for both groupings in Python with NumPy, a library for working with tables of numbers.
import numpy as np
def phi(x):
return np.where(x > 0, x + 1, np.exp(x)) # elu(x) + 1, always positive
np.random.seed(0)
N, d = 4, 2 # 4 words, 2 numbers per word
Q = np.random.randn(N, d)
K = np.random.randn(N, d)
V = np.random.randn(N, d)
# Way 1: compare every pair first (N x N table)
scores = phi(Q) @ phi(K).T
out1 = (scores @ V) / scores.sum(axis=1, keepdims=True)
# Way 2: summarize keys and values first (d x d table)
S = phi(K).T @ V
z = phi(K).sum(axis=0)
out2 = (phi(Q) @ S) / (phi(Q) @ z)[:, None]
print(np.allclose(out1, out2))
print(scores.shape, S.shape)
Here, we have:
phiis the feature map. It turns every number into a positive number.- The
@symbol means matrix multiplication, and.Tmeans flipping the table, which is theK^Tfrom our formula. Q,K, andVare random queries, keys, and values for 4 words.- Way 1 builds the N x N
scorestable first, then mixes the values, and divides by the total of each row. - Way 2 builds the small summary
Sand the totalzfirst, then each query reads from them. np.allclosechecks if both results are the same.
This will print the following:
True
(4, 4) (2, 2)
Here, we can see that both ways give the same answer. But Way 1 built a 4 x 4 table, and Way 2 built only a 2 x 2 table. With 100,000 words, Way 1 needs a 100,000 x 100,000 table, while Way 2 still needs only a d x d table.
Now, let's see the running memory version that is used while generating text:
S = np.zeros((d, d)) # running memory
z = np.zeros(d) # running total for dividing
for t in range(N):
k, v, q = phi(K[t]), V[t], phi(Q[t])
S = S + np.outer(k, v) # write this word into memory
z = z + k
out = (q @ S) / (q @ z) # read from memory
print(t, np.round(out, 3))
Here, we are reading one word at a time. np.outer(k, v) makes a small d x d table from one key and one value, and we add it into the memory S. Then the query of the current word reads from the memory. The size of S never changes, no matter how many words come.
It will print the following:
0 [ 1.494 -0.205]
1 [ 0.766 -0.605]
2 [-0.625 -0.051]
3 [-0.128 -0.28 ]
Here, each line is the output for one word, computed using only that word and the words before it. It works perfectly.
Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.
Normal Attention vs Linear Attention
Let me tabulate the differences between Normal Attention and Linear Attention for your better understanding.
| Point | Normal Attention | Linear Attention |
|---|---|---|
| Scoring | softmax of query-key dot products | dot product of phi(query) and phi(key) |
| Order of work | (Q x K^T) x V | Q x (K^T x V) |
| Work as text grows | Quadratic, N x N | Linear, N |
| Memory while generating | KV Cache grows with every word | Fixed d x d summary |
| Time per new word | Grows with text length | Stays the same |
| Exact recall of old details | Very good | Weaker |
| Quality on language tasks | Strong | Usually lower in its basic form |
What do we lose?
Linear Attention comes with a price.
Problem 1: The memory is a fixed-size summary. Normal attention keeps every word separately, so it can always go back and find one exact detail. Linear Attention squeezes everything into one d x d table. When too many words are added, they start to mix together and become hard to separate. So, tasks like "find the exact phone number mentioned 50 pages ago" become harder.
Problem 2: The focus is less sharp. Softmax is very good at giving almost all the weight to the single best match. The simple feature map spreads the weight more evenly. So, the model has a harder time focusing strongly on one word.
Problem 3: The memory never forgets. In the basic version, S only keeps adding. Old, useless information stays in the memory forever and takes space from new, useful information.
Because of these problems, the basic Linear Attention usually scores lower than normal attention on language tasks.
Modern versions of Linear Attention
Researchers have worked to fix these problems. Now, let's discuss the main ideas.
- Adding a forget step (decay and gates): Before adding the new word, the memory is multiplied by a number less than 1, so old information slowly fades. If this number is learned from the current word, it is called a gate. The model can then decide what to forget. RetNet and Gated Linear Attention use this idea.
- The delta rule (correcting the memory): Instead of just adding, the model first checks what the memory already says for this key, and writes only the difference. DeltaNet and Gated DeltaNet use this idea.
- Hybrid models: Many recent models mix many Linear Attention layers with a few normal attention layers. The Linear Attention layers keep the cost low, and the few normal attention layers keep exact recall. For example, Qwen3-Next uses three Gated DeltaNet layers for every one normal attention layer.
So, Linear Attention has moved from a research idea to a real part of some large models.
Now we must have understood how Linear Attention works.
Frequently Asked Questions
Does Linear Attention give the same output as normal attention?
No. Linear Attention does not give the same output as normal softmax attention. It replaces the softmax score with the dot product of phi(query) and phi(key), where phi is a feature map that turns numbers into positive numbers. Because of this, its focus is less sharp, and its basic form usually scores lower on language tasks.
Does Linear Attention need a KV Cache?
No. Linear Attention does not keep a KV Cache that grows with every new word. While generating text, it keeps a fixed-size d x d summary S and a running total z, and updates both one word at a time. So, the memory stays the same size, and every new word costs the same time.
Can Linear Attention be trained in parallel like a Transformer?
Yes. During training, all the words are available at once, so Linear Attention can be trained in parallel like a Transformer. Only while generating text does it behave like an RNN, reading one word at a time and keeping a fixed-size memory. This is why the 2020 paper that made it popular is named "Transformers are RNNs".
Do modern LLMs use Linear Attention?
Yes, some do, mostly in hybrid models. These models mix many Linear Attention layers with a few normal attention layers. The Linear Attention layers keep the cost low, and the few normal attention layers keep exact recall. For example, Qwen3-Next uses three Gated DeltaNet layers for every one normal attention layer.
That's it for now.
Thanks
Amit Shekhar
Founder @ Outcome School
You can connect with me on:
Follow Outcome School on:
