0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09Hook: what does "it" mean?
Read this: "The parcel didn't fit in the box because it was too big." What does "it" refer to? The parcel, obviously. Now change one word: "because it was too small." Now "it" means the box. You resolved that instantly, by looking at the other words in the sentence. To understand language, every word has to do the same: look at the words around it, and update its meaning based on what it finds. That's self-attention: the mechanism at the heart of every transformer, and every modern language model. Today, we build it from scratch: queries, keys and values, the scores, the softmax, the weighted sum, all with real numbers you can check by hand.
Season Two, Module Ten, stop two: self-attention, one of the most important stops on the entire map.
1:05From attention to self-attention
In the last module, attention let a decoder look back at an encoder's words: one sequence attending to another. Self-attention applies the same idea within a single sequence. Every word looks at every word in the same sentence, including itself, decides how relevant each one is, and builds a new version of itself by mixing in information from the relevant ones. The result is exactly what we wanted last episode: contextual embeddings, where "bank" near "cash" and "bank" near "river" end up as different vectors. And unlike an RNN, all the words are processed at the same time, in parallel.
1:51Queries, keys and values (the library analogy)
Self-attention gives every word three different roles, and a library is a good way to picture them. Imagine walking into a library with a question: that's your query. Every book has a label on its spine describing what it's about: that's its key. And every book has its actual contents: that's its value. You compare your query with every label, and you take information from the books whose labels match best. In self-attention, each word plays all three parts. Its embedding is multiplied by three learned matrices to produce a query vector, what this word is looking for; a key vector, how this word describes itself to others; and a value vector, the information it will hand over if chosen.
Those three matrices are learned by backpropagation, so the network discovers what to look for and what to share. To keep today's numbers easy to follow, our tiny example uses the embeddings themselves as the queries and keys. Real models learn all three projections.
2:57Step 1: scores (QKᵀ)
Let's build it with three words: "the parcel arrived", each represented by a tiny two-number vector. Step one: every word's query is compared with every word's key, using a dot product. That fills a three-by-three grid of scores. "The" against "the": one. "The" against "parcel": zero. "The" against "arrived": one. Row by row, the grid fills in. "Arrived" matches itself most strongly, with a score of two. Then we divide every score by the square root of the vector size. Here that's the square root of two, about one point four one.
We'll see why in a moment. In matrix form, the whole grid is Q times K-transpose, divided by root d.
3:47Step 2: softmax, row by row
Step two: turn each row of scores into weights with softmax, so each row becomes a set of positive numbers that add up to one. For "the", the weights are about forty percent on itself, twenty percent on "parcel" and forty percent on "arrived". For "parcel": twenty percent on "the", forty on itself, forty on "arrived". And for "arrived": a quarter on "the", a quarter on "parcel", and half on itself. Each row is one word's attention: how much it will listen to each word in the sentence. On the board, thicker beams mean more attention.
4:27Step 3: the weighted sum of values
Step three: each word builds its new vector by mixing the values of all the words, using its attention weights. For "arrived": a quarter of "the"'s value, one, zero, plus a quarter of "parcel"'s value, zero, two, plus half of its own value, one, one. That comes to zero point seven five, one. Do the same for every word, and each gets a new vector: "the" becomes zero point eight, zero point eight; "parcel" becomes zero point six, one point two. Look at the plot. Each word's new vector is a blend of the values of the words it paid attention to, so it now carries information about its context.
And that's the whole of self-attention, in one line: softmax of Q K-transpose over root d, times V.
5:20Why divide by √d?
Why divide the scores by the square root of d? Because real models use vectors with hundreds of numbers, and dot products of long vectors can get large. If the entries are random with variance one, the dot product's variance grows with d: about four for d equals four, sixty-four for d equals sixty-four, about five hundred for five hundred and twelve. Large scores make softmax extreme. Scores of one, two and three give a gentle spread: nine, twenty-five and sixty-seven percent. Multiply those scores by eight and softmax gives practically everything to one word: ninety-nine point nine seven percent.
When softmax saturates like that, the gradients for the other words almost vanish, and learning stalls. Dividing by root d brings the scores back to a sensible range, so the attention stays soft and trainable. A tiny detail with a big effect.
6:22The causal mask
One important variation. When a model is learning to write, predicting each next word, a word must not peek at the words that come after it. Otherwise it could simply copy the answer. So we apply a causal mask: before the softmax, we set every score for a future word to minus infinity, which becomes a weight of exactly zero. Now "the" can only attend to itself. "Parcel" can see "the" and itself: thirty-three and sixty-seven percent. "Arrived" sees everything before it, which is all three. Without the mask, every word sees the whole sentence, which is ideal for understanding text.
With the mask, each word sees only what came before, which is what we need for generating text. Next episode, that difference splits transformers into two famous families.
7:18Parallel computation and quadratic cost
Self-attention has two huge advantages over recurrent networks. It's parallel: the whole score grid is one big matrix multiplication, perfect for GPUs, instead of a step-by-step loop. And every word connects to every other word directly, in a single step, however far apart they are, so there's no long chain for information or gradients to fade along. The price is that the grid has one cell for every pair of words. A thousand tokens means a million scores. Ten thousand tokens means a hundred million. The cost grows with the square of the length, and that's why long inputs are expensive, a challenge we'll return to in Season Five.
8:02Try it yourself: a learned query
So far, our queries were just the embeddings themselves. Let's give the model a learned query matrix, a simple one that swaps the two numbers. Now "the" asks its question as zero, one. Where will it look? Pause. Its scores become zero, zero point seven one and zero point seven one. After softmax: about twenty percent on itself, and forty percent each on "parcel" and "arrived". Before, "the" mostly looked at itself and "arrived". Same words, same keys, but a different query matrix completely changed where it looked.
That's what training does: it learns the projections that make each word ask the right question.
8:53What do trained attention heads look at?
When researchers inspect trained models, they find heads with recognisable habits. Some always look at the previous word. Some connect a pronoun to the noun it refers to, like "it" back to "parcel" in "the parcel arrived, but it was damaged". Others park their attention on the first token or a punctuation mark when nothing else is relevant. These patterns are fascinating, but be careful: attention weights give hints about what a model is doing, not a complete explanation.
9:28The memory bill of attention
Quadratic cost isn't just about time; it's about memory. With four thousand and ninety-six tokens, one head's score grid has almost seventeen million numbers. Stored at two bytes each, that's about thirty-four megabytes, and eight heads make about two hundred and seventy megabytes for one layer, if they were all kept at once. Double the context, and it quadruples. Modern implementations avoid storing the whole grid by computing attention in small tiles, and we'll look at other tricks in Season Three.
10:04Self-attention beyond words
Nothing in the formula is specific to words. Cut an image into patches, and each patch can attend to every other. Slice audio into short frames, and the same thing works. Brightcart could even treat a customer's history, product views, cart additions and purchases, as a sequence of events and let attention find the patterns that predict what they'll want next. If you can turn something into a set of vectors, self-attention can relate them.
10:36Common mistakes when coding attention
If you code attention yourself, watch for these mistakes. Applying softmax down the columns instead of across the rows. Forgetting the causal mask, so the model peeks at the next word during training: the loss looks amazing, but generation is poor. Forgetting to mask padding. And overflow in the exponentials: the standard fix is to subtract each row's maximum score before applying softmax, which doesn't change the result but keeps the numbers safe.
11:07Attention as a soft dictionary
Here's another way to understand queries, keys and values. In ordinary programming, a dictionary lookup is hard: you ask for "kettle", and you get exactly the value stored under "kettle", or an error. Attention is a soft lookup. The query is compared with every key, and you get back a blend of all the values, weighted by how well each key matches. Because the blend changes smoothly as the query changes, the whole lookup is differentiable, so gradient descent can learn what to ask for and what to store.
11:42Predict: how far apart are two words?
In a hundred-word review, the first word is "not" and the last word is "recommend". How many steps must information travel between them? Pause, first for an RNN, then for self-attention. In an RNN, it must pass through ninety-nine recurrent steps, fading a little at each one. In self-attention, the last word looks straight at the first, in a single step. Short paths mean gradients and information don't have to survive a long journey, which is a big reason transformers learn long-range patterns so well.
12:24Myth vs Fact
Myth: attention means the model understands what it reads. Fact: attention is a mechanism, a learned weighted average that routes information between tokens. It's remarkably powerful, but whatever abilities a model has come from what it was trained on, how large it is and what it was trained to do, which is the story of Season Three.
12:48Recap
Let's recap. In self-attention, every token looks at every token. Each token produces a query, a key and a value through learned projections. Query-key dot products, divided by root d, become scores. Softmax turns each row into attention weights, and each token's output is the weighted mix of the values. Dividing by root d keeps the softmax trainable. A causal mask hides future words for generation. And it's all parallel, at a cost that grows with the square of the length. One sentence to remember: ask with a query, match on keys, and mix the values.
13:29Next: the full transformer
Mission complete. Every word in Brightcart's sentences can now look at its neighbours and become a context-aware vector, and you've computed it by hand. Next, the final episode of Season Two. We'll assemble the complete transformer: multiple attention heads, positional information, feed-forward layers, residual connections and normalisation, and meet its two famous families, BERT and GPT. See you on the map.