57 / 90

Day 57: Fault Tolerance, Checkpoint Corruption Recovery & Billing Defense

Handle truncated checkpoints, vocabulary expansion with strict=False, SIGTERM spot preemption, and cloud billing safeguards.

Models and Pretraining 480 active minutes (8 hours)
01 120 min

Corrupted, Truncated and Incompatible Checkpoint Diagnosis

Agent-Assisted Engineering Check

Prerequisites

Day 55 Checkpoints and error handling mechanics.

Learning Objective

Diagnose partial-write truncations (EOFError, pickle UnpicklingError), verify SHA256 checksums, and automate fallback to the most recent healthy historical checkpoint.

Instructions

1. Understand failure modes when processes are killed during standard write operations: file size is non-zero, but end of file is truncated.
2. Attempting to torch.load a truncated checkpoint throws _pickle.UnpicklingError: pickle data was truncated or EOFError.
3. Implement a checksum verification protocol: along with 'ckpt.pt', save 'ckpt.pt.sha256'. Verify hashes before loading.
4. Build an automated multi-stage fallback: if checkpoint_step_10000 fails validation, seamlessly fall back to checkpoint_step_9000 and notify the training supervisor.

Practice & Prediction Log

Write a recovery loader safe_load_checkpoint(checkpoint_dir) that iterates backwards through sorted checkpoint snapshots, rejects corrupted or truncated files, and successfully loads the latest valid state.

Independent Mastery Criterion

Demonstrate automatic fallback to an intact historical snapshot when the newest snapshot is intentionally truncated.

Authoritative Source Resources & Provenance

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

Author: PyTorch Documentation Team | Original Source Link ↗

Relevant Section / Range: Saving & Loading a General Checkpoint for Inference and/or Resuming Training

Verified Version & Date: PyTorch 2.x Documentation (Verified: 2026-10-30)

Selection Rationale:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

Source Prerequisites:

Python, PyTorch tensors and nn.Module basics.

Safe Fallback (Offline Resilience):

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

