Phase 06 / Data & checkpoint recovery
Design an input pipeline
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 70 minutes · CPU practice
Build and audit a deterministic batched host pipeline.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Neural network training
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/06-recovery/01-design-an-input-pipeline/code/main.py.\.venv\Scripts\python.exe phases/06-recovery/01-design-an-input-pipeline/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 recovery-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: Batch sizes ; eleven distinct IDs exactly once, aligned labels and repeated order. Preparation time and digest are local observed values.
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 and audit a deterministic batched host pipeline.
- Distinguish membership, order, alignment and final-batch policies.
- Use masks to preserve statistics after padding.
- State what a preparation timing does and does not measure.
The problem
Your dataset has eleven examples, but your model takes batches of four. What happens to the last three? We’ll build a small input pipeline and follow example IDs through shuffling and batching. That lets us catch missing examples or mismatched labels before a model’s loss hides the problem.
The idea
An input pipeline decides which examples reach the model and in what order. Preserve example identities so duplication, omission and split leakage remain detectable. Shapes alone cannot tell us whether the intended data was used.
Preserve identity through shuffling and batching
Treat each record as a small tuple , not as three independent arrays that can drift apart. A shuffle permutes the tuple order; batching groups tuples but should not change which label belongs to which feature. Here a seed gives order , with batch sizes .
Check both membership and alignment after every transform: IDs (0) through (10) appear exactly once, and each label still matches its record's feature rule. A duplicate/drop audit catches a pipeline that returns the right total length while silently repeating one record and omitting another. Preserve the data identity as well as the ordering seed when you need to replay it.
Preserve identity across every transformation
Carry the record ID beside each feature and label through shuffle, map, and batch. In the retained run, the batch boundaries are after positions 3 and 7; the final batch has only IDs . The full sequence still covers all eleven records once.
For a padded batch, a mask must travel with the padded rows. Otherwise the padding can affect a loss or mean as though it were a real observation. The hand calculation compares masked and unmasked label means to show where this changes the result.
record identity → shared index → {id,x,y}
shuffle index, not independent x and y arraysMake epoch ordering a pure decision
The seed determines a permutation, not a continuation cursor. Repeating the same seed reproduces the same first epoch order. A second epoch applies the declared ordering procedure again and produces in the retained run.
A digest over data values detects content edits, while a seed and sampler rule explain ordering. The output's repeated SHA-256 for a copied dataset and changed fingerprint for reordered or relabeled data separate those two questions. A digest identifies bytes; it does not establish that the data are valid.
Choose a deliberate policy for the last batch
Eleven examples divided into batches of four produce two full batches and a three-example remainder. The retained sizes are , and the figure's dotted separators fall after positions 3 and 7. Keeping the remainder preserves all IDs; dropping it omits three examples this epoch.
If the model requires fixed shapes, choose padding plus a mask and apply that mask to losses and reductions. Do not simply count padded rows as real records. For resume, the policy is part of the input contract because it changes where the next epoch begins.
11 records → [4] [4] [3]
drop remainder → [4] [4] + 3 omitted
pad/mask → [4] [4] [3 real + 1 masked]Measure what the stopwatch surrounds
The printed preparation time measures only this local in-memory setup and varies between runs; it is not a sustained input-throughput benchmark. The measured interval also excludes any device training workload. Treat the digest and exact ID order as reproducibility evidence, and use a representative synchronized workload if you need to compare pipeline speed.
Shuffling changes order, not dataset membership
Predict before looking: Where does the short final batch begin?
Read the figure
The horizontal axis is position in the shuffled epoch and the vertical axis is example ID, not loss or a quality score. The line visits IDs (9,10,4,1,0,7,6,8,2,5,3); dotted dividers after positions 3 and 7 create batches of (4,4,3). The last batch is IDs (2,5,3).
Connect it to the computation
Every ID from 0 through 10 appears once, so the plot shows order changing while membership stays fixed. Before fitting, verify the labels remain aligned with these IDs and decide whether to keep or mask the three-example remainder. For recovery, preserve both the ordering rule and the next unread position.
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 data and state
Create main.py in your course workspace. Use the tested course environment and add this block first.
# Step 1 — Prepare the data and state: This setup makes the dataset and software assumptions explicit.
import numpy as np
import hashlib
import time
ids = np.arange(11,dtype=np.int64)
features = (ids/10).astype(np.float32)
labels = (2*features-1).astype(np.float32)
def dataset_digest(x,y):
digest = hashlib.sha256()
for array in (x,y):
digest.update(str(array.dtype).encode())
digest.update(str(array.shape).encode())
digest.update(array.tobytes())
return digest.hexdigest()
fingerprint = dataset_digest(features,labels)
def epoch_order(seed,epoch):
return np.random.default_rng(np.random.SeedSequence([seed,epoch])).permutation(len(ids))This setup makes the dataset and software assumptions explicit. No external dataset or accelerator is required.
2 Build the pipeline or state transition
Append this block to the same file; follow the named state objects through each function.
# Step 2 — Build the pipeline or state transition
def make_batches(seed,epoch,batch_size=4,drop_last=False):
if batch_size <= 0:
raise ValueError("batch_size must be positive")
order = epoch_order(seed,epoch)
for start in range(0,len(order),batch_size):
chosen = order[start:start+batch_size]
if drop_last and len(chosen) < batch_size:
break
yield {"id":ids[chosen],"x":features[chosen],"y":labels[chosen]}
start_time = time.perf_counter()
batches = list(make_batches(seed=17,epoch=0))
elapsed = time.perf_counter()-start_time
seen = np.concatenate([b["id"] for b in batches])The function boundaries expose which inputs determine the next output and which state must be preserved.
3 Run the comparison
Append the checks, save main.py and run python main.py. Predict what should agree before running.
# Step 3 — Run the comparison
assert [len(b["id"]) for b in batches] == [4,4,3]
np.testing.assert_array_equal(np.sort(seen),ids)
assert len(np.unique(seen)) == len(ids)
for batch in batches:
np.testing.assert_allclose(batch["y"],2*batch["x"]-1,atol=1e-7)
repeated = np.concatenate([b["id"] for b in make_batches(17,0)])
np.testing.assert_array_equal(seen,repeated)
print("Batch sizes:",[len(b["id"]) for b in batches])
print("Example order:",seen.tolist())
print("Preparation seconds (local observation only):",elapsed)
print("Dataset SHA256:",fingerprint)The comparison checks the next behavior, not merely whether a save call succeeded.
Explain the APIs in this step
np.testing.assert_allclose(actual, desired, rtol=..., atol=...): Checks a host-side numerical expectation and raisesAssertionErrorwhen values differ beyond tolerance.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — Prepare the data and state: This setup makes the dataset and software assumptions explicit.
import numpy as np
import hashlib
import time
ids = np.arange(11,dtype=np.int64)
features = (ids/10).astype(np.float32)
labels = (2*features-1).astype(np.float32)
def dataset_digest(x,y):
digest = hashlib.sha256()
for array in (x,y):
digest.update(str(array.dtype).encode())
digest.update(str(array.shape).encode())
digest.update(array.tobytes())
return digest.hexdigest()
fingerprint = dataset_digest(features,labels)
def epoch_order(seed,epoch):
return np.random.default_rng(np.random.SeedSequence([seed,epoch])).permutation(len(ids))
# Step 2 — Build the pipeline or state transition
def make_batches(seed,epoch,batch_size=4,drop_last=False):
if batch_size <= 0:
raise ValueError("batch_size must be positive")
order = epoch_order(seed,epoch)
for start in range(0,len(order),batch_size):
chosen = order[start:start+batch_size]
if drop_last and len(chosen) < batch_size:
break
yield {"id":ids[chosen],"x":features[chosen],"y":labels[chosen]}
start_time = time.perf_counter()
batches = list(make_batches(seed=17,epoch=0))
elapsed = time.perf_counter()-start_time
seen = np.concatenate([b["id"] for b in batches])
# Step 3 — Run the comparison
assert [len(b["id"]) for b in batches] == [4,4,3]
np.testing.assert_array_equal(np.sort(seen),ids)
assert len(np.unique(seen)) == len(ids)
for batch in batches:
np.testing.assert_allclose(batch["y"],2*batch["x"]-1,atol=1e-7)
repeated = np.concatenate([b["id"] for b in make_batches(17,0)])
np.testing.assert_array_equal(seen,repeated)
print("Batch sizes:",[len(b["id"]) for b in batches])
print("Example order:",seen.tolist())
print("Preparation seconds (local observation only):",elapsed)
print("Dataset SHA256:",fingerprint)Run the example
python3 phases/06-recovery/01-design-an-input-pipeline/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 — Prepare the data and state: This setup makes the dataset and software assumptions explicit.
import numpy as np
import hashlib
import time
ids = np.arange(11,dtype=np.int64)
features = (ids/10).astype(np.float32)
labels = (2*features-1).astype(np.float32)
def dataset_digest(x,y):
digest = hashlib.sha256()
for array in (x,y):
digest.update(str(array.dtype).encode())
digest.update(str(array.shape).encode())
digest.update(array.tobytes())
return digest.hexdigest()
fingerprint = dataset_digest(features,labels)
def epoch_order(seed,epoch):
return np.random.default_rng(np.random.SeedSequence([seed,epoch])).permutation(len(ids))
# Step 2 — Build the pipeline or state transition
def make_batches(seed,epoch,batch_size=4,drop_last=False):
if batch_size <= 0:
raise ValueError("batch_size must be positive")
order = epoch_order(seed,epoch)
for start in range(0,len(order),batch_size):
chosen = order[start:start+batch_size]
if drop_last and len(chosen) < batch_size:
break
yield {"id":ids[chosen],"x":features[chosen],"y":labels[chosen]}
start_time = time.perf_counter()
batches = list(make_batches(seed=17,epoch=0))
elapsed = time.perf_counter()-start_time
seen = np.concatenate([b["id"] for b in batches])
# Step 3 — Run the comparison
assert [len(b["id"]) for b in batches] == [4,4,3]
np.testing.assert_array_equal(np.sort(seen),ids)
assert len(np.unique(seen)) == len(ids)
for batch in batches:
np.testing.assert_allclose(batch["y"],2*batch["x"]-1,atol=1e-7)
repeated = np.concatenate([b["id"] for b in make_batches(17,0)])
np.testing.assert_array_equal(seen,repeated)
print("Batch sizes:",[len(b["id"]) for b in batches])
print("Example order:",seen.tolist())
print("Preparation seconds (local observation only):",elapsed)
print("Dataset SHA256:",fingerprint)Expected result: Batch sizes ; eleven distinct IDs exactly once, aligned labels and repeated order. Preparation time and digest are local observed values.
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.
Batch sizes: [4, 4, 3]
Example order: [9, 10, 4, 1, 0, 7, 6, 8, 2, 5, 3]
Preparation seconds (local observation only): 0.010051334276795387
Dataset SHA256: 1a81451a8fb32a1bf0ad6307ea19198153ab1603b37174c76c4d498e343e6892
Batch sizes: [4, 4, 3]
Example order: [9, 10, 4, 1, 0, 7, 6, 8, 2, 5, 3]
Preparation seconds (local observation only): 2.258317545056343e-05
Dataset SHA256: 1a81451a8fb32a1bf0ad6307ea19198153ab1603b37174c76c4d498e343e6892
Epoch one order: [4, 0, 5, 10, 6, 2, 1, 9, 7, 3, 8]
Omitted IDs: [2, 3, 5]
Copy preserves fingerprint; reordered source and edited labels invalidate it.
PASS: recovery-01
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Compare epochs without a hard-coded order
# Experiment — Compare epochs without a hard-coded order
epoch_one = np.concatenate([b["id"] for b in make_batches(17,1)])
np.testing.assert_array_equal(np.sort(epoch_one),ids)
assert not np.array_equal(epoch_one,seen)
print("Epoch one order:",epoch_one.tolist())Expected: Same eleven IDs exactly once, different ordering for this tested seed/dataset.
Coverage is an invariant; ordering is a deterministic epoch-specific output. A changed order alone does not imply data loss.
Expose dropped records
# Experiment — Expose dropped records: Logging just the number of batches hides exclusions.
dropped = list(make_batches(17,0,drop_last=True))
dropped_ids = np.concatenate([b["id"] for b in dropped])
assert len(dropped_ids)==8
omitted = np.setdiff1d(ids,dropped_ids)
assert len(omitted)==3
print("Omitted IDs:",omitted.tolist())Expected: Eight retained IDs and three explicitly identified omissions.
Logging just the number of batches hides exclusions. An ID audit exposes which observations were not processed.
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.
Pad the final three-label batch to four elements with zero. Show that an unmasked mean differs, then derive the correct masked mean.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- The final three labels from the lesson’s last batch.
Outputs
- Four padded label slots, a validity mask, the ordinary padded mean, and the masked mean.
Invariants to check
- The padded unmasked mean differs from the mean of the three real labels; the masked mean equals that real-label mean.
Hints
- Build the mask from the number of real labels, not from label values.
- Divide the masked sum by the count of valid elements.
import numpy as np
def compare_padded_and_masked_mean(labels):
# TODO: Pad three labels to four with zero and compare the two means using a validity mask.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Pad the final three-label batch to four elements with zero.
last = batches[-1]["y"]
padded_labels = np.pad(last,(0,4-len(last)))
mask = np.array([1]*len(last)+[0]*(4-len(last)),dtype=np.float32)
masked = (padded_labels*mask).sum()/mask.sum()
np.testing.assert_allclose(masked,last.mean(),atol=1e-7)
assert not np.isclose(padded_labels.mean(),last.mean())Fingerprint meaning, not just a row count
Transfer
Reorder features and labels together, then change one label without changing any shape. Verify that both changes alter the dataset fingerprint while copying unchanged arrays preserves it. Explain why a new iterator order differs from a changed source dataset.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Reorder features and labels together, then change one label without changing any shape. Verify that both changes alter the dataset fingerprint while copying unchanged arrays preserves it. Explain why a new iterator order differs from a changed source dataset.
Outputs
- Three fingerprint comparisons for reordered data, changed labels, and copied arrays.
Invariants to check
- Changes to row order or values alter the fingerprint while exact copies preserve it.
Hints
- The fingerprint includes dtype, shape and array bytes.
import numpy as np
import hashlib
def practice_fingerprint_meaning_not_just_a_row_count(features, labels):
"""Implement the fingerprint meaning, not just a row count check."""
# TODO: Hash canonical feature and label bytes plus shape/dtype metadata; compare reorder, label-edit, and unchanged-copy cases.
raise NotImplementedErrorShow a hint
The fingerprint includes dtype, shape and array bytes.
Reveal reference solution and reasoning
# Fingerprint meaning, not just a row count (Transfer): A sampler permutation can be reproduced against a fixed source.
same=dataset_digest(features.copy(),labels.copy())
reversed_digest=dataset_digest(features[::-1],labels[::-1])
# Accumulate the next contribution into `changed_labels[0]`.
changed_labels=labels.copy()
changed_labels[0]+=0.1
changed_digest=dataset_digest(features,changed_labels)
assert same==fingerprint
assert reversed_digest!=fingerprint and changed_digest!=fingerprint
print('Copy preserves fingerprint; reordered source and edited labels invalidate it.')A sampler permutation can be reproduced against a fixed source. Reordering the source changes which example an index identifies, so restoring only the sampler position would no longer have the same meaning.
Catch a feature/label shuffle mismatch
Challenge
Reverse the target order inside a batch but keep features unchanged. Reject this batch with an independent alignment check, then repair shared indexing.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Reverse the target order inside a batch but keep features unchanged. Reject this batch with an independent alignment check, then repair shared indexing.
Outputs
- An accepted jointly shuffled batch and a rejected split-shuffled batch.
Invariants to check
- Features and labels carry the same row IDs after batching.
Hints
- The known relation provides a stronger oracle than a falling training loss.
import numpy as np
import hashlib
def practice_catch_a_feature_label_shuffle_mismatch(features, labels, order):
"""Implement the catch a feature/label shuffle mismatch check."""
# TODO: Apply one shared permutation to aligned arrays, then deliberately reverse only labels and reject the mismatched rows.
raise NotImplementedErrorShow a hint
The known relation provides a stronger oracle than a falling training loss.
Reveal reference solution and reasoning
# Catch a feature/label shuffle mismatch (Challenge): Wrong alignment can preserve shapes and numeric ranges.
batch = batches[0]
wrong_labels = batch["y"][::-1]
assert not np.allclose(wrong_labels,2*batch["x"]-1)
fixed = labels[batch["id"]]
np.testing.assert_allclose(fixed,2*batch["x"]-1,atol=1e-7)
# Accumulate the next contribution into `changed_labels[0]`.
changed_labels = labels.copy()
changed_labels[0]+=1
assert dataset_digest(features,changed_labels)!=fingerprintWrong alignment can preserve shapes and numeric ranges. Keep common record IDs through transformations, and record dataset identity so restoring an old cursor does not silently select new content.
Diagnose the result
Wrong alignment can preserve shapes and numeric ranges. Keep common record IDs through transformations, and record dataset identity so restoring an old cursor does not silently select new content.
Carry forward
- Preserve identity across every transformation
- Make epoch ordering a pure decision
- Choose a deliberate policy for the last batch
- Measure what the stopwatch surrounds
Keep your evidence
Keep the exact epoch/example ID order, uneven final-batch sizes, hand-derived masked versus unmasked label mean, changed seed order and duplicate/drop audit.
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.