Phase 06 / Data & checkpoint recovery
Asynchronous checkpoints and failure boundaries
Revision v0.18.1 · Updated since your last visit. Review the changes; your progress is saved.
Lesson · about 90 minutes · CPU practice
Distinguish requested, completed, verified and published checkpoint state. Continue a functional update while an asynchronous writer is alive.
Phase study guide: preparation, milestones and project evidence
Before you start
Before this: Recover data position and resume
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/05-asynchronous-checkpoints-and-failure-boundaries/code/main.py.\.venv\Scripts\python.exe phases/06-recovery/05-asynchronous-checkpoints-and-failure-boundaries/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-05.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: The accepted step remains while the live state reaches . A real local checkpoint restores the saved vector. Both timing intervals are observed and vary by machine.
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
- Distinguish requested, completed, verified and published checkpoint state.
- Continue a functional update while an asynchronous writer is alive.
- Recover from the last accepted checkpoint after an interrupted publication.
- Surface an asynchronous failure before announcing a checkpoint.
The problem
Your training loop says “saved,” then the process disappears. Which step can you safely resume? We will separate an asynchronous save request, completed storage work and the application’s announcement of a recoverable checkpoint. You will interrupt publication deliberately and show which state recovery selects.
The idea
Asynchronous saving overlaps writing with training. A snapshot moves through requested, writing, completed and accepted states. Recovery must select a checkpoint whose completion and validity satisfy the actual storage contract.
Distinguish a save request from a recovery point
A save request, a completed write, a verified restore, and an application-accepted checkpoint are separate events. In the injected publication failure, step (2)'s directory exists, but the LATEST manifest still points to verified step (1). The live state is at step (2), so recovery chooses step (1) and may replay work.
The diagram bars count completed steps, not time: saved snapshot (1), live state (2), accepted checkpoint (1). The gap is work the process completed but the application has not made eligible for recovery. wait_until_finished() completes writer work before this example validates and publishes the manifest; completion alone is not acceptance.
Define a completed training boundary
The teaching state is a weight vector plus its completed-step counter. The code applies a known increment and snapshots step (1); live computation can advance to step (2) without changing the already captured vector. This makes the restore comparison direct instead of relying on a loss that might move unpredictably.
A full training checkpoint must also carry optimizer memory, random state, and the consumed-input position. An asynchronous writer changes when the bytes finish, not which state is required to continue.
Separate save latency from acceptance
The timer around save() records the call's blocking time. A second interval covers the continued update and the remaining wait. In the retained observation, these were about (0.0031) s and (0.0143) s, but they vary by machine and this tiny local fixture does not isolate disk throughput.
Keep the checkpointer alive until its work finishes. Small saves may finish before the caller can observe overlap, so do not require a race. The application invariant is to leave the accepted manifest unchanged until completion and restore checks pass.
Publish a checkpoint you can actually restore
After the wait, restore against the expected target and compare the saved step and every value with the captured snapshot. Only after that check does the example write a temporary sibling manifest and replace the existing LATEST record. The replace keeps a local reader from observing a partially written JSON file.
That local rename is not a general durability or distributed-commit guarantee. Remote object stores, power failures, and concurrent writers need their own supported protocol and failure tests.
Practice interruption without relying on lucky timing
The injected interruption happens after step (2)'s directory is written but before the application publishes it. The unchanged manifest selects step (1), even though the newer directory is visible. A separate finalization callback failure surfaces from the wait, and no manifest is published for that attempt.
These checks test application ordering and error propagation; they do not reproduce every storage failure. Keep the old accepted point until the new point restores and validates successfully.
Translate the boundary into an operational rule
Record requested, completed, and accepted steps separately. This run's failed publication leaves accepted step (1) while live work reaches (2); on restart, the application chooses the former and the replay policy accounts for work after it. If a save is outstanding during orderly shutdown, wait for it; abrupt exit resumes from the last accepted artifact.
When a continuation differs, compare data IDs, optimizer state, key, and contract before loosening numerical tolerances. A matching weight vector or bar height alone does not prove the next transition matches.
A live step can be ahead of the accepted checkpoint
Predict before looking: After the publication interruption, which step will application recovery select?
Read the figure
The horizontal axis names three state positions and the vertical axis counts completed steps, not seconds. Saved snapshot is at step 1, live state at step 2, and accepted checkpoint at step 1. The equal saved and accepted bars contrast with the live bar, which is one step ahead.
Connect it to the computation
After the injected publication interruption, the application selects step 1 even though a step-2 directory exists. Use the acceptance manifest and restored vector to choose the recovery point; bar height alone does not verify contents. The timing intervals and surfaced finalization error answer different questions and do not turn this local experiment into a durability measurement.
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 Define functional state and publication
Create a Python file in the course environment. Add this block after the preceding block, then run the assembled file.
# Step 1 — Define functional state and publication: The manifest has its own acceptance boundary.
import json
import tempfile
import time
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np
import orbax.checkpoint as ocp
root=Path(tempfile.mkdtemp(prefix='jax-async-lesson-'))
def transition(state):
return {'weight':state['weight']+.25,'step':state['step']+1}
def publish(path, step):
pending=root/'LATEST.pending'
# Write the serialized artifact payload to disk.
pending.write_text(json.dumps({'path':str(path),'step':step}))
pending.replace(root/'LATEST.json')
def accepted():
return json.loads((root/'LATEST.json').read_text())The manifest has its own acceptance boundary. State updates return new arrays so later work cannot redefine the snapshot.
2 Save, continue and verify
Create a Python file in the course environment. Add this block after the preceding block, then run the assembled file.
# Step 2 — Save, continue and verify
state={'weight':jnp.arange(1024,dtype=jnp.float32),'step':jnp.array(0,jnp.int32)}
snapshot=transition(state)
path=root/'step_1'
t0=time.perf_counter()
with ocp.AsyncCheckpointer(ocp.StandardCheckpointHandler()) as cp:
cp.save(path,args=ocp.args.StandardSave(snapshot))
returned=time.perf_counter()
assert not (root/'LATEST.json').exists()
live=transition(snapshot)
cp.wait_until_finished()
committed=time.perf_counter()
restored=cp.restore(path,args=ocp.args.StandardRestore(snapshot))
np.testing.assert_array_equal(restored['weight'],snapshot['weight'])
assert int(restored['step'])==1 and int(live['step'])==2
publish(path,1)
report={'save_call_seconds':returned-t0,'remaining_work_and_wait_seconds':committed-returned,
'accepted_step':accepted()['step'],'live_step':int(live['step'])}
assert report['accepted_step']==1Wait on the real background writer, restore against the snapshot contract and publish only after the comparison passes.
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.jnp.array(values, dtype=...): Constructs a JAX array from Python/NumPy values.
3 Interrupt publication deliberately
Create a Python file in the course environment. Add this block after the preceding block, then run the assembled file.
# A deliberately interrupted application publication leaves the previous commit selected.
unpublished=root/'step_2'
with ocp.AsyncCheckpointer(ocp.StandardCheckpointHandler()) as cp:
cp.save(unpublished,args=ocp.args.StandardSave(live))
cp.wait_until_finished()
try:
raise RuntimeError('injected interruption before updating LATEST')
except RuntimeError:
pass
assert accepted()['step']==1
with ocp.StandardCheckpointer() as cp:
previous=cp.restore(accepted()['path'],target=snapshot)
np.testing.assert_array_equal(previous['weight'],snapshot['weight'])
assert int(previous['step'])==1
print('Checkpoint workspace:',root)
print(json.dumps(report,indent=2))
print('Unpublished step 2 exists; application recovery still selects verified step 1.')The injected application interruption leaves the old accepted checkpoint intact even though a newer directory exists.
View the cumulative build in main.py
These blocks append in order to your separate practice file.
# Step 1 — Define functional state and publication: The manifest has its own acceptance boundary.
import json
import tempfile
import time
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np
import orbax.checkpoint as ocp
root=Path(tempfile.mkdtemp(prefix='jax-async-lesson-'))
def transition(state):
return {'weight':state['weight']+.25,'step':state['step']+1}
def publish(path, step):
pending=root/'LATEST.pending'
# Write the serialized artifact payload to disk.
pending.write_text(json.dumps({'path':str(path),'step':step}))
pending.replace(root/'LATEST.json')
def accepted():
return json.loads((root/'LATEST.json').read_text())
# Step 2 — Save, continue and verify
state={'weight':jnp.arange(1024,dtype=jnp.float32),'step':jnp.array(0,jnp.int32)}
snapshot=transition(state)
path=root/'step_1'
t0=time.perf_counter()
with ocp.AsyncCheckpointer(ocp.StandardCheckpointHandler()) as cp:
cp.save(path,args=ocp.args.StandardSave(snapshot))
returned=time.perf_counter()
assert not (root/'LATEST.json').exists()
live=transition(snapshot)
cp.wait_until_finished()
committed=time.perf_counter()
restored=cp.restore(path,args=ocp.args.StandardRestore(snapshot))
np.testing.assert_array_equal(restored['weight'],snapshot['weight'])
assert int(restored['step'])==1 and int(live['step'])==2
publish(path,1)
report={'save_call_seconds':returned-t0,'remaining_work_and_wait_seconds':committed-returned,
'accepted_step':accepted()['step'],'live_step':int(live['step'])}
assert report['accepted_step']==1
# A deliberately interrupted application publication leaves the previous commit selected.
unpublished=root/'step_2'
with ocp.AsyncCheckpointer(ocp.StandardCheckpointHandler()) as cp:
cp.save(unpublished,args=ocp.args.StandardSave(live))
cp.wait_until_finished()
try:
raise RuntimeError('injected interruption before updating LATEST')
except RuntimeError:
pass
assert accepted()['step']==1
with ocp.StandardCheckpointer() as cp:
previous=cp.restore(accepted()['path'],target=snapshot)
np.testing.assert_array_equal(previous['weight'],snapshot['weight'])
assert int(previous['step'])==1
print('Checkpoint workspace:',root)
print(json.dumps(report,indent=2))
print('Unpublished step 2 exists; application recovery still selects verified step 1.')Run the example
python3 phases/06-recovery/05-asynchronous-checkpoints-and-failure-boundaries/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 — Define functional state and publication: The manifest has its own acceptance boundary.
import json
import tempfile
import time
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np
import orbax.checkpoint as ocp
root=Path(tempfile.mkdtemp(prefix='jax-async-lesson-'))
def transition(state):
return {'weight':state['weight']+.25,'step':state['step']+1}
def publish(path, step):
pending=root/'LATEST.pending'
# Write the serialized artifact payload to disk.
pending.write_text(json.dumps({'path':str(path),'step':step}))
pending.replace(root/'LATEST.json')
def accepted():
return json.loads((root/'LATEST.json').read_text())
# Step 2 — Save, continue and verify
state={'weight':jnp.arange(1024,dtype=jnp.float32),'step':jnp.array(0,jnp.int32)}
snapshot=transition(state)
path=root/'step_1'
t0=time.perf_counter()
with ocp.AsyncCheckpointer(ocp.StandardCheckpointHandler()) as cp:
cp.save(path,args=ocp.args.StandardSave(snapshot))
returned=time.perf_counter()
assert not (root/'LATEST.json').exists()
live=transition(snapshot)
cp.wait_until_finished()
committed=time.perf_counter()
restored=cp.restore(path,args=ocp.args.StandardRestore(snapshot))
np.testing.assert_array_equal(restored['weight'],snapshot['weight'])
assert int(restored['step'])==1 and int(live['step'])==2
publish(path,1)
report={'save_call_seconds':returned-t0,'remaining_work_and_wait_seconds':committed-returned,
'accepted_step':accepted()['step'],'live_step':int(live['step'])}
assert report['accepted_step']==1
# A deliberately interrupted application publication leaves the previous commit selected.
unpublished=root/'step_2'
with ocp.AsyncCheckpointer(ocp.StandardCheckpointHandler()) as cp:
cp.save(unpublished,args=ocp.args.StandardSave(live))
cp.wait_until_finished()
try:
raise RuntimeError('injected interruption before updating LATEST')
except RuntimeError:
pass
assert accepted()['step']==1
with ocp.StandardCheckpointer() as cp:
previous=cp.restore(accepted()['path'],target=snapshot)
np.testing.assert_array_equal(previous['weight'],snapshot['weight'])
assert int(previous['step'])==1
print('Checkpoint workspace:',root)
print(json.dumps(report,indent=2))
print('Unpublished step 2 exists; application recovery still selects verified step 1.')Expected result: The accepted step remains while the live state reaches . A real local checkpoint restores the saved vector. Both timing intervals are observed and vary by machine.
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.
Checkpoint workspace: /var/folders/mp/_mq7srqx2y10p5nhjz9m7hj40000gn/T/jax-async-lesson-oukfh9cs
{
"save_call_seconds": 0.0038282088935375214,
"remaining_work_and_wait_seconds": 0.017898499965667725,
"accepted_step": 1,
"live_step": 2
}
Unpublished step 2 exists; application recovery still selects verified step 1.
Checkpoint workspace: /var/folders/mp/_mq7srqx2y10p5nhjz9m7hj40000gn/T/jax-async-lesson-rlb94myr
{
"save_call_seconds": 0.0023883748799562454,
"remaining_work_and_wait_seconds": 0.013635833747684956,
"accepted_step": 1,
"live_step": 2
}
Unpublished step 2 exists; application recovery still selects verified step 1.
Expected background failure surfaced: injected finalization callback failure
Step two verified and accepted; next transition agrees.
Missing target rejected; accepted checkpoint unchanged.
PASS: recovery-05
Download execution record · The notebook includes executed cells and figure outputs. Compare your run with these values; timings depend on the machine.
Trigger an asynchronous error
# Experiment — Trigger an asynchronous error: The controlled failure happens in the finalization callback.
def injected_failure():
raise RuntimeError('injected finalization callback failure')
failed_path=root/'callback_failure'
cp=ocp.AsyncCheckpointer(ocp.StandardCheckpointHandler(),async_options=ocp.options.AsyncOptions(post_finalization_callback=injected_failure))
try:
cp.save(failed_path,args=ocp.args.StandardSave(live))
try:
cp.wait_until_finished()
except RuntimeError as error:
assert 'injected' in str(error)
print('Expected background failure surfaced:',error)
else:
raise AssertionError('background error was hidden')
finally:
cp.close()
assert accepted()['step']==1Expected: An intentional error log and caught RuntimeError; the accepted step is unchanged.
The controlled failure happens in the finalization callback. Some storage may already exist; the application still requires successful completion and verification before accepting it.
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.
Verify and publish the already written second checkpoint. Restore it and compare the next functional transition against the live state. Keep the original snapshot unchanged.
Show a writing guide and starter scaffold
How to write this exercise code
Learner-only inputs, outputs, checks and hints
Inputs
- The already written second-checkpoint path, its live state, and the original step-one snapshot.
Outputs
- The restored second state, a comparison of its next transition with the live continuation, and a published step-two pointer.
Invariants to check
- The restored step-two state matches the live state; both next transitions agree; the original snapshot remains at step one.
Hints
- Restore the second checkpoint against a target shaped like the live state.
- Publish only after restored values and the next transition have been checked.
import json
from pathlib import Path
import jax.numpy as jnp
import numpy as np
import orbax.checkpoint as ocp
def verify_publish_and_compare(checkpoint_path, live_state, original_snapshot, publish_fn):
# TODO: Restore step two, compare its next transition with the live continuation, then publish it.
raise NotImplementedErrorReveal the reference solution
# Exercise solution: Verify and publish the already written second checkpoint.
with ocp.StandardCheckpointer() as cp:
verified=cp.restore(unpublished,target=live)
np.testing.assert_array_equal(verified['weight'],live['weight'])
assert int(verified['step'])==2
publish(unpublished,2)
np.testing.assert_array_equal(transition(verified)['weight'],transition(live)['weight'])
assert accepted()['step']==2 and int(snapshot['step'])==1
print('Step two verified and accepted; next transition agrees.')Keep only a genuinely accepted target
Transfer
Create a manifest pointing to a nonexistent checkpoint in a disposable variable. Write a preflight that rejects it without replacing the real accepted manifest. Explain why a preflight alone cannot prove numerical correctness.
Show a writing guide and starter scaffold
How to write this practice solution
Learner-only inputs, outputs, checks and hints
Inputs
- Create a manifest pointing to a nonexistent checkpoint in a disposable variable. Write a preflight that rejects it without replacing the real accepted manifest. Explain why a preflight alone cannot prove numerical correctness.
Outputs
- Rejected missing target and byte-identical accepted manifest.
Invariants to check
- Preflight failure never publishes or replaces the accepted checkpoint pointer.
Hints
- Check path existence and the declared step before restoration; still compare restored contents afterward.
import json
import tempfile
import time
from pathlib import Path
import jax
import jax.numpy as jnp
import numpy as np
import orbax.checkpoint as ocp
def practice_keep_only_a_genuinely_accepted_target(accepted_manifest, candidate_path):
"""Implement the keep only a genuinely accepted target check."""
# TODO: Build a disposable manifest for a nonexistent checkpoint and reject it without modifying the accepted manifest.
raise NotImplementedErrorShow a hint
Check path existence and the declared step before restoration; still compare restored contents afterward.
Reveal reference solution and reasoning
# Keep only a genuinely accepted target (Transfer)
def preflight(record):
if not Path(record['path']).is_dir() or int(record['step'])<0:
raise ValueError('checkpoint target unavailable')
return record
before=accepted()
try:preflight({'path':str(root/'never_saved'),'step':99})
except ValueError:pass
else:raise AssertionError('missing target accepted')
assert accepted()==before
preflight(before)
print('Missing target rejected; accepted checkpoint unchanged.')File presence is a necessary local preflight, not proof that metadata, data or training state is correct. The restore comparison supplies the stronger check.
Diagnose the result
If the accepted step is ahead of the restored state, inspect publication order and the saved step counter. If wait raises, keep that error and the last accepted manifest; do not suppress the error and publish anyway.
Carry forward
- Record save request, completion and acceptance separately.
- Keep the asynchronous writer alive until completion or reported failure.
- Verify a restored next transition before replacing the accepted recovery point.
Keep your evidence
Keep the requested/completed/accepted step log, the restored snapshot comparison, interrupted-publication result and surfaced finalization error. Explain why directory presence alone is separate from acceptance.
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.