Attention and transformers
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A transformer lets every token look at every other token and decide how much each one matters. Follow one worked example of self-attention on "the cat sat", with real numbers: queries, keys and values, dot-product scores, scaling by √d_k, softmax weights and the weighted sum. Then see how heads, feed-forward layers, stacked blocks and positions turn that one step into the model behind GPT.
Tokens become vectors
A transformer reads text as tokens, here "the cat sat". Each token starts as an embedding: a list of numbers for its meaning. Ours have 2 numbers. Alone, each vector ignores its neighbours: "sat" does not know who sat.
token embedding the [1, 0] cat [0, 1] sat [1, 1] each vector was made for the word alone, without looking at the other words
اقرأ الدرس خطوة بخطوة
Tokens become vectors
A transformer reads text as tokens, here "the cat sat". Each token starts as an embedding: a list of numbers for its meaning. Ours have 2 numbers. Alone, each vector ignores its neighbours: "sat" does not know who sat.
token embedding the [1, 0] cat [0, 1] sat [1, 1] each vector was made for the word alone, without looking at the other wordsQuery, key and value
Three learned weight matrices turn every embedding into three new vectors: a query (what am I looking for?), a key (what do I offer?) and a value (what do I pass on?). The query of "sat" is [−1, 1].
query q = x · W_Q W_Q = [[0, 1], [-1, 0]] key k = x · W_K W_K = [[1, 0], [0, 2]] value v = x · W_V W_V = [[0, 1], [1, 0]] token key value the [1, 0] [0, 1] cat [0, 2] [1, 0] sat [1, 2] [1, 1] query of sat: [−1, 1]Score: query · key
Attention compares the query of "sat" with every key using a dot product: multiply matching numbers, then add. For "cat": [−1, 1] · [0, 2] = 2. The scores are the −1, cat 2, sat 1. Bigger means a better match.
s = [dot(q, k) for k in K] the [−1, 1] · [1, 0] = −1×1 + 1×0 = −1 cat [−1, 1] · [0, 2] = −1×0 + 1×2 = 2 sat [−1, 1] · [1, 2] = −1×1 + 1×2 = 1Scale by √d_k
Each score is divided by √d_k, the square root of the key length. Here d_k = 2, so we divide by 1.41: −0.71, 1.41, 0.71. With long vectors, unscaled scores grow huge and learning slows down.
d_k = len(q) = 2 sqrt(2) = 1.414 the −1 / 1.414 = −0.71 cat 2 / 1.414 = 1.41 sat 1 / 1.414 = 0.71 the original transformer: d_k = 64, so it divides by 8Softmax: scores to weights
Softmax turns the scores into weights: raise e to the power of each score, then divide each by their sum. The weights are positive and add up to 1: the 0.07, cat 0.62, sat 0.31. So "sat" attends mostly to "cat".
e = [exp(x) for x in s] w = [x / sum(e) for x in e] the exp(−0.71) = 0.49 / 6.63 = 0.07 cat exp(1.41) = 4.11 / 6.63 = 0.62 sat exp(0.71) = 2.03 / 6.63 = 0.31 sum of weights = 0.07 + 0.62 + 0.31 = 1.00Mix the values
The new vector for "sat" is the weighted sum of the values: 0.07×[0, 1] + 0.62×[1, 0] + 0.31×[1, 1] = [0.93, 0.38]. It now carries information from "cat". That is self-attention.
return mix(w, V) 0.07 × [0, 1] 0.62 × [1, 0] 0.31 × [1, 1] = [0.93, 0.38] "sat" before: [1, 1] after: [0.93, 0.38]Every token at once
Every token does the same with its own query, all at the same time. Written with matrices it is one formula: softmax(QKᵀ / √d_k) V. No token waits for the one before it, so the work runs in parallel on the hardware.
Attention(Q, K, V) = softmax(Q Kᵀ / √d_k) V weights, one row per query: the cat sat the 0.11 0.45 0.45 cat 0.25 0.50 0.25 sat 0.07 0.62 0.31Many heads
One attention finds one kind of match. The original transformer runs 8 attention heads side by side, each with its own weights and vectors of 64 numbers instead of 512. Their outputs are joined and mixed back into one vector per token.
d_model = 512 heads h = 8 d_k = d_model / h = 512 / 8 = 64 each head: its own W_Q, W_K, W_V join the 8 outputs (8 × 64 = 512 numbers), then one more matrix W_O mixes themA transformer block
A block is attention followed by a small feed-forward network applied to each token. Each part adds its result to its input (a residual connection) and then normalises. The original stacks 6 blocks; GPT-3 stacks 96.
x = LayerNorm(x + Attention(x)) x = LayerNorm(x + FeedForward(x)) feed-forward: 512 -> 2048 -> 512 numbers, per token blocks: 6 (original), 96 (GPT-3)Where is each word?
Attention alone ignores word order: shuffle the words and each one gets the same mix as before. So a position signal is added to every embedding first. The original transformer used sine and cosine waves of different lengths.
input = embedding + position signal PE(pos, 2i) = sin(pos / 10000^(2i / d_model)) PE(pos, 2i+1) = cos(pos / 10000^(2i / d_model)) BERT and GPT-2 learn their position vectors insteadPredict the next token
A language model such as GPT stacks only these blocks, with a mask so each token sees only earlier ones. The last vector becomes a probability for every token in the vocabulary. A likely one, "on", is added, and it repeats.
prompt the cat sat mask each token attends to itself and earlier ones last vector -> one probability per vocabulary token pick "on" text the cat sat on ...
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01In self-attention, what does a token's query do?
The query is what the token is looking for. Its dot product with each key gives a score; softmax turns the scores into weights for mixing the values.
02A query is [2, 0] and a key is [1, 3]. What is their dot product, before scaling?
Multiply matching numbers and add: 2×1 + 0×3 = 2. A dot product of two vectors is a single number.
03Why does attention divide the scores by √d_k?
The transformer paper scales by 1/√d_k because large dot products make softmax extremely peaked, with tiny gradients. Softmax, not the scaling, makes the weights add up to 1.
04Softmax gives the weights 0.07, 0.62 and 0.31 for three values [0, 1], [1, 0] and [1, 1]. What is the output vector?
Weighted sum: 0.07×[0, 1] + 0.62×[1, 0] + 0.31×[1, 1] = [0.62 + 0.31, 0.07 + 0.31] = [0.93, 0.38].
05Why does a transformer add a position signal to each embedding?
Self-attention treats its input as a set: shuffle the tokens and each one gets the same mix. A position signal (sine and cosine waves in the original paper) tells the model where each token is.
المسرد
- Token
- A piece of text the model works with: a word or a part of a word. Each token starts as an embedding vector.
- Query, key, value
- Three vectors made from each token's embedding with learned weight matrices: what it looks for, what it offers to be matched, and what it passes on.
- Dot product
- Multiply two vectors number by number and add the results. A bigger dot product means the vectors point more the same way.
- Softmax
- Turns a list of scores into positive weights that add up to 1: raise e to the power of each score, then divide by the total.
- Self-attention
- Each token builds a new vector as a weighted mix of all tokens' values, with weights from how well its query matches their keys.
- Attention head
- One complete attention with its own weight matrices. A transformer runs several heads side by side and joins their outputs.
- Transformer block
- Attention followed by a feed-forward network, each with a residual connection and normalisation. Models stack many blocks.
- Positional encoding
- A signal added to each embedding that tells the model where the token is in the sequence.
الملاحظات والمصادر
- The numbers are a toy: 2 numbers per token and hand-picked weight matrices. Real models learn their weights by gradient descent and use hundreds or thousands of numbers per token (512 in the original transformer).
- Weights are shown to 2 decimals (0.0743, 0.6200, 0.3057); the new vector is computed with the unrounded weights.
- The original transformer (2017) was built for translation: an encoder reads the source sentence and a decoder writes the translation, also attending to the encoder. GPT-style language models keep only the decoder side.
- "on" is an illustration of next-token prediction, not the output of a real model.
- The Python program in the lesson is real: run it and it prints [0.93, 0.38].
- Vaswani et al., Attention Is All You Need (NeurIPS 2017): scaled dot-product attention, multi-head attention, the transformer
- Bahdanau, Cho & Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (2014): the first attention mechanism
- Stanford CS224N, J. Hewitt, Self-Attention & Transformers (course notes, 2023)
- Harvard NLP, The Annotated Transformer: the paper as runnable code
- Goodfellow, Bengio & Courville, Deep Learning (MIT Press, 2016), chapter 6: softmax units
- Radford et al., Improving Language Understanding by Generative Pre-Training (2018): a decoder-only transformer (GPT)
- Brown et al., Language Models are Few-Shot Learners (2020): GPT-3, 96 layers
- Python Library Reference: math.exp and math.sqrt
اختبار يتاح بعد الخطوة الأخيرة.