Phase 07 / Transformers & language models
Masking, tokenization, and sequence packing
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 90 minutes · CPU practice
Construct a causal mask and prevent packed sequences from attending across boundaries.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Attention from small pieces
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/02-masking-tokenization-and-sequence-packing/code/main.py.\.venv\Scripts\python.exe phases/07-transformers/02-masking-tokenization-and-sequence-packing/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-02.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: Causal means ; no weight above the diagonal.
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
- Build a causal mask from positions
- Keep token IDs and targets aligned
- Combine causal and segment boundaries
- Handle padding without an all-masked softmax
The problem
An attention head should not always see every token. For example, a next-token model must not peek at the future. We’ll build a causal mask one row at a time, then add padding and boundaries between packed examples. Before training, you’ll be able to explain exactly which positions may read each other.
The idea
An attention mask controls which positions supply context. A loss mask controls which targets contribute to the objective. Tokenization, target shifting and sequence packing decide the positions to which those different rules apply.
Inspect an attention mask
Read across a query row to see which keys contribute to its output. Allowed cells show their weights; blocked cells are zero. Every row sums to one, apart from display rounding. Equal weights come from equal allowed scores in this example, not from masking alone.
In causal mode, the nonzero triangle includes the current position and its past. Packed mode splits that triangle into two separate examples, so the second cannot read the first. Full context removes both restrictions. Move the last value and watch which outputs change; the weights stay fixed because this control changes values, not scores. This is an analytic browser calculation; the Python experiments verify the same weighted averages in JAX.
Keep context eligibility separate from scored targets
Next-token training has two separate questions: what may a position read, and which target contributes to loss? At input position , the target is token , so a response-only role flag must follow that shifted target. Otherwise the prompt/response boundary can score the wrong token.
A prompt token can be excluded from direct loss while still influencing a scored response through attention. A blocked attention edge changes context; a loss mask changes supervision. For packed examples, also prevent the next segment from reading the previous one and stop targets at the boundary. Trace one query, its allowed keys, and its shifted target before trusting the batch loss.
Build a causal mask from positions
For query position , the causal rule permits keys , including the diagonal. With equal allowed scores, values give prefix means , matching the recorded output. The last position sees all four values; earlier positions see shorter prefixes.
Change the final value and check that the first three outputs remain fixed. That counterfactual tests whether future information can leak backward. If you use a strict triangle that excludes the diagonal, input and target alignment must be changed to match.
allowed key columns
query 0: 1 0 0 0
query 1: 1 1 0 0
query 2: 1 1 1 0
query 3: 1 1 1 1Keep token IDs and targets aligned
Token IDs are positions in a vocabulary table, so the miniature mapping turns abcab into . Next-token training pairs inputs with targets : each target is one step ahead.
At the end of a packed example, do not use the next unrelated example as its target. Mark the boundary with a separator or an ignored loss position. Larger tokenizers add normalization and subword rules, but the ID and target alignment still needs an explicit check; reject unknown characters rather than silently reusing an ID.
Combine causal and segment boundaries
A causal triangle only knows order. For packed segment IDs , positions 2 and 3 begin a new example, so a valid key must be both earlier-or-equal and in the same segment. With the fixture's values, the outputs are : the second segment averages only its own values, rather than inheriting the earlier segment's mean.
Check both halves of the contract separately: the attention mask blocks cross-segment context, and target eligibility stops next-token loss at the segment edge. Reusing one segment ID for unrelated spans would reconnect them.
Handle padding without an all-masked softmax
A padded query may have no valid key. Softmax of an all-negative-infinity row has no normalized distribution and can produce NaNs. The code gives such a query a harmless fallback key, then zeros its output and excludes its loss; real queries keep their original allowed keys.
Treat that fallback as numerical bookkeeping, not semantic content. Perturb padded values and verify real outputs stay unchanged. A real query with no valid key should still fail if that state violates the model contract.
Turn the allowed positions into weights
The heatmap makes the causal rule visible: row is query , column is key ; a blocked future edge is replaced by negative infinity before softmax and therefore gets zero weight when the row has an allowed key. Allowed scores are unchanged. If a row has no allowed key, the code handles it explicitly instead of asking softmax to normalize an empty set.
This mask sets eligibility, not preference: learned scores can still favor one allowed key over another. After a row is normalized, use its weights with the matching value rows to compute the result.
Carry token and segment identity into packed training
The character example isolates index alignment and boundaries. The optional foundations workflow adds reversible UTF-8 bytes and a train-only ByteLevel BPE processor with explicit PAD/BOS/EOS/UNK IDs and byte fallback. Its records are deduplicated and grouped by Project Gutenberg chapter before tokenization; chapters I–IV train, V validates, and VI–VIII remain final test.
Chunk packing records document IDs, preserves each selected text token, masks padding, and blocks attention and next-token loss across document boundaries. Inspect projects/text-harness/foundations/data.py and its report counts to verify that each boundary survives preprocessing.
A causal mask blocks future information
Predict before looking: Which cells must remain zero?
Read the figure
Rows are query positions and columns are key positions; cell color encodes attention weight from 0 to 1. The diagonal and cells left of it are eligible, while cells to the right are future positions and have weight exactly zero. Row 0 puts weight 1 on key 0; row 1 splits across keys 0 and 1; row 2 splits about across keys 0–2; row 3 splits across all four.
Connect it to the computation
The fixture uses equal scores among the keys that remain eligible, which is why the allowed cells are uniform; a causal mask alone does not impose uniform weights. With values , query 2 therefore returns , while the final query returns . Its zero at key 3 is the concrete protection against reading the future value 16. Next, perturb that last value and predict which rows can change; only the final query can use it.
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 masked_mean(values, allowed):
scores = jnp.where(allowed, 0., -jnp.inf)
weights = jax.nn.softmax(scores, axis=-1)
return weights @ values, weights
def make_mask(segment_ids, valid):
positions = jnp.arange(segment_ids.shape[0])
causal = positions[:, None] >= positions[None, :]
same_segment = segment_ids[:, None] == segment_ids[None, :]
return causal & same_segment & valid[:, None] & valid[None, :]allowed key columns query : query : query : query :
Explain the APIs in this step
jnp.arange(n, dtype=...): Creates a 1-D JAX array of evenly spaced values[0, 1, ..., n-1]on the target device.
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: Causal means [2, 3, 4.666667, 7.5]; no weight above the diagonal.
values = jnp.array([[2.], [4.], [8.], [16.]])
causal = jnp.arange(4)[:, None] >= jnp.arange(4)[None, :]
out, weights = masked_mean(values, causal)
assert jnp.allclose(out[:, 0], jnp.array([2., 3., 14/3, 7.5]))
assert jnp.allclose(jnp.triu(weights, 1), 0.)
print("Causal means:", out[:, 0])Causal means ; no weight above the diagonal.
Explain the APIs in this step
jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.jnp.arange(n, dtype=...): Creates a 1-D JAX array of evenly spaced values[0, 1, ..., n-1]on the target device.jnp.allclose(actual, expected, rtol=..., atol=...): Returns a JAX boolean scalar indicating whether corresponding values are within the requested tolerance.
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 masked_mean(values, allowed):
scores = jnp.where(allowed, 0., -jnp.inf)
weights = jax.nn.softmax(scores, axis=-1)
return weights @ values, weights
def make_mask(segment_ids, valid):
positions = jnp.arange(segment_ids.shape[0])
causal = positions[:, None] >= positions[None, :]
same_segment = segment_ids[:, None] == segment_ids[None, :]
return causal & same_segment & valid[:, None] & valid[None, :]
# Step 3 — 3. Run and check: Causal means [2, 3, 4.666667, 7.5]; no weight above the diagonal.
values = jnp.array([[2.], [4.], [8.], [16.]])
causal = jnp.arange(4)[:, None] >= jnp.arange(4)[None, :]
out, weights = masked_mean(values, causal)
assert jnp.allclose(out[:, 0], jnp.array([2., 3., 14/3, 7.5]))
assert jnp.allclose(jnp.triu(weights, 1), 0.)
print("Causal means:", out[:, 0])Run the example
python3 phases/07-transformers/02-masking-tokenization-and-sequence-packing/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 masked_mean(values, allowed):
scores = jnp.where(allowed, 0., -jnp.inf)
weights = jax.nn.softmax(scores, axis=-1)
return weights @ values, weights
def make_mask(segment_ids, valid):
positions = jnp.arange(segment_ids.shape[0])
causal = positions[:, None] >= positions[None, :]
same_segment = segment_ids[:, None] == segment_ids[None, :]
return causal & same_segment & valid[:, None] & valid[None, :]
# Step 3 — 3. Run and check: Causal means [2, 3, 4.666667, 7.5]; no weight above the diagonal.
values = jnp.array([[2.], [4.], [8.], [16.]])
causal = jnp.arange(4)[:, None] >= jnp.arange(4)[None, :]
out, weights = masked_mean(values, causal)
assert jnp.allclose(out[:, 0], jnp.array([2., 3., 14/3, 7.5]))
assert jnp.allclose(jnp.triu(weights, 1), 0.)
print("Causal means:", out[:, 0])Expected result: Causal means ; no weight above the diagonal.
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.
Causal means: [2. 3. 4.666667 7.5 ]
Causal means: [2. 3. 4.666667 7.5 ]
PASS: transformers-02
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Perturb the future
# Experiment — Perturb the future
changed = values.at[-1, 0].set(1000.)
changed_out, _ = masked_mean(changed, causal)
assert jnp.allclose(changed_out[:3], out[:3])
assert not jnp.allclose(changed_out[-1], out[-1])Expected: Only the last output changes.
Perturbation tests whether earlier representations depend on future information.
Pack two independent examples
# Experiment — Pack two independent examples: Causal order alone does not isolate independent packed examples.
segments = jnp.array([0, 0, 1, 1])
valid = jnp.ones(4, dtype=bool)
packed = make_mask(segments, valid)
packed_out, _ = masked_mean(values, packed)
assert jnp.allclose(packed_out[:, 0], jnp.array([2., 3., 8., 12.]))Expected: Packed means .
Causal order alone does not isolate independent packed examples.
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.
Encode abcab with a three-character vocabulary. Create shifted inputs/targets, and a loss-eligibility vector for packed segments that excludes a cross-segment next-token target.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- Token IDs, shifted targets, segment IDs, and a validity mask.
Outputs
- A causal attention mask and loss-eligibility mask that respect segment boundaries.
Invariants to check
- No future token or cross-segment token is visible; padded queries have finite zero outputs.
Hints
- Separate attention permission from target-loss eligibility.
- Give all-masked padded queries an explicit fallback before applying the output mask.
import jax.numpy as jnp
def packed_causal_mask(segment_ids, valid):
"""A causal attention mask and loss-eligibility mask that respect segment boundaries."""
# TODO: Build causal and segment-aware permission masks, then define which shifted targets enter loss.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Encode abcab with a three-character vocabulary.
vocab = {"a":0, "b":1, "c":2}
ids = jnp.array([vocab[c] for c in "abcab"])
assert jnp.array_equal(ids[:-1], jnp.array([0,1,2,0]))
assert jnp.array_equal(ids[1:], jnp.array([1,2,0,1]))
seg = jnp.array([0,0,0,1,1])
loss_valid = seg[:-1] == seg[1:]
assert jnp.array_equal(loss_valid, jnp.array([True,True,False,True]))Repair padding-query NaNs
Transfer / diagnosis
Use valid=[True,True,False,False]. Reproduce the undefined all-masked rows, then give padded queries a fallback and zero their outputs.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Use
valid=[True,True,False,False]. Reproduce the undefined all-masked rows, then give padded queries a fallback and zero their outputs.
Outputs
- Finite attention outputs with padded query rows exactly zero.
Invariants to check
- Valid queries preserve their allowed keys; only invalid padded-query rows use the fallback.
Hints
- Insert a diagonal fallback only for invalid queries.
import jax.numpy as jnp
def practice_repair_padding_query_nans(valid, logits):
"""Implement the repair padding-query nans check."""
# TODO: Create an all-masked padded query, add a numerically safe fallback for that row, and zero its output afterward.
raise NotImplementedErrorShow a hint
Insert a diagonal fallback only for invalid queries.
Reveal reference solution and reasoning
# Repair padding-query NaNs (Transfer / diagnosis)
pad_valid = jnp.array([True,True,False,False])
pad_mask = make_mask(jnp.zeros(4, dtype=int), pad_valid)
bad_pad, _ = masked_mean(values, pad_mask)
assert not jnp.all(jnp.isfinite(bad_pad))
fallback = (~pad_valid[:, None]) & jnp.eye(4, dtype=bool)
pad_out, _ = masked_mean(values, pad_mask | fallback)
pad_out = jnp.where(pad_valid[:, None], pad_out, 0.)
assert jnp.all(jnp.isfinite(pad_out))
assert jnp.allclose(pad_out[:,0], jnp.array([2.,3.,0.,0.]))A fallback makes normalization defined; zeroing and loss masking retain the semantic padding contract.
Detect packed-example leakage
Transfer / diagnosis
Compare causal-only and segment-aware outputs at query . Explain which prior values caused the difference.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Compare causal-only and segment-aware outputs at query . Explain which prior values caused the difference.
Outputs
- Two outputs and a boundary-leakage difference check.
Invariants to check
- A packed query attends only to causal keys from its own segment.
Hints
- Query should see only value from its own segment.
import jax.numpy as jnp
def practice_detect_packed_example_leakage(segment_ids, values):
"""Implement the detect packed-example leakage check."""
# TODO: Compare outputs at query two with causal-only and segment-aware masks, then identify the prior-segment values that change the result.
raise NotImplementedErrorShow a hint
Query should see only value from its own segment.
Reveal reference solution and reasoning
# Detect packed-example leakage (Transfer / diagnosis)
assert jnp.allclose(out[2,0], 14/3)
assert jnp.allclose(packed_out[2,0], 8.)
assert not jnp.allclose(out[2,0], packed_out[2,0])The earlier values and belong to another example; they must be excluded despite being past positions.
Diagnose the result
NaN in a padded output can mean that its mask row permits no keys; count allowed keys before blaming the optimizer. Add a fallback only for invalid queries, zero their outputs, and ignore their loss. If a packed output includes another example’s values, inspect equal-segment and causal conditions separately. Recheck the hand-derived result.
Carry forward
- Perturbation tests whether earlier representations depend on future information.
- Causal order alone does not isolate independent packed examples.
Keep your evidence
Keep token/target alignment, the two masks, future perturbation, segment-leakage comparison and all-masked-row repair. Verify that masks and ignored loss positions enforce the same boundaries.
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.