Key terms for this tutorial
Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.
- attention
- A mechanism where each output position mixes input positions, weighted by how relevant they are.
- model
- A function with learnable parameters that maps inputs to outputs.
- softmax
- A function that turns logits into probabilities that add up to 1.
- token
- A unit of text (word, sub-word, or character) that a language model processes.
- transformer
- An architecture that uses attention to process sequences in parallel instead of one step at a time.
- Transformer
- An architecture that uses attention to process sequences in parallel instead of one step at a time.
Every token looks at every other token
In the sentence 'The cat sat on the mat because it was tired,' the word it could refer to the cat or the mat. To decide, the model needs to relate it to earlier words.
Self-attention gives every token a weighted view of the entire sequence. The weights come from how well each token's 'key' matches another token's 'query'.
Core idea: attention turns a bag of token vectors into a context-aware representation by taking a weighted average. The weights are learned.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Attention and Transformers'. Explain the section 'Every token looks at every other token' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Query, key, and value
For each token, the model learns three projections: a query (what am I looking for?), a key (what do I contain?), and a value (what information do I contribute if selected?).
Attention score = query · key. Softmax turns those scores into a probability distribution. The output is the weighted sum of values.
import numpy as np
def softmax(x):
e = np.exp(x - np.max(x, axis=-1, keepdims=True))
return e / np.sum(e, axis=-1, keepdims=True)
# Three token embeddings
X = np.random.randn(3, 4) # 3 tokens, 4 dims
# Learned Q, K, V projection matrices
W_q = np.random.randn(4, 4)
W_k = np.random.randn(4, 4)
W_v = np.random.randn(4, 4)
Q = X @ W_q
K = X @ W_k
V = X @ W_v
scores = Q @ K.T # (3, 3)
weights = softmax(scores) # each row sums to 1
output = weights @ V # (3, 4)
print("attention weights:\n", weights.round(3))
print("output shape:", output.shape)
attention weights: [[0.366 0.333 0.301] [0.311 0.398 0.291] [0.305 0.296 0.399]] output shape: (3, 4)
Line-by-line: self_attention.py
Read this slowly. Each line does one small, concrete thing.
import numpy as np— Import thenumpylibrary so we can use its built-in tools.def softmax(x):— Define thesoftmaxfunction, which describes a step in the data or model pipeline.print("attention weights:\n", weights.round(3))— Print a result so we can see what the model learned.print("output shape:", output.shape)— Print a result so we can see what the model learned.
Pop-in: Read the code one block at a time
Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Attention and Transformers'. Explain the section 'Query, key, and value' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Multi-head attention and positional encodings
Multi-head attention runs the attention computation several times in parallel with different learned projections. This lets the model capture many kinds of relationships at once: syntax, coreference, topic, and more.
Attention by itself is permutation-invariant: it does not know whether 'cat' comes before 'sat'. Positional encodings add a vector to each token based on its position, giving the model order.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Attention and Transformers'. Explain the section 'Multi-head attention and positional encodings' in plain English. Include simple analogies, vocabulary definitions, and a short example.
The transformer block
A standard transformer block has two sub-layers: attention and a feed-forward network. Each sub-layer is followed by a residual connection and layer normalization. The whole stack is repeated many times.
- Attention mixes information across the sequence
- Feed-forward processes each token independently and adds non-linearity
- Residual connections let gradients skip layers, making deep networks trainable
- Layer norm keeps activations stable
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Attention and Transformers'. Explain the section 'The transformer block' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Check yourself
Why do we need positional encodings?
Self-attention computes a weighted average of all tokens. What information would it be missing without positional encodings?
Attention is permutation-invariant: swapping token order does not change the weighted-average computation. Positional encodings tell the model which token appeared first, second, etc., so it can understand sequence and grammar.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Attention and Transformers'. The practice question 'Why do we need positional encodings?' asks: Self-attention computes a weighted average of all tokens. What information would it be missing without positional encodings? The answer is: Attention is permutation-invariant: swapping token order does not change the weighted-average computation. Positional encodings tell the model which token appeared first, second, etc., so it can understand sequence and grammar.. Explain the concept behind this in simple terms.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Attention and Transformers'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Three questions
1. In self-attention, what does the query do?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Attention and Transformers'. The quiz asks: In self-attention, what does the query do? The correct answer is: It represents what the current token is looking for. Explain why that answer is right and why the other choices are wrong, using a simple example.
2. What function turns raw attention scores into a probability distribution?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Attention and Transformers'. The quiz asks: What function turns raw attention scores into a probability distribution? The correct answer is: Softmax. Explain why that answer is right and why the other choices are wrong, using a simple example.
3. Why is multi-head attention useful?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Attention and Transformers'. The quiz asks: Why is multi-head attention useful? The correct answer is: It lets the model attend to different types of relationships in parallel. Explain why that answer is right and why the other choices are wrong, using a simple example.
Keep learning
Deep dive into scaled dot-product attention, multi-head, positional encodings, and layer norm.
Part of the CodeHS tutorial library.