Please enable JavaScript to use CodeHS

AI Engineer

Attention in depth

Transformers are not magic. This deep dive builds a full self-attention head, explains positional encodings, and contrasts encoders and decoders.

AI ~15 min Programmer
Vocabulary

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.
decoder
The part of a language model that generates output tokens one at a time.
positional encoding
Information added to token embeddings so the model knows where each token is in the sequence.

Scores

Scaled dot-product attention

Attention computes softmax(Q K^T / sqrt(d_k)) V. The scale by square root of head dimension keeps dot-product magnitudes stable as dimension grows. Without it, softmax saturates and gradients vanish.

scaled_attention.py
import torch
import torch.nn.functional as F

T, d = 4, 8
Q = torch.randn(T, d)
K = torch.randn(T, d)
V = torch.randn(T, d)

scores = Q @ K.T
scaled = scores / d ** 0.5
weights = F.softmax(scaled, dim=-1)
out = weights @ V
print('weights row sum:', weights.sum(dim=-1))
print('output shape:', out.shape)
Output
weights row sum: tensor([1., 1., 1., 1.])
output shape: torch.Size([4, 8])

Line-by-line: scaled_attention.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn.functional as F — Import the torch library so we can use its built-in tools.
  3. Q = torch.randn(T, d) — Create a tensor filled with random numbers to use as fake data or initial weights.
  4. K = torch.randn(T, d) — Create a tensor filled with random numbers to use as fake data or initial weights.
  5. V = torch.randn(T, d) — Create a tensor filled with random numbers to use as fake data or initial weights.
  6. weights = F.softmax(scaled, dim=-1) — Convert logits into probabilities that add up to 1.
  7. print('weights row sum:', weights.sum(dim=-1)) — Print a result so we can see what the model learned.
  8. print('output shape:', out.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 — Deep Dive'. Explain the section 'Scaled dot-product attention' 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

Why multiple heads?

One head can focus on one type of relationship. Multi-head attention runs several parallel attention operations with different learned projections, then concatenates and projects the result. Different heads can specialise in syntax, long-distance coreference, or semantic similarity.

multihead.py
import torch
import torch.nn as nn

T, d_model, heads = 8, 64, 4
x = torch.randn(T, d_model)
qkv = nn.Linear(d_model, 3 * d_model)
Q, K, V = qkv(x).chunk(3, dim=-1)
Q = Q.view(T, heads, d_model // heads).transpose(0, 1)
K = K.view(T, heads, d_model // heads).transpose(0, 1)
V = V.view(T, heads, d_model // heads).transpose(0, 1)
print('per-head shape:', Q.shape)
Output
per-head shape: torch.Size([4, 8, 16])

Line-by-line: multihead.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn as nn — Import the torch library so we can use its built-in tools.
  3. x = torch.randn(T, d_model) — Create a tensor filled with random numbers to use as fake data or initial weights.
  4. qkv = nn.Linear(d_model, 3 * d_model) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  5. print('per-head shape:', Q.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 — Deep Dive'. Explain the section 'Why multiple heads?' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Position

Positional encodings

Attention is permutation-invariant: it does not know where a token sits. Positional encodings inject order. Sinusoidal encodings use sine and cosine waves of different frequencies, allowing the model to learn relative positions. Learned embeddings are also common in modern models.

posenc.py
import math
import torch

T, d = 4, 8
pe = torch.zeros(T, d)
for pos in range(T):
    for i in range(0, d, 2):
        pe[pos, i] = math.sin(pos / 10000 ** (i / d))
        if i + 1 < d:
            pe[pos, i + 1] = math.cos(pos / 10000 ** ((i + 1) / d))
print('positional encoding shape:', pe.shape)
print(pe.round(decimals=2))
Output
positional encoding shape: torch.Size([4, 8])
tensor([[ 0.0000,  1.0000,  0.0000,  1.0000,  0.0000,  1.0000,  0.0000,  1.0000],
        [ 0.8415,  0.5403,  0.0998,  0.9950,  0.0100,  1.0000,  0.0010,  1.0000],
        [ 0.9093, -0.4161,  0.1987,  0.9801,  0.0200,  0.9998,  0.0020,  1.0000],
        [ 0.1411, -0.9900,  0.2955,  0.9553,  0.0300,  0.9996,  0.0030,  1.0000]])

Line-by-line: posenc.py

Read this slowly. Each line does one small, concrete thing.

  1. import math — Import the math library so we can use its built-in tools.
  2. import torch — Import the torch library so we can use its built-in tools.
  3. for pos in range(T): — Loop over the data one batch at a time.
  4. for i in range(0, d, 2): — Loop over the data one batch at a time.
  5. print('positional encoding shape:', pe.shape) — Print a result so we can see what the model learned.
  6. print(pe.round(decimals=2)) — 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 — Deep Dive'. Explain the section 'Positional encodings' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Check yourself

Check yourself

?

Why scale by sqrt(d_k)?

What happens if Q @ K.T is not scaled before softmax?

Dot products grow with dimension, pushing softmax into very small gradients and producing near-one-hot attention weights.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Attention and Transformers — Deep Dive'. The practice question 'Why scale by sqrt(d_k)?' asks: What happens if Q @ K.T is not scaled before softmax? The answer is: Dot products grow with dimension, pushing softmax into very small gradients and producing near-one-hot attention weights.. 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 — Deep Dive'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Quick quiz

Three questions

1. What does the scale factor sqrt(d_k) prevent?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Attention and Transformers — Deep Dive'. The quiz asks: What does the scale factor sqrt(d_k) prevent? The correct answer is: Softmax saturation from large dot products. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. Why are positional encodings needed?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Attention and Transformers — Deep Dive'. The quiz asks: Why are positional encodings needed? The correct answer is: To give the model order information because attention is permutation-invariant. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. What is the purpose of multi-head attention?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Attention and Transformers — Deep Dive'. The quiz asks: What is the purpose of multi-head attention? The correct answer is: To let the model attend to different representation subspaces in parallel. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Stack attention and FFN blocks into a working mini GPT.

Part of the CodeHS tutorial library.