Training Systems · Local CPULaptop CPULesson 1 of 6 in Phase 06

Phase 06 / Data & checkpoint recovery

Design an input pipeline

Revision v0.18.1 ·

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.

macOS / Linux terminal · repository folder
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-cpu.txt

PowerShell · repository folder
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-cpu.txt

After activation, run the complete worked example from that same folder:

macOS / Linux terminal · activated environment
python phases/06-recovery/01-design-an-input-pipeline/code/main.py

PowerShell command · repository folder
.\.venv\Scripts\python.exe phases/06-recovery/01-design-an-input-pipeline/code/main.py

For 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.

Check: Batch sizes [4,4,3][4,4,3]; 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.

Stage 1 of 5 · Understand the MechanismCore mental model, equations & visual walkthrough

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 (id,x,y)(id,x,y), 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 [9,10,4,1,0,7,6,8,2,5,3][9,10,4,1,0,7,6,8,2,5,3], with batch sizes [4,4,3][4,4,3].

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.

multiset⁡(π(0),…,π(N−1))=multiset⁡(0,…,N−1),ℓˉ=∑imiℓi∑imi\operatorname{multiset}(\pi(0),\ldots,\pi(N-1))=\operatorname{multiset}(0,\ldots,N-1),\qquad \bar\ell=\frac{\sum_i m_i\ell_i}{\sum_i m_i}

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 [2,5,3][2,5,3]. 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 arrays

Make 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 [4,0,5,10,6,2,1,9,7,3,8][4,0,5,10,6,2,1,9,7,3,8] 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 [4,4,3][4,4,3], 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.

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

Recorded environment: JAX 0.9.2 · 1 CPU device

The notebook contains the data experiment, plotting code, and recorded figure output. Rerun it to test your changes.

Stage 2 of 5 · Build & Run the ReferenceStep-by-step code construction & verified execution output

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.

main.py · append build step 1
# 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.

main.py · append build step 2
# 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.

main.py · append build step 3
# 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 raises AssertionError when values differ beyond tolerance.
View the cumulative build in main.py

These blocks append in order to your separate practice file.

main.py · cumulative Python build
# 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.py
About 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
main.py · complete Python 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 [4,4,3][4,4,3]; 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.

2026-10-27T17:04:40.833518+00:00 · Python 3.14.3 · JAX 0.9.2 · 1 CPU device

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.

Stage 3 of 5 · Controlled ExperimentsPredict before running & test boundary conditions

Compare epochs without a hard-coded order

Compare epochs without a hard-coded order · Python experiment
# 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

Expose dropped records · Python experiment
# 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.

Stage 4 of 5 · Hands-On Exercise & CheckpointModify the code yourself, solve transfer tasks & test your understanding
Hands-On Exercise · Modify & Verify Run in the declared lesson environment

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.
Your attempt · complete the TODOs
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 NotImplementedError
Reveal the reference solution
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.
Your attempt · complete the TODOs
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 NotImplementedError
Show a hint

The fingerprint includes dtype, shape and array bytes.

Reveal reference solution and reasoning
Fingerprint meaning, not just a row count · Python solution
# 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 y=2x−1y=2x-1 provides a stronger oracle than a falling training loss.
Your attempt · complete the TODOs
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 NotImplementedError
Show a hint

The known relation y=2x−1y=2x-1 provides a stronger oracle than a falling training loss.

Reveal reference solution and reasoning
Catch a feature/label shuffle mismatch · Python solution
# 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)!=fingerprint

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.

Check your understanding

What information is missing from a model-only checkpoint for mid-epoch recovery?

Choose one answer

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.

Stage 5 of 5 · Keep Your EvidenceRecord your verification receipt & carry takeaways forward

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

Download evidence template

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.

Save work for this lesson

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.

Primary references