The sequence models of 3-7 squeezed everything seen so far into a single hidden state and walked forward one step at a time. Attention changes the idea. Whenever it needs to, it looks again at every earlier position and pays more attention to the relevant ones. We follow the numbers of the query (Q), key (K) and value (V) by hand, and see why the Transformer, built by stacking these parts, became the backbone of today's language models — and what it costs.
An encoder–decoder RNN packs a whole sentence into one fixed-length vector and processes positions one at a time, in order. As sentences get longer, two things become problems.
Bottleneck: an encoder–decoder translation model shrinks the source sentence into one fixed-length vector and then produces the translation from it. Bahdanau et al. saw this fixed-length vector as the performance bottleneck and proposed letting the model look up the relevant parts of the source by itself each time it produces a word of the translation [R1]. This is attention. Waiting in line: an RNN must know ht before it can compute ht+1, so positions cannot be computed at the same time. The Transformer removed recurrence entirely and computed all positions at once with attention alone, which made training much faster [R2].
We translate "초파리가 사과를 먹었다" into "The fly ate the apple". Each time an English word is produced, attention is shared among the Korean words. The thicker the line, the larger the attention.
The Korean order is "초파리가 (the fly) · 사과를 (the apple) · 먹었다 (ate)", while the English order is "The fly · ate · the apple". The verb sits in a different place. So when producing "ate", the model must look hard at "먹었다" at the very end. The attention values in this figure are numbers set for explanation. A real translation model finds such correspondences by itself through training, and Bahdanau et al. reported that the learned attention agrees well with human intuition [R1]. All attention values are between 0 and 1 and sum to 1 (softmax).
Attention(Q, K, V) = softmax(Q·Kᵀ / √dk) · VVaswani et al., 2017
| Symbol | In the library | In a neural network |
|---|---|---|
| Q Query | A note saying what I am looking for | A vector expressing "what the current position needs". Input × WQ |
| K Key | The index card attached to each book | A vector expressing "this is the kind of information I am" for each position. Input × WK |
| V Value | The actual content of the book | The information each position actually hands over. Input × WV |
| Q·K | How well the note matches the card | The dot product of the two vectors. The more similar their directions, the larger it is |
| ÷ √dk | — | Prevents the dot product from growing with vector length and making softmax pile onto a single position [R2] |
| softmax | Dividing reading time among the books | Turns the scores into attention that sums to 1 |
| × V | Mixing the contents in proportion to time spent reading | Adds up the values using attention as weights. This is the output |
In section 3 the question and the books were separate. In self-attention, every word of the sentence is a query, a key and a value at once. Each word shares its attention among all the other words.
The word vectors were set by hand with four slots: [animal, food, action, pointer word]. The query transform WQ was set so that "pointer words look for food, actions look for animals". The key and value transforms are left as they are. A real Transformer learns the word vectors and WQ·WK·WV through training, and they are hundreds of slots wide. The formula is exactly the same as in this example. Code 1 produces the same numbers.
A sentence holds several layers of relationships. "Who ate?" and "What was eaten?" are different questions. Each head uses its own WQ·WK·WV to look at a different relationship, and the results are concatenated.
Attention compares all positions at once. So even if the word order is shuffled, each word's result is exactly the same. To tell it the order, a "positional encoding" that differs for each position is added to the word vectors.
The original paper put sin(pos / 100002i/d) in the even slots for position pos and cos(…) in the odd slots [R2]. The front slots oscillate quickly and the back slots slowly, so each position gets a different pattern. It is like reading the second, minute and hour hands of a clock together to fix a single time. Learning the positional encoding through training is also widely used. The small Transformer in code 2 uses a learned position embedding.
One Transformer block consists of multi-head attention and a feedforward neural network (the MLP from 3-2). Each gets a shortcut that adds its input back unchanged (residual connection) and normalization, and these blocks are stacked in many layers.
The same block serves different purposes when you change "which position can see which" (the mask).
The reasons the Transformer came into wide use can be summed up in three points. They come with costs. The biggest cost is attention computation that grows with the square of the length.
Same task as 3-7 code 2 (every step is ±1, the answer is the first step) and same training settings (Adam 0.005, 30 epochs, 2,000 training and 1,000 test samples, 2 seeds). The Transformer uses one self-attention block (width 16, 2 heads) and a learned position embedding. "Attention to first step" is the mean of the attention that every position gives to the first position.
This part covers the Transformer up to its architecture. Generative models that use this architecture to produce text and images (pretraining of large language models, instruction tuning, diffusion models, etc.) are outside the scope of this series. The following parts (3-4 Speech, 3-6 Time Series & Stock Prices, 3-5 Text) focus on the process of turning data into numbers.
Both code examples use only libraries preinstalled in Colab. After "Download notebook (.ipynb)", open it in Colab with File → Upload notebook, or copy the code and paste it into a new notebook cell.
Computes the library example, five-word self-attention, two heads, and order shuffling with positional encoding, using the same numbers as the page. To use your own data, change BOOK_K·BOOK_V·QUERIES or the word vectors X.
Solves again, with a Transformer of a single self-attention block, the task on which LSTM failed at long lengths in 3-7. It also measures how much attention the trained Transformer gives to the first step, where the answer is. The table below section 9 is built directly from this output.
These are prompts to paste into AI assistants such as ChatGPT, Qwen, or Claude. Pressing "Copy" attaches the chosen code after the prompt. Replace the parts in 〔 〕 with your own situation.
An AI's answer is only a starting point. Always check any papers, figures, or library functions it suggests against the original sources and official documentation. If you used AI help for a competition entry or paper, disclose the fact and extent of its use according to the rules of the organizers and the journal.
This is the same dictionary as the yellow dotted underlines in the text. The same terms are used throughout the series. Click a section name to jump to where the term first appears.
Analogies are a first step to understanding, but they can also seed misunderstanding. Fruit fly and brain analogies are marked by strength. Direct evidence that they actually do the same thing · Partial only some properties are similar · None no known counterpart
| Concept | Everyday analogy | Fruit fly / brain analogy | Where the analogy breaks down |
|---|---|---|---|
| Attention | Highlighting the important pages when studying for an exam | Partial Human selective attention (focusing on one voice in a noisy place) | Attention in the brain is a phenomenon tangled up with senses, intentions, fatigue and more. A model's attention is only a weighted average set by dot products and softmax |
| Q·K·V | The library's question note, index cards and book contents | None | A library brings you one book, but attention mixes all the books in proportion |
| Softmax attention | Dividing reading time among the books | None | Time is used up however you divide it, but even a position with attention 0.01 is still fully computed (which is why it costs n²) |
| Multi-head | Several editors reading the same document from different viewpoints | None | A head's "viewpoint" is not set by people. When interpreted after training, many heads show no clear role |
| Positional encoding | Reading the second, minute and hour hands of a clock together fixes the time | None | A clock comes back around after a day, but positional encoding is familiar only within the lengths it was trained on |
| Residual connection | Always keeping the original pinned next to the edited manuscript | None | The key point is that the original is "added back as is". If the edits are small, the original passes almost unchanged to the next layer |
| Mask (GPT-style) | Covering the answer sheet and solving the next question by looking only at the earlier ones | None | During training all positions are computed at once. Only the "visible range" is covered |
E-1 About the author · E-2 Academic references · E-3 Figure sources
A guide for instructors, on-the-job (OJT) trainers, and tutors. Times are estimates; adjust them to your actual class.
| Audience | University students and working professionals who have finished 3-7. Practitioners who want to know "what parts language models are built from" |
|---|---|
| Prerequisites | Dot product of vectors (multiply matching positions and add), softmax and MLP from 3-2, encoder–decoder from 3-7 |
| Learning objectives | ① Compute the attention formula softmax(QKᵀ/√d_k)V with numbers ② Explain why self-attention, multi-head attention and positional encoding are each needed ③ Explain both why the Transformer became the foundation and its n² cost |
| Estimated time | Reading 45–55 min · animation demos 25 min · Colab practice 30 min (code 1 10 min, code 2 run 8 min + interpretation 12 min) |
Intro 5 min (section 1 bottleneck) → sections 2·3 library 15 min → sections 4·5 10 min → section 6 order shuffling 10 min → section 9 n² and code 2 results 5 min → check questions 5 min.
Sections 1·3 15 min → section 8: link the three architectures to work cases (classification, summarization, translation) 20 min → section 9 cost calculation (with your own document lengths) 15 min → code 2 run and interpretation 25 min → prompt cards 15 min.
Beginners: sections 1·2·3·9 only. Intermediate learners: have them compute the result vector of section 3 by hand and compare it with code 1, and derive the 4d² + 4d of section 7 themselves.
| Section | Questions to pause and ask | Hands-on tips |
|---|---|---|
| 1 Remaining problems | "If a 40-word sentence is packed into an 8-slot vector, how many slots does each word get?" | Switch from 5 to 40 words and watch the numbers change |
| 2 Attention | "Why does the model look at the last word when producing ate?" | Stop at the "ate" button |
| 3 Q·K·V | "Couldn't we just fetch the book with the largest attention?" | With "Curious about both", watch the result mix into [5.5, 5.5] |
| 4 Self-attention | "What does 'it' refer to? How did the model know?" | Press it → sweet in that order, and also see the limits of hand-set rules |
| 5 Multi-head | "If we increase the heads to 8, do the parameters grow 8 times?" | Check the parameter count at model width 512 |
| 6 Position | "If the result is the same even after shuffling the order, what is the problem?" | Press no positional encoding → shuffled order → add, in that order |
| 7 Block | "Is most of a block's parameters in attention or in the feedforward network?" | Read the "feedforward share" in the base model |
| 8 Encoder·Decoder | "Why does the GPT style have to hide future positions?" | Press Decoder only and point to the × cells of the mask |
| 9 Strengths & limits | "If a document becomes twice as long, how many times more attention computation is needed?" | Switch 4,096 → 32,768 to compare memory, then move on to the experiment table below |
| Misconception | Correct explanation | Scene to show |
|---|---|---|
| Attention picks the single most important word | It mixes all words in proportion. Words with small attention also enter the result | Section 3 "Curious about both" |
| The Transformer knows order by itself | Without positional encoding, shuffling the order gives the same result | Section 6 |
| People assign a role to each head | Roles emerge through training. The two heads on this page were set by hand for explanation | Section 5 and the explanation below it |
| The Transformer is better than an RNN in every way | It is strong at long-range connections and parallel computation, but it costs the square of the length and can be at a disadvantage with small data | Section 9 |
| The attention map is the reason for the model's judgment | It only shows where the model looked while computing; it does not guarantee why the judgment is right | "sweet" in section 4 |
q·k = 2×2 + 0.4×0 = 4. 4 / √2 ≈ 2.828. This equals the score of book A in section 3.
Attention ≈ [0.238, 0.238, 0.525]. Result = 0.238×[10,0] + 0.238×[0,10] + 0.525×[6,6] ≈ [5.53, 5.53]. The output of code 1 is [5.525, 5.525].
It stays exactly the same. Each word's output is determined only by "comparison with all other words", and the set of things compared is the same regardless of order. In code 1 the difference was 1e-16 (the level of rounding error).
W_Q·W_K·W_V·W_O are each 512 × 512, with 512 biases each: 4 × 262,144 + 4 × 512 = 1,050,624. Changing the number of heads only shrinks the head width; the matrix sizes stay the same, so the count is unchanged.
4 times. (2n)² = 4n². It goes from 4,096² = 16,777,216 to 8,192² = 67,108,864.
In code 1, compute how the attention in the library example changes if you do not divide by √d_k. Explain in two sentences how the effect of the division grows when the vectors are scaled up 10 times.
In code 2, remove the Transformer's position embedding (AddPosition) and train again. Report how the results and the "attention to first step" change with 3 or more seeds, and write the reason, linking it to section 6.
| Beginners | Sections 5·7 can be skipped without breaking the flow. Make sure to calculate just the library of section 3 by hand |
|---|---|
| Advanced | Have learners research and present ways to reduce the n² cost of section 9 (looking at the input in segments, low-rank approximation, etc.). Verify the papers they find in the original |
| Further learning | Sangsun Ahn, “Data Science for Business” lecture notes (data science in general) · STEP [K-Digital] AI Natural Language Processing (linked to 3-5 and 3-8) · STEP [K-Digital] Fundamentals of Fintech Data Analysis (linked to 3-6) |
| Materials for instructors | Grading criteria for the check questions and sample answers for the assignments are on the answer key page for educators (3-8) |
You've read "3-8 Attention & Transformers" all the way through. Everyone in the lab will sum it up in a word.