# Why Is Attention Quadratic?

> Why self-attention cost grows with the square of the input length, what that costs in memory and speed, and how teams cope, for your AI interview.

**In short:** Attention is quadratic because every token is scored against every other token. With n tokens that makes n times n scores, so doubling the input roughly quadruples the attention work.

AI and LLM interview question Q056, Transformer architecture. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/why-is-attention-quadratic-in-sequence-length

## Say it in 30 seconds

Attention is quadratic because every token gets scored against every other token. With n tokens, that's n times n scores. So if I double the length of the text, the attention work roughly quadruples. That's why long documents are slow and memory hungry. Teams cope in two ways. FlashAttention keeps the same answer but moves less data. Sparse methods skip some pairs, which scales better but can lose links.

## Say it in 2 minutes

Attention is where each token looks at the others and decides how much each one matters. To do that, the model scores every token against every other token. With n tokens, that makes a grid of n times n scores, and the grid is the source of the cost.

The grid grows with the square of the length. Double the text and the grid has four times as many cells. The cost shows up in time, to fill the grid, and in memory, to hold it while it works. The FlashAttention paper says the time and memory complexity of self-attention are quadratic in sequence length.

There are two families of fixes. Exact methods such as FlashAttention keep every score, so the answer is the same, but they move less data around the GPU. Sparse methods such as Longformer and BigBird look at fewer pairs and scale linearly, but they can miss a link that sat far away in the text.

So in an interview I would say the cost is real, the fixes are trade-offs, and the choice depends on the task. A clinic summariser that must keep every clause might pick an exact method. A tool that only needs nearby context might pick a sparse one. Either way I would measure speed and answer quality on real files.

## What does quadratic mean for attention, in plain words?

Quadratic means the work grows with the square of a size. Double the size and the work becomes four times bigger. Triple it and the work becomes nine times bigger.

A transformer reads text as tokens, the small pieces the model works with. Attention is the step where each token looks at the others and works out which ones matter for its meaning. The original paper says the model computes "the dot products of the query with all keys".

Picture a claims desk at an insurer. Every new claim is checked against every open claim, looking for a match. Ten open claims mean 100 checks. A hundred open claims mean 10,000. The desk slows down long before the claims stop coming.

A transformer does the same with tokens. A text of n tokens gives n times n scores, so the work grows fast as the text gets longer.

- **Token:** A small piece of text the model reads and writes, often a word or part of one.
- **Score:** A number saying how much one token should look at another.
- **Sequence length:** How many tokens the model reads at once, written as n.
- **Quadratic:** Work that grows with the square of the size: double the input, four times the work.

## Where does the n-squared cost come from?

Attention packs the queries of all the tokens into one matrix, and the keys of all the tokens into another, then multiplies them. A query says what a token is looking for, and a key says what each token offers. The paper describes it as computing the attention function on a set of queries at once.

The result is a grid with one row per token and one column per token. Each cell holds one score. With n tokens, that is n times n cells. A softmax step then turns each row of scores into weights, and the weights mix the value vectors into the output. Both steps touch the whole grid.

*Diagram, Every token is scored against every token: Each token's query meets every token's key, so the grid is n by n. Softmax turns each row into weights, and those weights mix the values back into an output of the same length. The orange box is where the square cost sits.*
1. Every token's query is compared with every token's key.
2. Softmax turns each row of scores into weights that add up to one.
3. The weights mix the value vectors, so the output has n tokens again.

The cost shows up twice. The first is time: every cell needs a dot product, so the arithmetic grows with the square of the length. The second is memory: a standard implementation holds the big grid while it works, so the memory grows with the square too.

> **Tip:** A one-line answer for the interview: every token is compared with every token, so both the work and the memory grow with the square of the length.

## How fast does the cost grow in a worked example?

Here is a made-up clinic tool that summarises long discharge notes. The script counts the score cells for one attention head, on one pass. A real model runs several heads in parallel, so its total is bigger. The attention grid still grows with the square of the length, while the other layers grow in a straight line, so attention takes over at long lengths.

```python
# A made-up clinic tool: every token is scored against every token.
lengths = [1000, 2000, 4000, 8000, 16000]
previous = None
for tokens in lengths:
    scores = tokens * tokens
    if previous is None:
        print(f"{tokens:>6} tokens: {scores:>12,} scores")
    else:
        print(f"{tokens:>6} tokens: {scores:>12,} scores, {scores // previous} times the row above")
    previous = scores
```

Output:

```text
  1000 tokens:    1,000,000 scores
  2000 tokens:    4,000,000 scores, 4 times the row above
  4000 tokens:   16,000,000 scores, 4 times the row above
  8000 tokens:   64,000,000 scores, 4 times the row above
 16000 tokens:  256,000,000 scores, 4 times the row above
```

Each doubling of the text makes the grid four times bigger. Going from 1,000 to 16,000 tokens makes the grid 256 times bigger, because 16 squared is 256.

That is why a team cannot paste a 16,000 token file into one request and expect the speed of a 1,000 token one. The attention grid is 256 times bigger, so the attention step gets much slower, even though the rest of the model grows more gently.

## How do teams cope with the cost?

