Phase 07 / Transformers & language models
Attention from small pieces
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 90 minutes · CPU practice
Implement scaled dot-product attention and test its output shape.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Data & checkpoint recovery
Hardware: CPU
Setup help: Python, notebook, or Cloud TPU VM
Use the tested CPU packages (the recorded environment uses Python 3.14.3). Other Python versions require separate checks. Hardware receipts apply only to their recorded source, environment, hardware, and cases; they do not qualify every lesson or TPU configuration. See the TPU performance and hardware evidence guide. The optional Cloud TPU specialization explains target-specific execution boundaries. Logical CPU devices practice partitioning; they do not simulate TPU performance.
Download the repository ZIP or use your existing checkout. Extract it and open a terminal in the folder containing requirements-cpu.txt. The beginner ZIP is separate; these lessons use the full repository folder.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txtpy -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txtAfter activation, run the complete worked example from that same folder:
python phases/07-transformers/01-attention-from-small-pieces/code/main.py.\.venv\Scripts\python.exe phases/07-transformers/01-attention-from-small-pieces/code/main.pyFor an incremental build, create main.py in your own practice folder, append each build block in order, and run python main.py with this environment active. Keep that file separate from the downloaded reference solution.
Download this lesson’s notebook. Open it with a Python kernel using the course environment. Run cells from the top after restarting the kernel; experiments depend on earlier definitions.
For local Jupyter, first install the course requirements using the Local Python steps, then use your environment’s Python to start Jupyter:
python -m pip install jupyterlab
python -m jupyter lab.\.venv\Scripts\python.exe -m pip install jupyterlab
.\.venv\Scripts\python.exe -m jupyter labSelect the downloaded transformers-01.ipynb file in JupyterLab. The notebook contains reference solutions; make your prediction and attempt each practice task before opening them. Restart the kernel before changing logical device setup.
The worked reference for this lesson is CPU-validated. Some references explicitly configure logical CPU devices; setting JAX_PLATFORMS does not adapt them to a TPU. Follow the execution matrix and reviewed multi-host example before attempting a target run.
For accelerator preparation, study TPU setup, observed runtime receipts, checkpointed jobs and precision and retained traces. Current receipts cover bounded v5e1 launch, resume, and precision checks; four single-device Pallas cases; and a four-device v5e collective fixture. Each receipt is limited to its recorded source, environment, cases, and hardware. It does not qualify all lessons or TPU configurations. Cloud provisioning is optional for CPU learning.
Check: Uniform weights ; both output rows .
Revisit the guided CPU setup · Open 19: TPU Setup. Package instructions are CPU instructions; Windows and accelerator environments need their own validation.
What you will be able to do
- Track query, key and value axes
- Derive the uniform-query result
- Scale scores and keep softmax stable
- Test relationships that should survive a change
The problem
When a model reads a sequence, how can one position use information from another? We’ll build a single attention head as a weighted average. Start with a query whose answer we know, then change the query and watch which values it emphasizes. Small arrays let us see every part of the calculation.
The idea
Attention uses queries and keys to determine weights, then combines values using those weights. Scores describe compatibility; values provide the content being mixed. The attention matrix is an intermediate computation rather than the model's complete output.
Calculate one weighted value mixture
Attention answers two linked questions: which keys should this query use, and what content do their values contribute? Start with weights we can inspect directly: . The weights sum to one, but the output coordinates need not.
On a heatmap, follow one query row across the eligible keys, then apply those weights to the corresponding value rows. If you change a value while holding weights fixed, the mixture changes but the heatmap does not. Predict the mixture before reading the computed output.
Track query, key and value axes
The shapes explain that recipe. With and , has shape : one row per query and one column per key. Softmax over the last axis gives each query its own distribution across keys. Multiplying by three value rows produces two output rows; the value width can differ from key width .
A rectangular example exposes a transposed-axis mistake that square shapes can hide. In the code, check each intermediate shape and ask: is this reduction choosing among keys for each query?
Q (Tq, Dk) @ Kᵀ (Dk, Tk) → scores (Tq, Tk)
softmax over Tk → weights (Tq, Tk)
weights @ V (Tk, Dv) → output (Tq, Dv)Derive the uniform-query result
A zero query has dot product zero with every key, so softmax receives and returns . The three values sum to , so their mean is ; the recorded run prints that output for both queries. This gives a known answer for checking both normalization and value mixing.
Keep this special case separate from the nonuniform permutation exercise: uniform weights make every value-only permutation preserve the mean. The exercise declares a nonzero query and a fixture where changing value order changes its output. A heatmap row is a weighted average, not an index selecting one value.
Scale scores and keep softmax stable
As feature width grows, dot products can grow in scale under common initialization assumptions. Dividing by moderates that scale; it does not prevent every possible input from producing saturated weights. The independent NumPy reference subtracts each row maximum before exponentiating, while JAX softmax uses a stable normalization.
Adding the same finite constant to every score in one row leaves its softmax unchanged. Use that invariance as a check, then inspect unusually concentrated weights in context rather than treating scaling as a guarantee.
Test relationships that should survive a change
Use invariants to check that the computation still means the same thing after a controlled edit. Adding a shared vector to every value should add to each output because each weight row sums to one. Permuting keys with their paired values preserves the same weighted terms; permuting values alone usually changes which content each score selects.
The recorded nonuniform fixture prints original and paired outputs as , while the value-only result is . The separate zero-query example still stays at its mean under any value permutation. Use the exercise's explicit fixture to distinguish the general behavior from that uniform exception. Since this head is unmasked, it can read future positions and is not yet a next-token model.
Read attention as matching, then mixing
The compact equation assigns a job to each stage: and form compatibility scores, row-wise softmax turns them into weights , and mixes the content. The score divisor uses key width ; each row of is nonnegative and sums to one.
For the zero-query example, all three scores tie, so the value mixture is their mean, . Check this by hand before moving from the single head to learned projections.
From the attention head to a decoder stack
The small Q/K/V exercise isolates one weighted mixture. A decoder adds learned projections, multiple heads, normalization, residual paths, token embeddings and causal blocks. In the optional text foundations, compare the independent NumPy attention row with the model output before interpreting a generated token. Its small CPU pilot is documented in projects/text-harness/foundations/README.md; it is a separate workflow from the original four-stage one-block harness.
Each query distributes one unit of attention
Predict before looking: Why do the initial rows have equal weights?
Read the figure
Rows are queries, columns are keys, and each cell is the attention weight assigned to that key; the shared color scale runs from to . Read horizontally because each query's weights normalize across keys. In the zero-query panel every cell is about . In the changed-query panel, query 0 assigns about , and query 1 assigns .
Connect it to the computation
The changed queries and score keys ; key 2 ties with the matching coordinate, so each row has two largest weights. The code applies softmax to these scores, then multiplies the resulting row by the value matrix. In the uniform panel that weighted sum is ; the changed panel's weights alone do not tell you its output until you combine them with values. Next, predict how changing one value row affects output without changing these weights.
Figure data and execution details
Open full-size figureDownload data and provenance
The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.
Your build: Create a separate main.py in your practice folder. Append each block in order and run python main.py in the lesson environment. The downloaded script is the complete reference, so keep it separate from your attempt.
1 Prepare the experiment
In the CPU environment from setup, create main.py and add this block. Write down the dimensions and the known result before continuing.
# Step 1 — 1. Prepare the experiment
import jax
import jax.numpy as jnp
import numpy as npThese imports provide JAX array transformations and NumPy reference calculations. Define the numerical functions next; the final build block supplies the concrete fixture and checks.
2 Implement the mechanism
Append this block in the same file. Follow the shape diagram above and identify each reduction or state transition.
# Step 2 — 2. Implement the mechanism
def attend(q, k, v):
scores = q @ k.T / jnp.sqrt(q.shape[-1])
weights = jax.nn.softmax(scores, axis=-1)
return weights @ v, weightsMultiplying by gives scores of shape . Softmax normalizes each query’s weights across the keys. Multiplying by then gives an output of shape .
3 Run and check
Append this block and run python main.py. Compare its output with your prediction. An assertion failure means a stated contract needs investigation.
# Step 3 — 3. Run and check: Uniform weights 1/3; both output rows [2, 2].
q = jnp.zeros((2, 2))
k = jnp.array([[1., 0.], [0., 1.], [1., 1.]])
v = jnp.array([[2., 0.], [0., 4.], [4., 2.]])
output, weights = attend(q, k, v)
print("Weights / output:", weights, output)
assert jnp.allclose(weights, jnp.full((2, 3), 1/3))
assert jnp.allclose(output, jnp.array([[2., 2.], [2., 2.]]))
assert jnp.allclose(jnp.sum(weights, axis=-1), 1.)Uniform weights ; both output rows . The separate permutation exercise declares its own nonuniform Q/K/V fixture and does not depend on the later q_new experiment.
Explain the APIs in this step
jnp.zeros(shape, dtype=...): Creates a JAX array of the requested shape filled with zeros.jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.jnp.full(shape, fill_value, dtype=...): Creates an array of the requested shape with every element set tofill_value.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — 1. Prepare the experiment
import jax
import jax.numpy as jnp
import numpy as np
# Step 2 — 2. Implement the mechanism
def attend(q, k, v):
scores = q @ k.T / jnp.sqrt(q.shape[-1])
weights = jax.nn.softmax(scores, axis=-1)
return weights @ v, weights
# Step 3 — 3. Run and check: Uniform weights 1/3; both output rows [2, 2].
q = jnp.zeros((2, 2))
k = jnp.array([[1., 0.], [0., 1.], [1., 1.]])
v = jnp.array([[2., 0.], [0., 4.], [4., 2.]])
output, weights = attend(q, k, v)
print("Weights / output:", weights, output)
assert jnp.allclose(weights, jnp.full((2, 3), 1/3))
assert jnp.allclose(output, jnp.array([[2., 2.], [2., 2.]]))
assert jnp.allclose(jnp.sum(weights, axis=-1), 1.)Run the example
python3 phases/07-transformers/01-attention-from-small-pieces/code/main.pyAbout this command
This shortcut uses an activated macOS/Linux course environment in the repository folder. For Windows, use the explicit interpreter command in “Setup help” above. The script includes worked examples and reference solutions.
Inspect the complete assembled example
# Step 1 — 1. Prepare the experiment
import jax
import jax.numpy as jnp
import numpy as np
# Step 2 — 2. Implement the mechanism
def attend(q, k, v):
scores = q @ k.T / jnp.sqrt(q.shape[-1])
weights = jax.nn.softmax(scores, axis=-1)
return weights @ v, weights
# Step 3 — 3. Run and check: Uniform weights 1/3; both output rows [2, 2].
q = jnp.zeros((2, 2))
k = jnp.array([[1., 0.], [0., 1.], [1., 1.]])
v = jnp.array([[2., 0.], [0., 4.], [4., 2.]])
output, weights = attend(q, k, v)
print("Weights / output:", weights, output)
assert jnp.allclose(weights, jnp.full((2, 3), 1/3))
assert jnp.allclose(output, jnp.array([[2., 2.], [2., 2.]]))
assert jnp.allclose(jnp.sum(weights, axis=-1), 1.)Expected result: Uniform weights ; both output rows .
Recorded output and runtime details
Reference output captured from executing the complete lesson script (code/main.py) and its assertions in the course CPU environment.
Weights / output: [[0.33333334 0.33333334 0.33333334]
[0.33333334 0.33333334 0.33333334]] [[2. 2.]
[2. 2.]]
Weights / output: [[0.33333334 0.33333334 0.33333334]
[0.33333334 0.33333334 0.33333334]] [[2. 2.]
[2. 2.]]
original / paired / value-only: [[2.6748495 1.3251503]] [[2.6748495 1.3251503]] [[2. 2.6748495]]
zero-query mean: [[2. 2.]]
PASS: transformers-01
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Compare a nonzero query with NumPy
# Experiment — Compare a nonzero query with NumPy
q_new = jnp.array([[2., 0.]])
actual, w_new = attend(q_new, k, v)
# Transfer the device result to the host for an independent NumPy comparison.
scores_np = np.asarray(q_new) @ np.asarray(k).T / np.sqrt(2)
# Reduce along axis=-1 to compute `raw`.
raw = np.exp(scores_np - scores_np.max(axis=-1, keepdims=True))
# Reduce along axis=-1 to compute `reference_w`.
reference_w = raw / raw.sum(axis=-1, keepdims=True)
np.testing.assert_allclose(w_new, reference_w, rtol=1e-6, atol=1e-6)
# Transfer the device result to the host for an independent NumPy comparison.
np.testing.assert_allclose(actual, reference_w @ np.asarray(v), rtol=1e-6, atol=1e-6)Expected: Keys and receive equal larger weights than key .
A separate NumPy calculation checks nonuniform weighting and the output axis.
Shift every value vector
# Experiment — Shift every value vector: Row-normalized attention preserves a shared value translation.
shift = jnp.array([5., -2.])
shifted, _ = attend(q_new, k, v + shift)
assert jnp.allclose(shifted, actual + shift)Expected: Each output shifts by .
Row-normalized attention preserves a shared value translation.
Make it yours
Where to put your code: Modify your own main.py, or use the Make it yours cell in your downloaded notebook. Run your attempt in the declared environment and verify your prediction before opening the reference solution.
Start from the explicit independent fixture below: q_ex = [[2, 0]], k_ex = [[1, 0], [0, 1], [1, 1]], and v_ex = [[2, 0], [0, 4], [4, 2]]. Implement attend using the declared starter. Show algebraically why permuting keys and their paired values together preserves the weighted sum. Then test order [2, 0, 1] for both the paired permutation and a value-only permutation. Compare each result to the original output with NumPy. State why the separate zero-query worked example cannot show a value-only change.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- Independent nonuniform fixture: q_ex=[[2,0]], k_ex=[[1,0],[0,1],[1,1]], v_ex=[[2,0],[0,4],[4,2]], and permutation order [2,0,1].
Outputs
- Original attention output, paired-permutation output, and value-only-permutation output compared with an independent NumPy reference.
Invariants to check
- Permuting keys and their paired values together preserves the weighted sum.
- A value-only permutation can change the result for this nonuniform fixture; this is not guaranteed for every query/value set.
- Zero queries produce a uniform-weight mean that is invariant under value permutations.
Hints
- Implement scaled scores, softmax over keys, then weights @ values.
- Write the paired permutation as a reindexing of the same sum.
- Run the full solution using only the fixture declared in this starter.
import jax
import jax.numpy as jnp
def attend(q, k, v):
"""Return attention outputs and normalized key weights."""
# TODO: compute scaled query-key scores, normalize over keys, and mix values.
raise NotImplementedError
q_ex = jnp.array([[2., 0.]])
k_ex = jnp.array([[1., 0.], [0., 1.], [1., 1.]])
v_ex = jnp.array([[2., 0.], [0., 4.], [4., 2.]])
order = jnp.array([2, 0, 1])1. Key functions & syntax to use:
jnp.array(values, dtype=...)— Constructs a JAX array from Python/NumPy values.
Reveal the reference solution
# Exercise solution: all inputs are declared here, independent of prior experiments.
import jax
import jax.numpy as jnp
import numpy as np
def attend(q, k, v):
scores = q @ k.T / jnp.sqrt(q.shape[-1])
weights = jax.nn.softmax(scores, axis=-1)
return weights @ v, weights
q_ex = jnp.array([[2., 0.]])
k_ex = jnp.array([[1., 0.], [0., 1.], [1., 1.]])
v_ex = jnp.array([[2., 0.], [0., 4.], [4., 2.]])
order = jnp.array([2, 0, 1])
original, weights = attend(q_ex, k_ex, v_ex)
paired, paired_weights = attend(q_ex, k_ex[order], v_ex[order])
value_only, _ = attend(q_ex, k_ex, v_ex[order])
assert jnp.allclose(paired, original)
assert not jnp.allclose(value_only, original)
# Independent NumPy reference for the original and both permutations.
def numpy_attend(q, k, v):
scores = q @ k.T / np.sqrt(q.shape[-1])
exp_scores = np.exp(scores - scores.max(axis=-1, keepdims=True))
w = exp_scores / exp_scores.sum(axis=-1, keepdims=True)
return w @ v
np.testing.assert_allclose(original, numpy_attend(np.asarray(q_ex), np.asarray(k_ex), np.asarray(v_ex)), rtol=1e-6, atol=1e-6)
np.testing.assert_allclose(paired, numpy_attend(np.asarray(q_ex), np.asarray(k_ex[order]), np.asarray(v_ex[order])), rtol=1e-6, atol=1e-6)
np.testing.assert_allclose(value_only, numpy_attend(np.asarray(q_ex), np.asarray(k_ex), np.asarray(v_ex[order])), rtol=1e-6, atol=1e-6)
# For any permutation p, sum_i w_i V_{p(i)} generally changes when w is nonuniform.
# With q=0, all w_i=1/3 and the output is mean(V), invariant under every permutation.
zero_query, _ = attend(jnp.zeros((1, 2)), k_ex, v_ex)
assert jnp.allclose(zero_query, v_ex.mean(axis=0, keepdims=True))
print("original / paired / value-only:", original, paired, value_only)
print("zero-query mean:", zero_query)Use a different value dimension
Transfer / diagnosis
Make each value a single scalar . Check the output shape and zero-query mean.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Make each value a single scalar . Check the output shape and zero-query mean.
Outputs
- One scalar attention output per query and a zero-query mean check.
Invariants to check
- The key/value row pairing remains aligned and the query axis is preserved.
Hints
- The score matrix does not depend on Dv.
import jax.numpy as jnp
def practice_use_a_different_value_dimension(values):
"""Implement the use a different value dimension check."""
# TODO: Construct scalar values with shape (3,1), attend with a zero query, and assert the output shape and arithmetic mean.
raise NotImplementedErrorShow a hint
The score matrix does not depend on Dv.
Reveal reference solution and reasoning
# Use a different value dimension (Transfer / diagnosis)
scalar_v = jnp.array([[3.], [6.], [9.]])
scalar_out, _ = attend(q, k, scalar_v)
# Check tensor shape invariant: `scalar_out.shape == (2, 1)`
assert scalar_out.shape == (2, 1)
assert jnp.allclose(scalar_out, 6.)Queries and keys share ; values may have an independent feature dimension.
Expose a wrong softmax axis
Transfer / diagnosis
Normalize zero scores along axis and compare row sums with the intended contract. Repair the axis.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Normalize zero scores along axis and compare row sums with the intended contract. Repair the axis.
Outputs
- Both row-sum diagnostics and a corrected attention-weight matrix.
Invariants to check
- For each query, probabilities sum across key positions.
Hints
- Two queries and three keys make the incorrect result visible.
import jax.numpy as jnp
def practice_expose_a_wrong_softmax_axis(scores):
"""Implement the expose a wrong softmax axis check."""
# TODO: Normalize a zero score matrix across axis zero, inspect column sums, and implement the key-axis normalization.
raise NotImplementedErrorShow a hint
Two queries and three keys make the incorrect result visible.
Reveal reference solution and reasoning
# Expose a wrong softmax axis (Transfer / diagnosis): A legal operation can normalize the wrong axis.
wrong_w = jax.nn.softmax(jnp.zeros((2, 3)), axis=0)
assert jnp.allclose(wrong_w.sum(axis=-1), 1.5)
right_w = jax.nn.softmax(jnp.zeros((2, 3)), axis=-1)
assert jnp.allclose(right_w.sum(axis=-1), 1.)A legal operation can normalize the wrong axis. Rectangular shapes expose the mismatch.
Diagnose the result
If weights sum to rather than , inspect the softmax axis on the score matrix. If paired key/value permutation changes the output, check that the same order was applied to both arrays. Repair the axis or pairing, then rerun the independent NumPy and translation checks.
Carry forward
- A separate NumPy calculation checks nonuniform weighting and the output axis.
- Row-normalized attention preserves a shared value translation.
Keep your evidence
Keep the Q/K/V axis diagram, zero-query hand mean, independent nonuniform fixture and NumPy output, paired permutation invariance and one value-only permutation result. Explain the zero-query exception and repair a wrong softmax axis.
Save your modified code, its output, and an explanation of your prediction. Checkpoint answers and exercise evidence are tracked separately.
Saved in this browser. Export or back up your portfolio anytime in My learning.
Reference execution: CPU validation only. This worked reference is validated on CPU. Accelerator compatibility requires a separate source review and target execution receipt. Use the execution matrix to review device selection and data ownership before adapting a separate target program. Execution matrix and target qualification.