What actually transforms in a transformer
Attention routes, the MLP transforms
It was truly frustrating and disheartening. There I was, watching yet another video explaining Q/K/V, a Stanford lecture this time, nodding along and quietly convincing myself it made sense. It did not. I could recite the words, attention, Q/K/V, layer norm, and still not feel what the machine was doing. It was as though my ability to learn had simply plateaued. So I went back to the best explanation I knew, Jeremy's fast.ai lesson 24, "Attention and transformers". It was not about language models, but that did not matter. That was the key. Do not think about Q/K/V at all.
That might seem counter-intuitive, but what do you think about instead? Just three projections.
Jeremy teaches this on images, not language, and that turns out not to matter at all. Imagine you are comparing two pixels, or two patches, and you do not just want to know whether they look the same. You want to know whether they are similar in some particular way you care about. The pointy-eared way, say. One set of channels in the first patch matching some different set of channels in the second.
To do that, you pass the input through a projection before you compare anything. A projection is just a matrix multiplication, a learned matrix that picks out which channels to pay attention to and which to ignore. You do this twice, with two different projection matrices, so the model can choose one set of channels to look for in the first thing and a different set to look for in the second. That is what lets it decide this is similar to that in the way we care about.
Then there is a third projection. Once similarity has been found, the model does not hand back the original channels, it passes them through a third matrix to decide what information to actually pull out and carry forward.
That is all it ever was. Three learned matrices, three projections. Nobody needs to say query, key, or value to understand any of it. I had spent months, cough, probably years, letting those three words convince me there was a complexity I was missing, some lookup or exact match, like a database. In a hand-wavy way I moved on, thinking I probably understood it. This is not ideal for learning. The idea did not stay learned in my brain. There are three matrix multiplications, and the names were the only confusing part.
Transformers should not be difficult. In essence they work like this.
A piece of text is split into tokens. Each token becomes a vector that carries meaning. A position vector is added so the model knows the order. That vector enters the stream.
Within each block, attention routes and the MLP transforms. Two opposite and complementary jobs. Each one adds its result back onto the stream.
The blocks are stacked many times. The final representation leaves the stream.
That is fairly much it, plus normalisation.
What attention actually does
Projections give you three versions of each token. What does attention do with them?
It routes information. In a language model every token looks back at itself and the tokens before it and decides which ones are relevant to it right now. In Jeremy's image version there is no before or after, a patch can see every other patch, but the operation is identical. It is not a lookup that returns one answer, it is a weighted average over all of them. The first projection is what a token is looking for. The second is what each other token offers up to be matched against. Compare the two and you get a relevance score for every earlier token. Pass those scores through a softmax, which simply squashes them into weights that are all positive and add up to one. That matters because the output is about to be an average, and an average only makes sense if the weights are shares of a whole. Then take a weighted sum of the third projection, the information each token is willing to pass on.
That is the whole operation. Match, weight, mix. The output for a token is a blend of information gathered from the tokens it decided were relevant. If the word "it" needs to know what it refers to, it can look back, find "platypus", weight it heavily, and pull that information in.
Real attention runs several of these routings side by side, the heads, each looking for something different, then a final matrix mixes their results back into one stream. That is a fourth projection, but notice what it is not. It is one more linear map. Nothing in it transforms a token in the way only the MLP can. The three comparison projections gather, the fourth blends, and the whole thing stays pure routing.†
And here is the part that took me far too long to notice. Its main job is not to compute a new feature from one token in isolation. Its job is to decide what context that token receives. The projections reshuffle channels linearly, and the rest is routing, moving those results between tokens and blending them. Once the weights are fixed, the token is not transformed in any way a single matrix could not do. It is simply handed a weighted average of what other tokens were offering. The softmax chooses those weights per input, but it chooses where information flows, not what it becomes. Hold on to that, because it matters more than it looks, and it leads straight to the question in the title.
Attention can choose and blend, but it can not produce something outside the range of its inputs. Because the weights are positive and sum to one, each head's output always sits inside the range of what the other tokens offered. That is where the MLP does its distinctive work.
Before the final output projection, each head produces a weighted average of its value vectors. Because the weights are positive and sum to one, that average sits within the range of what those value vectors offered. This does not mean attention leaves representations unchanged. The value vectors are learned projections, the weights depend on the input, and the output projection remaps the result. But attention is still doing a different job from the MLP. Attention chooses and blends context - the MLP performs the local non-linear reshaping.
Without the MLP, attention can move information around cleverly, even learn to copy patterns, but it lacks the MLP's position-wise non-linear computation. Stack attention alone and there is a risk that representations collapse.
† This is a distinction of jobs, not a strict mathematical separation. Attention changes token representations by mixing in context from other positions through input-dependent weights. The MLP applies a learned non-linear transformation independently at each position. Attention routes. The MLP transforms locally.
The part nobody names it after
So attention has gathered and mixed information from the right places. But it has not done the kind of local non-linear reshaping that the MLP does. Each token is now holding a weighted average of what its neighbours offered, and an average is still just a mixture of things that were already there. Something has to take that mixture and reshape it into something new. That something is the MLP.
The MLP is the plainest part of the whole architecture. It is the same multi-layer perceptron that has existed for decades, the thing most courses teach in week one. It takes each token on its own and passes it through a learned non-linear transformation. It widens the token into a larger space, four times wider is typical, applies a non-linear function so the transformation can be non-linear rather than just another linear matrix operation, then projects it back down to the size it started. Step into a roomier space, do the expressive work where there is room, compress the result back into the stream.
This is the only place in the block where a token's own content is transformed locally, through a learned non-linear map. It is also the only elementwise non-linearity in the block. There are two other non-linearities, the softmax inside attention and the division inside the norm, but both of those mix across a set of values rather than acting on each number on its own. Take the non-linearity out and the whole MLP collapses into a single matrix, which tells you the non-linearity was the entire point. And unlike attention, the MLP acts on each token in isolation. It cannot look at any other token. It has no way to move information between positions at all.
Which gives us the sentence the whole thing turns on.
Attention routes but does not transform. The MLP transforms but cannot route.
That is a useful distinction of jobs, not a claim that attention does nothing to a representation. Attention changes what reaches a token by mixing in context from other tokens. The MLP does the local non-linear reshaping of what is now there.
Two operations doing precisely opposite and complementary jobs. Attention is the only part that moves information between tokens. The MLP is the only part that transforms a token's content. Neither can do the other's job. Stack them together and you get something that can gather context and then make sense of it, over and over, up the depth of the network.
And here is the irony I could not unsee once I had it. The part everyone talks about, the part the famous paper is named after, attention, is the part that does not transform. The part that actually does the transforming is the humble MLP that nobody names anything after, the oldest and least glamorous piece in the box. We call it a transformer, and the thing doing the actual transforming is the bit we never mention.
Zoom out to the whole network and it actually does transform something. It takes a sequence of input embeddings and turns it into a sequence of output representations, and in that whole-system sense it is a transformer of sequences, whichever internal part does the reshaping. The name is not wrong, it is just describing the system from the outside. My bugbear is from the inside, at the level of the components, where the word points at attention and the real transforming happens somewhere else.
Attention routes, the MLP transforms
The shared blackboard
There is one more piece holding all this together, and when I spotted it I relaxed, because it was an old friend. It is the same residual connection from image models, the skip connection that made ResNets trainable. If you came through fast.ai, or you did any computer vision before transformers took over, you already know this one. I recognised it immediately, and suddenly the transformer felt less like alien territory and more like somewhere I had been.
The idea is simple. Instead of each layer replacing what came before, it adds to it. A block takes the current state, computes something, and adds that result back on top. Nothing is thrown away, nothing is overwritten. The information just accumulates.
I find it helpful to picture a shared blackboard running up through the network. The token embeddings are written on it at the bottom. Every block reads what is currently on the board, works out a contribution, and adds that contribution back onto the board. Attention reads the board and writes in the information it gathered. The MLP reads the board and writes in its transformation. Block after block, the board fills up, and nothing is ever rubbed out. Whatever the final state of the board is at the top, that is the output. There is an additional complexity that makes these residual connections a bit more fancy than the image-model version, but we will come back to that later.
The blackboard takes you most of the way, but it has one weakness. A blackboard has empty space, so writing a new note means finding a clear patch to put it in. That quietly suggests each block's contribution sits beside the others in its own spot. The residual stream does not work like that. A contribution is summed into the same slots as whatever is already there, laid on top rather than placed alongside.
So picture an overhead projector instead, if you are old enough to remember them. The token embeddings go on the first acetate at the bottom. Every block does not take a fresh patch of a board, it lays a new transparent sheet over the frame. What you see at any moment is the light coming through all the sheets at once, every mark superimposed into a single combined image. A block reads that combined image, works out its contribution, draws it on a new sheet, and adds that sheet to the pile. Nothing underneath is hidden or rubbed out, it just reads through everything laid down so far.
The frame never changes size, however many sheets you stack. That is the whole point. Adding a sheet enriches the picture without widening the frame, which is exactly addition rather than concatenation, the same choice that separates a ResNet from a DenseNet. The final image, read off the top of the stack, is the output. That is why a token can collect contribution after contribution and still be the same size at the top as it was at the bottom.
This is also why very deep stacks train at all. Because each block only adds a contribution, the gradient has a clean, unbroken path straight down the stream during learning. It was the residual connection that first let image models go genuinely deep, and it does exactly the same job here. The famous loss-surface picture, the one where a deep network's landscape goes from a crumpled mess to something smooth and bowl-shaped once you add skip connections, is the same phenomenon doing the same favour for transformers.
The half-lie, layer norm
By the time I hit layer norm, the pattern was impossible to ignore, and my bugbear with these names was in full swing. Here was another one where the word actively worked against me.
The name tells you it normalises a layer. It does not. It normalises each token on its own, across that token's own features. Picture the activations as a grid, tokens down one side, features along the other. Layer norm works along a single row, taking one token's features and rescaling them to a sensible, standard range. Each token is handled independently of all the others. Nothing is normalised across the layer in the sense the word invites, all the tokens together. The name points at the wrong level entirely.
This was another of those hand-wavy things I had nodded along to and never actually cemented, which stung a little, because I had used normalisation layers in CNNs for years. I knew how to drop a batch norm or a layer norm into an image model and get a result. I had never really sat with what the thing computed. So I went back to the fantastic fast.ai lesson 17 on initialisation and normalisation, and this time I made myself understand it rather than recognise it.
What I found there added a twist. Layer norm standardises the numbers, yes, but then it multiplies by a learned scale and adds a learned shift. Here is the part I first got wrong. Those learned numbers are per feature, and they are shared across every token. The mean and variance being removed are per token, a separate pair for each token computed across its own features. A scale and shift that is the same for every token cannot reproduce a different mean and variance for each one, so it cannot undo the standardisation. The per-token normalisation always happens, and it keeps happening all through training. What the learned numbers give you is not an escape from normalisation, it is control over the scale and offset that follow it. Jeremy's way of putting it stuck with me. The overall scale and offset of the activations used to be smeared across every weight in the matrix, and all this really does is pull those degrees of freedom out into tidy learnable numbers that are easy for the optimiser to steer.
So the name misleads in one real way. It is not about the layer, it is per token. The normalising part itself is honest, and it stays honest once training is under way. It earns its place, it keeps the numbers in a sane range so the next operation has something well-behaved to work with, and it hands training an easy set of knobs for scale and offset. Useful job, misleading name. A more honest label would be something like per-token feature normalisation.
Seeing it in the code
At this point I wanted to see the whole thing in one place, small enough to hold in my head. Andrej Karpathy wrote exactly that, a complete GPT that trains and generates, in pure Python with no dependencies at all. His own note at the top says it best, the file is the complete algorithm and everything else is just efficiency. I am going to ignore the training half entirely here, the autograd and the optimiser, and look only at the forward pass, the part that turns tokens into a prediction. That is the machine we have been building. Here is the whole of it, piece by piece.
It starts exactly where the blackboard section said it would, with meaning and position added together.
tok_emb = state_dict['wte'][token_id] # token embedding
pos_emb = state_dict['wpe'][pos_id] # position embedding
x = [t + p for t, p in zip(tok_emb, pos_emb)] # joint token and position embedding
That x is the blackboard. It is created once, here, and from now on everything is written back onto it by addition. Watch it.
Now the promise I made earlier, the bit that is a little fancier than the image-model version. I said each block adds to the stream. Look more closely and it adds twice, not once.
# 1) Multi-head Attention block
x_residual = x
x = rmsnorm(x)
...
x = [a + b for a, b in zip(x, x_residual)]
# 2) MLP block
x_residual = x
x = rmsnorm(x)
...
x = [a + b for a, b in zip(x, x_residual)]
Two stashes of x_residual, two adds. Normalise, attention, add. Then normalise, MLP, add. So a block is not one residual step, it is two, one wrapping the routing and one wrapping the transforming, each writing its own contribution onto the board. That is the fancy bit. And notice the normalise sits on the branch that computes the contribution, never on the stream itself, so the board rolls on untouched underneath.
Inside the attention block, there they are. The three projections, no query, key or value in sight.
q = linear(x, state_dict[f'layer{li}.attn_wq'])
k = linear(x, state_dict[f'layer{li}.attn_wk'])
v = linear(x, state_dict[f'layer{li}.attn_wv'])
Three linear calls. Three matrix multiplications. That is the whole mystery that the names had wrapped in a database metaphor for me, sitting right there as three lines of ordinary code.
Then the routing itself, match, weight, mix.
attn_logits = [sum(q_h[j] * k_h[t][j] for j in range(head_dim)) / head_dim**0.5 for t in range(len(k_h))]
attn_weights = softmax(attn_logits)
head_out = [sum(attn_weights[t] * v_h[t][j] for t in range(len(v_h))) for j in range(head_dim)]
The first line scores how well the first projection matches the second, across every earlier position. The softmax turns those scores into weights that sum to one. The third line is the weighted sum of the third projection. Information is gathered and blended here. Attention changes a token by bringing it context. Its distinctive job is routing, rather than the MLP's local non-linear transformation. The division by the square root of the head size keeps the scores from growing as the head widens, so the softmax does not saturate.
I am showing a single head here. The real code runs several in parallel and then a final linear with attn_wo stitches their outputs back together, the fourth projection from earlier, still linear, still pure routing.
That scoring line is also where a piece I had always hand-waved finally fell into place, and it fell into place precisely because I was reading the code rather than a diagram. This little model adds position at the very start, a learned entry from the wpe table bolted onto each token before anything else happens. Modern models mostly do not. They use rotary position embeddings, RoPE, and for the longest time I could say the word and nod along without feeling it.
Then I sat with this scoring line in a SolveIt session, working through it a piece at a time and being asked to explain each one, and it clicked. Look at what the line is. It is a dot product between the first projection and the second, a measure of how similar two tokens are. That is all a relevance score is, a similarity. And if the thing you care about for position is not where a token sits in absolute terms but how far apart two tokens are, then the place to inject position is not at the input at all. It is right here, inside the comparison. RoPE rotates the two projections by an amount that depends on their positions, so that when you take this dot product, the result depends on the difference between those positions. Relative distance, baked straight into the similarity.
Nothing about RoPE had got simpler. What changed is that I finally had the surrounding picture solid enough that the new piece had only one sensible place to go. The score is a similarity, position should enter the similarity, so rotate the things being compared. Of course. That is what understanding the core actually buys you, the next idea arrives almost for free, and it was walking the code line by line, out loud, that got me there.
And the MLP, the part that actually transforms.
x = linear(x, state_dict[f'layer{li}.mlp_fc1']) # widen
x = [xi.relu() for xi in x] # the only elementwise non-linearity
x = linear(x, state_dict[f'layer{li}.mlp_fc2']) # back down
Widen, apply the one genuine non-linearity, come back down. mlp_fc1 is four times the width, just as we said. This is the only place a token's own content is reshaped, and the relu is the only elementwise non-linearity in the whole block. Take it out and those two matrix multiplies collapse into one. The non-linearity was the point.
There is one quiet detail that made me smile, and it closes the layer norm thread. The code does not use layer norm at all. It uses rmsnorm.
def rmsnorm(x):
ms = sum(xi * xi for xi in x) / len(x)
scale = (ms + 1e-5) ** -0.5
return [xi * scale for xi in x]
This is the modern simplification, and it normalises per token across that token's own features, exactly the reading I had to fight for. It also drops two things layer norm does. There is no mean-centering, it divides by the root mean square without subtracting the mean first, and in this code there is no learned scale or shift at all. I like to imagine the field quietly conceded my complaint, though in truth RMSNorm won because it is cheaper and works just as well. Either way the name earns its keep. Root mean square norm says exactly what it computes, it squares, takes the mean, takes the root, and divides, with no misdirection about layers and no pretending to do more than it does.
Finally the board is read off into a prediction.
logits = linear(x, state_dict['lm_head'])
One last projection from the stream to a score for every possible next token, and the softmax after it turns those into probabilities. That is the entire forward pass. Embeddings in, blackboard up the middle, routing and transforming written onto it block after block, scores out.
Every single thing we talked about is in there, and nothing we did not talk about is needed for the architecture itself. The real models add efficiency and scale on top, GeLU instead of ReLU, many layers instead of one, fast tensor operations instead of these little scalar values. But the machine is this. You can read it in an afternoon.
Why the distinction matters
Transformer is a fair name for the whole system. The network turns a sequence of input representations into a sequence of output representations.
The useful distinction is inside the block. Attention changes a token by mixing in context from other positions. The MLP changes it through a local non-linear transformation. Attention answers what information should reach this token now. The MLP answers what should this token compute from what it has.
That is not a competition over which component deserves the word transform. It is a way to see why the two components are paired so effectively.
How I actually got here
There is a second lesson tangled up with the first, and it is about how I finally got here rather than what I learned. For a long time my way of studying this was to read another explanation or watch another video, which is how I ended up nodding along to that Stanford lecture while nothing stuck. The mainstream AI chat tools did not help as much as you would hope. They are relentlessly verbose, and no amount of custom instruction telling them to be concise really holds. Asking them to explain a mechanism tends to bury the one sentence I needed under five paragraphs I did not. I tried making ChatGPT build infographics with me to produce a concise explanation, and every one of them failed. They numbered the steps correctly, attention as 1, the MLP as 2, and then draw the MLP first before attention.
What got me past my own plateau was building the thing myself in small steps and being caught the moment I was vague. Say a piece, have it questioned, correct it, move on. That is the SolveIt way of working, the human staying in the driving seat, and it is the only reason this understanding stuck when years of hand-waving had not. It is also, I realise, the same lesson as the names. Learning is a compression problem. A good, concise, corrected step helps you. A wall of words, however fluent, does not.
I only knew the infographic was wrong because by then I understood the mechanism. The tool could produce a confident, clean, numbered diagram that was subtly broken, and the only defence against that is to have built the understanding yourself. That is the argument for you staying the agent.
One last picture
I will leave you with the metaphor I kept thinking about while making the diagrams for this, because it is too fitting to waste. The infographics I tried to produce were drawn in the style of Macross, the show whose transforming Valkyrie fighters I grew up with. There is a real piece of history there. The original Macross Valkyrie toy was licensed and rebadged into the Transformers line as the Autobot Jetfire. Same physical airframe, lifted into a different universe and given a new name to fit the new story.
That is this whole post in a single toy. The machine does not change. The name it is given depends on which story you are telling about it, and the name you inherit can quietly tell you the wrong story about what you are looking at. A VF-1 told it is an Autobot. Layer norm told it works on layers. Three projections told they are a database. Ignore the name for a moment, and look at what the thing actually does.
Part of the Robotech/Macross inspired infographic, whose whole did not quite work