Compared Candidate Sources & Selection Analysis (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: checkpoint dict {'model', 'optimizer', 'model_args', 'iter_num', 'best_val_loss', 'config'} written with torch.save to out_dir/ckpt.pt; the init_from == 'resume' branch reloads it

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Transformer architecture from Days 46-48 and training loop from Days 49-51.

Safe Fallback (Offline Resilience):

Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.

Compared Candidate Sources & Selection Analysis (2)
Megatron-LM Checkpoint Utility ↗ compared_alternative [BSD-3-Clause]

High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.

PyTorch Lightning ModelCheckpoint ↗ compared_alternative [Apache 2.0]

High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.

02 120 min

Partial Weight Loading, Vocabulary Expansions & Strict Mode Management

Independent Mastery Check (no AI assistance).

Prerequisites

Day 57 Activity 1, PyTorch module parameter dictionaries.

Learning Objective

Perform partial weight transfers across altered architectures using strict=False, safely expand embedding layers for new tokens, and audit missing_keys vs unexpected_keys.

Instructions

1. Understand load_state_dict(..., strict=False) return values: incompatible_keys has missing_keys and unexpected_keys attributes.
2. Handle vocabulary expansion: when fine-tuning a model on a new domain with added special tokens, vocab_size changes from V_old to V_new.
3. Transfer old embeddings: copy existing weights into the new [V_new, d] tensor and initialize new token embeddings with small random gaussian noise or mean embedding.
4. Avoid common silent bugs: verify that missing keys are only the newly added modules, not accidentally misspelled layer names.

Practice & Prediction Log

Take a pretrained model with vocab_size=100. Expand the vocabulary to 105. Safely load the old weights with strict=False, initialize the 5 new token embeddings, and verify the old 100 token outputs remain completely unaltered.

Independent Mastery Criterion

Successfully expand model vocab without altering existing token representations.

Authoritative Source Resources & Provenance

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

Author: PyTorch Documentation Team | Original Source Link ↗

Relevant Section / Range: Warmstarting Model Using Parameters from a Different Model (strict=False)

Verified Version & Date: PyTorch 2.x Documentation (Verified: 2026-10-30)

Selection Rationale:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

Source Prerequisites:

Python, PyTorch tensors and nn.Module basics.

Safe Fallback (Offline Resilience):

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

Compared Candidate Sources & Selection Analysis (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: init_from == 'resume' branch (strips the '_orig_mod.' prefix, then model.load_state_dict)

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Transformer architecture from Days 46-48 and training loop from Days 49-51.

Safe Fallback (Offline Resilience):

Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.

Compared Candidate Sources & Selection Analysis (2)
Megatron-LM Checkpoint Utility ↗ compared_alternative [BSD-3-Clause]

High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.

PyTorch Lightning ModelCheckpoint ↗ compared_alternative [Apache 2.0]

High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.

03 120 min

Cloud Spot Preemption Signals, Graceful SIGTERM Handling & Billing Safeguards

Agent-Assisted Engineering Check

Prerequisites

Day 57 Activity 1, Linux POSIX signals and cloud spot economics.

Learning Objective

Register Python signal handlers for SIGTERM/SIGINT to immediately trigger emergency atomic checkpoint persistence when a cloud Spot GPU node receives preemption notice, protecting research budgets from lost progress.

Instructions

1. Understand cloud spot instances: cloud providers offer up to 70-90% discounts on preemptible GPUs, but issue a termination notice (typically 30 to 120 seconds notice) via SIGTERM or metadata service.
2. In Python, import signal and register signal.signal(signal.SIGTERM, sigterm_handler).
3. In the handler, set a global flag graceful_exit = True. At the end of the current training step, flush an emergency atomic checkpoint and exit cleanly with code 0.
4. Analyze disk I/O cost trade-offs: checkpointing every step destroys GPU throughput due to disk write latency; checkpointing every 10,000 steps risks wasting hours of compute. Design an adaptive interval policy.

Practice & Prediction Log

Write a training loop with a registered SIGTERM handler. Launch it, send a kill -15 (SIGTERM) from another shell or process, and verify that the script immediately completes the current step, flushes an emergency checkpoint, and exits cleanly.

Independent Mastery Criterion

Trap SIGTERM signals and cleanly save an emergency checkpoint before process exit.

Authoritative Source Resources & Provenance

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: checkpoint dict {'model', 'optimizer', 'model_args', 'iter_num', 'best_val_loss', 'config'} written with torch.save to out_dir/ckpt.pt; the init_from == 'resume' branch reloads it

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Transformer architecture from Days 46-48 and training loop from Days 49-51.

Safe Fallback (Offline Resilience):

Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.

Compared Candidate Sources & Selection Analysis (2)
Megatron-LM Checkpoint Utility ↗ compared_alternative [BSD-3-Clause]

High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.

PyTorch Lightning ModelCheckpoint ↗ compared_alternative [Apache 2.0]

High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.

linking CC-BY 4.0

Transformer Math 101

Author: Quentin Anthony, Stella Biderman, Hailey Schoelkopf | Original Source Link ↗

Relevant Section / Range: N/A

Verified Version & Date: EleutherAI Research Blog (Verified: 2026-10-30)

Selection Rationale:

Widely cited, practical industry guide deriving 6ND compute FLOPs, activation memory, KV cache size, and VRAM estimation.

Source Prerequisites:

Transformer matrix dimensions and matrix multiplication FLOP counting.

Safe Fallback (Offline Resilience):

The 6ND derivation (2ND forward, 4ND backward) and peak VRAM estimation models are fully worked out in the curriculum.

Compared Candidate Sources & Selection Analysis (2)

Rigorous academic formulation; Transformer Math 101 provides accessible step-by-step arithmetic equations.

Kaplan et al. Section 2.1 Compute Budgeting ↗ compared_alternative [Open Access]

Original 6ND approximation; EleutherAI expands on activation memory and KV cache.

04 120 min

Assessment: Preemption & Corruption Fault Injection Simulation Drill

Independent Mastery Check (no AI assistance).

Prerequisites

Day 57 Activities 1-3.

Learning Objective

Execute a full chaotic fault-injection simulation: induce unexpected SIGTERM kills, inject bit corruption into checkpoint files, and verify autonomous self-healing recovery.

Instructions

1. Write a supervisor simulation script that runs a 30-step training job.
2. At step 10, inject a simulated SIGTERM. Verify an emergency checkpoint is cleanly saved.
3. At step 20, corrupt the most recent checkpoint file by overwriting the last 512 bytes with zeroes.
4. Relaunch the training runner. Verify that it detects the corruption at step 20, safely falls back to the previous snapshot, and completes all 30 steps with a decreasing loss curve.

Practice & Prediction Log

Run the automated chaos drill test suite. Verify that the self-healing training agent logs all anomalies, discards bad checkpoints, and successfully produces the final trained model.

Independent Mastery Criterion

Achieve 100% test pass rate across combined hardware crash and storage corruption drills.

Authoritative Source Resources & Provenance

linking BSD-3-Clause

PyTorch Tutorial: Saving and Loading Models

Author: PyTorch Documentation Team | Original Source Link ↗

Relevant Section / Range: Saving & Loading a General Checkpoint for Inference and/or Resuming Training

Verified Version & Date: PyTorch 2.x Documentation (Verified: 2026-10-30)

Selection Rationale:

Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.

Source Prerequisites:

Python, PyTorch tensors and nn.Module basics.

Safe Fallback (Offline Resilience):

All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.

Compared Candidate Sources & Selection Analysis (2)
TensorFlow tf.train.Checkpoint Guide ↗ compared_alternative [Apache 2.0]

TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.

Hugging Face Safetensors Documentation ↗ compared_alternative [Apache 2.0]

Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.

linking MIT

nanoGPT: train.py pretraining loop

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: train.py: checkpoint dict {'model', 'optimizer', 'model_args', 'iter_num', 'best_val_loss', 'config'} written with torch.save to out_dir/ckpt.pt; the init_from == 'resume' branch reloads it

Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)

Selection Rationale:

Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.

Source Prerequisites:

Transformer architecture from Days 46-48 and training loop from Days 49-51.

Safe Fallback (Offline Resilience):

Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.

Compared Candidate Sources & Selection Analysis (2)
Megatron-LM Checkpoint Utility ↗ compared_alternative [BSD-3-Clause]

High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.

PyTorch Lightning ModelCheckpoint ↗ compared_alternative [Apache 2.0]

High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.