4.1.13 · D2Transformer Architecture

Visual walkthrough — Computational complexity of attention

2,417 words11 min readBack to topic

Before we start, three plain-English words we will use constantly. No symbol appears until it is drawn.

So is just a table: one row per word, one column per feature. Every figure below starts from this table.


Step 1 — What a matrix multiply costs

WHAT. Everything in attention is matrix multiplication. So before anything else we must agree on the price of ONE multiply. Take a grid with rows and columns, times a grid with rows and columns. The rule of matrix multiply: to fill one output cell, you slide along a full row of the left grid and a full column of the right grid, multiplying pairs and adding them up.

WHY this tool. We count multiplications because on a computer/GPU the multiply-add is the unit of work — a "FLOP" (floating-point operation). Counting FLOPs is how we compare architectures fairly, independent of which chip runs them.

PICTURE. In the figure, one output cell (coral) needs one row (lavender) dotted with one column (mint). That row/column each have length , so one cell costs multiply–adds. There are cells to fill.

Figure — Computational complexity of attention

Multiply those two: total cost . Memorise this; every later step is just plugging numbers into .


Step 2 — Turning tokens into Q, K, V

WHAT. From the input table (size ) we make three new tables by multiplying with three learned weight grids . In multi-head attention each of these is a single block that internally holds all heads side by side — column-block is head 's slice of width . So one matrix multiply produces every head's queries at once; we never do separate small multiplies. Here is the head dimension — the width each token gets inside one attention head.

  • ::: input, rows (tokens) by columns (features)
  • ::: fixed learned grids, tall by wide — but read as side-by-side blocks, one per head
  • ::: full outputs ; slicing off head 's columns gives that head's query/key/value table

WHY. A query is "what am I looking for?", a key is "what do I offer?", a value is "what I'll hand over if chosen". We need all three before any comparison happens. This step is self-attention's setup, and the block view is exactly how multi-head attention packs heads into one multiply.

PICTURE. Three arrows fan out of , each producing an table sliced into head-blocks of width .

Figure — Computational complexity of attention

Cost, using Step 1's rule with (the full block does all heads):

Notice: this grows once with . Double the words, double the work. That is linear — gentle. Hold that thought; it is NOT where the pain comes from. (If you only look at a single head, its slice costs ; summing over all heads gives again — same number, since .)


Step 3 — Every token meets every token:

WHAT. Now the heart, done inside one head. We multiply that head's (size ) by — the "T" means transpose, flipping on its side so its shape becomes .

  • ::: query rows, each of length
  • ::: keys flipped, so now tall by wide
  • ::: the score matrix, — cell = how much token cares about token

WHY transpose? We want the dot product of query with key (a dot product measures agreement — big when two vectors point the same way). To line up "row of " against "row of " as a matrix multiply, must be turned sideways so its rows become columns. That is exactly what does.

PICTURE. This is the moment the output stops being tall-thin and becomes a full square — one cell for every ordered pair of tokens.

Figure — Computational complexity of attention

Cost, Step 1 rule with :

There it is — the quadratic term . Why unavoidable? The output has cells because we insisted every token gets a score against every other token. The square shape is the cost.


Step 4 — Softmax: turning scores into weights

WHAT. Each row of becomes a set of proper attention weights. For row :

  • ::: makes every score positive (bigger score → much bigger value)
  • ::: shrinks the scores first so the exponentials don't blow up (a stability scale)
  • denominator sum ::: adds up the whole row, so the weights end up summing to
  • ::: final weight — the share of attention token gives token

WHY. Raw scores can be any size, positive or negative. We need each token's attention to be a clean set of shares (all , summing to ). Softmax is the tool that answers "turn these numbers into a probability split".

PICTURE. A single square row lights up: big-score cells become bright, tiny-score cells fade, and the whole row's brightness sums to one bar of length 1.

Figure — Computational complexity of attention

Cost. For each of the cells we do a constant amount of work: one division by , one , and one accumulation into its row-sum, then one final divide. That is per cell — crucially, the head dimension does not appear here (we already collapsed it away in Step 3). So softmax costs : the same square, touched a constant number of times, with no factor of and no new asymptotic term.


Step 5 — Collecting the answer:

WHAT. Multiply the weight square (size ) by the value table (size ).

  • ::: attention weights,
  • ::: value rows,
  • output row ::: a blend of all value rows, mixed by row 's weights

WHY. Now that token knows how much to trust each other token (that's ), it builds its new representation as a weighted average of everyone's values. This is the payoff of the whole mechanism.

PICTURE. Each output row is a weighted stack of value rows; heavy weights pull their value rows in strongly.

Figure — Computational complexity of attention

Cost, Step 1 rule with :

The second quadratic term — same size as Step 3. So both "compare" and "collect" cost .


Step 6 — The output projection (the term people forget)

WHAT. After the heads are glued back into a full -wide table (size ), one last multiply with (size ) mixes the heads' information:

  • ::: concatenated heads,
  • ::: learned mixing grid,
  • ::: final attention output,

WHY. Each head worked in its own little -slice. lets the heads talk to each other and returns to full model width. See multi-head attention for what the heads are.

PICTURE. Head-slices concatenated into one wide bar, then squeezed through the square .

Figure — Computational complexity of attention

Cost, Step 1 rule with :

Together with the Q, K, V projections of Step 2 (each ), the linear part is about , i.e. .


Step 7 — Adding it all up (and the multi-head twist)

WHAT. Sum every step's price (attention terms summed over all heads).

Step What Cost
2 Q, K, V projections (all heads, one multiply each)
3 scores (per head )
4 softmax (per entry , no )
5 collect (per head )
6 output projection

WHY the two survivors. Softmax's is lower-order than (no factor), so it drops out. Keep only the biggest terms:

Now the multi-head twist. With heads, each head uses . The attention work across all heads is The cancels! And the projections are done once over the full (recall Step 2: a single multiply already outputs every head), not once per head. So:

PICTURE. A bar chart: for small the bar towers; as grows the bar overtakes it — the crossover that forces long-context models toward sparse attention and memory-optimization tricks.

Figure — Computational complexity of attention

The one-picture summary

Figure — Computational complexity of attention

Read it left to right: the tall-thin becomes tall-thin (cheap, linear), those crash together into a fat square (the quadratic villain), softmax paints the square, the square collects values back into a tall-thin output, and mixes it. The square is the whole story.

Recall Feynman retelling — say it in plain words

Imagine a room of people (tokens). First everyone writes three cards: a "want" card, an "offer" card, and a "give" card. Writing cards is quick — it scales with how many people there are, one round of writing. Then comes the expensive part: every person compares their want-card against everyone's offer-card. That's people each doing comparisons — an grid of handshakes. Double the crowd and the handshakes quadruple. After comparing, each person mixes everyone's give-cards in proportion to how much they liked them — another full pass. Finally a group huddle () blends what the different sub-groups (heads) found. The huddle and the card-writing are linear (cheap); the two handshake grids are the quadratic cost that makes long documents so painful.

Recall Quick self-check

Where does the term come from? ::: From producing an score for every token pair, and again from walking that same square. Why don't heads multiply the cost? ::: Each head uses width, so — the cancels; projections run once over full in a single multiply. Which term dominates for very long sequences? ::: (the attention square), because outgrows the linear once . Why doesn't softmax add a factor? ::: It does work per already-computed score cell, so it is — lower-order than .

Related scaling concern for long inputs: positional encoding scaling.