There are two main families. Exact methods keep every pair and work on the grid more cleverly. Sparse methods look at fewer pairs, so they cost less but can miss links.

> "Transformers are slow and memory-hungry on long sequences, since the time and memory complexity of self-attention are quadratic in sequence length." (FlashAttention paper)
>
> "Transformer-based models are unable to process long sequences due to their self-attention operation, which scales quadratically with the sequence length." (Longformer paper)
>
> "To remedy this, we propose, BigBird, a sparse attention mechanism that reduces this quadratic dependency to linear." (BigBird paper)

*Diagram, Two ways to tame the grid: Both paths start from the same long document. The exact path keeps the same answer and moves less data. The sparse path scales linearly, but a token may miss a link it would have seen in the full grid.*
1. The whole document goes to the exact method.
2. The same document goes to the sparse method instead.
3. FlashAttention works in tiles, so less data moves to and from the GPU.
4. A token loses the links to tokens outside its window.

FlashAttention is an exact method, so its answer matches the full grid. It works in tiles so the GPU moves less data. The paper also says it uses less memory than standard attention, and that its memory grows linearly in sequence length. It reports that it trains Transformers faster than the baselines it was tested against.

Sparse methods change the rule. Longformer combines a local windowed attention with a task-motivated global attention, and its attention scales linearly with length. BigBird also turns the quadratic dependency into a linear one. The FlashAttention paper notes that approximate attention methods trade model quality to cut compute. Sparse methods like these fall in that group, so the model may miss a link that sat far away.

The original Transformer paper saw this coming. It said that for very long sequences, self-attention could be restricted to a neighbourhood of nearby positions instead of every position.

### How would you explain the cost to a law firm?

A made-up law firm wants its assistant to read a 300-page loan agreement in one pass and answer a question about one clause. Its partner asks why the bill jumps when the whole file is attached.

- **Whole file: Everything in one pass.** Every token is scored against every other token. The grid is huge, so the answer is slow and costly.
- **Clauses first: Find the few that matter.** Search finds the clauses that mention the question, and only those go in. The grid stays small.

The fix is to read less at once. Splitting the file has a cost too, because a clause often refers to a definition on another page. So the team also fetches the cross references, which keeps the answer right.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Every token is scored against every token, so there are n times n scores.
- [ ] Doubling the length makes the attention work four times bigger.
- [ ] The cost is in both compute and memory.
- [ ] FlashAttention keeps the exact answer and moves less data.
- [ ] Sparse methods such as Longformer and BigBird scale linearly but give up some links.
- [ ] A longer context means a bigger grid, so time and memory both rise with the square of the length.

**Common traps**

- Trap: "Attention is slow because of the GPU." Better: A faster GPU helps, but the grid still grows with the square of the length.
- Trap: "FlashAttention makes attention linear." Better: It keeps the exact answer and moves less data. Linear cost needs a sparse method that gives up some links.
- Trap: "A longer context window costs nothing extra." Better: A longer window means a bigger grid, so time and memory rise with the square of the length.

## Can you spot the full grid?

**Spot the full grid:** Your team reviews three attention snippets. Which one builds the full n by n score grid?

A. scores = [dot(q[i], k[j]) for i in range(n) for j in range(n)]
B. scores = [dot(q[i], k[j]) for i in range(n) for j in range(w)]
C. scores = [dot(q[i], k[i]) for i in range(n)]

**Answer:** A. The first loop visits every token i and every token j, so the grid is n by n. The second stops at a window of w tokens, and the third compares each token only with itself.

**Quick check:** A bank's support bot must read a 60 page policy in one go. Which fact explains why the cost climbs when the policy gets longer?

A. Attention compares every token with every other token, so the grid grows with the square of the length.
B. The bank's fee schedule was updated last month.
C. The policy file is saved as a PDF.
D. The bot's randomness setting is too high.

**Answer:** A. Attention compares every token with every other token. Double the policy and the grid is four times bigger. The fee schedule, the file format and the randomness setting leave the grid unchanged.

## Can you answer these from memory?

**Flash cards**

- **Why is attention quadratic?** Every token is scored against every token, so n tokens make n times n scores.
- **What does doubling the length do?** The attention grid is four times bigger, so the attention work quadruples.
- **What two things cost n squared?** The arithmetic to fill the grid, and the memory to hold it while it works.
- **What does FlashAttention change?** It keeps the same answer, moves less data, and its memory grows linearly, not with the square.
- **What is the trade-off of sparse attention?** Cost grows linearly, but a token can miss links it would have seen in the full grid.
- **Why does long context cost so much?** Attention grows with the square of the length, in both compute and memory.

## Likely follow-up questions

- Q043 What is self-attention? https://designervenkat.online/interview/ai/what-is-self-attention
- Q055 What is the KV cache, and why does it speed up generation? https://designervenkat.online/interview/ai/what-is-the-kv-cache
- Q057 What is FlashAttention? https://designervenkat.online/interview/ai/what-is-flashattention
- Q058 Multi-query vs grouped-query attention? https://designervenkat.online/interview/ai/multi-query-vs-grouped-query-attention
- Q059 Sliding-window and sparse attention? (full answer coming)

## Learn it in depth

- [Self-Attention](https://designervenkat.online/learn/machine-learning/self-attention)
