Unit 7 of 11 · about 5 hours · implement

Complete language-model checkpoint state, atomic publication and corrupted-state handling

Complete checkpoints and atomic writes are familiar. This unit audits a real trainer, extends a deliberately incomplete one, and proves that interruption and corruption cannot silently select an invalid continuation.

You'll be able to

  • Map every mutable language-model training state to its owner and serialized representation.
  • Publish immutable local checkpoints with integrity metadata and an explicit reader acceptance rule.
  • Reject incomplete, corrupted or incompatible state before mutating the live training objects.

Covers

Model, optimizer, scheduler, scaler, RNG, data and configuration checkpoint stateAtomic checkpoint publication, restart selection and corrupted-state handling
1

Read

In this order, only the parts listed

0 of 4 done

  1. OLMo-core: trainer state versus model and optimizer stateOLMo-core and Official Training Scripts

    Trainer.state_dict, load_state_dict and load_checkpoint: counters, loader, callbacks and conditional RNG restoration

    Do not mistake Trainer.state_dict alone for the full checkpoint; model and optimizer state belong to the train module.

  2. OLMo-core: local publication and discoveryOLMo-core and Official Training Scripts

    Checkpointer.save, dir_is_checkpoint, find_checkpoints, latest_checkpoint, _save_metadata, _get_tmp_dir and _teardown_tmp_dir

    Trace local storage only. Remote uploads do not inherit local atomic-rename semantics; sharding and fleet recovery stay outside this section.

  3. nanoGPT: the checkpoint to extendnanoGPT Training Loop

    init_from == 'resume' branch; scaler creation; checkpoint dictionary and torch.save inside the evaluation branch; initial and prefetched X, Y batches

  4. Local atomic replacement and synchronizationPython - Atomic Replacement and File Synchronization

    os.replace and os.fsync entries, including the same-filesystem restriction and flush-before-fsync instruction (page read 2026-10-16)

2

Focus on

  • Save at a completed-update boundary: model, moments and group mapping, schedule position, scaler, counters, CPU and device RNG, sampler/shuffle state, corpus/tokenizer/config hashes and callback state. Mid-accumulation saves additionally need partial gradients and window position.
  • nanoGPT does not save RNG, scaler or loader state. Its random-window sampler also prefetches the next batch before saving; either save that pending batch and its identity or move publication to a boundary with a fully specified next-batch recipe.
  • For local single-file checkpoints, write an immutable payload through a temporary sibling, flush and synchronize it, then atomically replace its final name. Publish a manifest last with size, digest, schema and run identity; readers require all checks before loading into fresh objects.
  • A successful rename gives atomic visibility, not guaranteed survival of power loss. Directory synchronization and filesystem behavior matter for durability. Keep the previous verified checkpoint until the new one has passed validation.
Common mistakes · 3
  • Calling successful deserialization an integrity check. Corrupted tensor bytes may still deserialize; validate the recorded digest and semantic identity too.
  • Using a filename or modification time as proof of completeness. Select the highest accepted step with its manifest, not merely the newest path.
  • Treating an in-memory state dictionary as an immutable snapshot. Its tensors can alias live state; serialize immediately or copy them before training continues.
3

Try it yourself

Closed-book, before checking anything

In a CPU test, retain one verified checkpoint, start a separate writer for the next temporary payload, and terminate it after it signals that only part was written. Discovery must ignore that unpublished attempt. Next, alter one byte in a copied published payload without updating its recorded digest: validation must reject it before deserialization or live-state mutation. Keep both failure records and show explicit fallback to the older verified state.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.The model and optimizer reload correctly. Why might the next training batch still be wrong?Answer

    The loader position, random stream or already-prefetched batch may be missing. A checkpoint must describe the next consumed batch, not only the last completed update.

  2. 2.A checkpoint's checksum passes, but its tokenizer hash differs. May you resume it as the same run?Answer

    No. Integrity proves the bytes match the manifest, not that the bytes belong to a compatible experiment. Reject the mismatch or declare an explicit new intervention.

  3. 3.Can an atomic rename alone guarantee a checkpoint survives sudden power loss?Answer

    No. Visibility and durability are different guarantees. Buffered data and directory entries need appropriate synchronization, with filesystem-specific limits.

You're done when

Interrupted publication, byte tampering and tokenizer/config mismatches are rejected without changing live state, and the previous verified checkpoint remains loadable.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 15 more in the section
  • OLMo-core and Official Training ScriptsAllen Institute for AI · primary

    Trace src/examples/llm/train.py through nn/transformer/, optim/, train/train_module/, train/trainer.py and train/callbacks/checkpointer.py. Note what Trainer.state_dict saves (loader, RNG and callback state) and how the data loader checks its fingerprint. The CPU integration test test_train_small_model_cpu needs extra packages and downloads external data, so point it at a small local fixture or treat the run as optional.

  • nanoGPT Training LoopAndrej Karpathy · support

    Read train.py and model.py at commit 3adf61e and run the reduced CPU or small-GPU configuration. The repository is marked deprecated, its checkpoint holds no RNG, scaler or data-loader state, and the loop runs max_iters + 1 updates. Use those gaps for your kill-and-resume and atomic-save tests.

  • Python - Atomic Replacement and File SynchronizationPython Software Foundation · reference

    Read os.replace and os.fsync for the local single-file publication extension. Atomic visibility is not a power-loss durability guarantee. Page read 2026-10-16.

Also in this section

  • CS336 Assignment 1 - Training and SerializationStanford University · required

    Revisit only the optimizer, schedule, gradient clipping, data loading, checkpointing, training-together and decoding problems. Add kill-and-resume, tokenizer mismatch and corrupted-checkpoint tests beyond the foundation implementation.

  • Deep Learning Tuning PlaybookGoogle Research · required

    Read #a-scientific-approach-to-improving-model-performance (scientific, nuisance and fixed hyperparameters; incremental tuning), #determining-the-number-of-steps-for-each-training-run, #saving-checkpoints-and-retrospectively-selecting-the-best-checkpoint and the FAQ entries on schedules and #how-can-optimization-failures-be-debugged-and-mitigated. Write the run and triage protocol before launching comparisons; skip the batch-norm material.

  • Build a Large Language Model (From Scratch), Chapter 5 and Appendix DSebastian Raschka / Manning · support

    Use Chapter 5 (the loss, training loop and saving weights, pp. 128-167) and Appendix D (warmup, cosine decay and gradient clipping, pp. 313-321) as the first correct tiny pretraining loop before the large-run recipe.

  • Machine Learning Engineering - Instabilities, Checkpoints and DebuggingStas Bekman · support

    Read training/instabilities/README.md and training/instabilities/training-loss-patterns.md (spike types, resume and data-sampler spikes), training/checkpoints/README.md, debug/underflow_overflow.md and training/dtype.md. Use the spike taxonomy to label the failure you inject.

  • The Smol Training Playbook - Preflight and Training MarathonHugging Face · support

    Read the Preflight Checklist, the Training Marathon and the loss-spike stories for checks to run before and during a small pretraining run. The page has no stable anchors, so cite section names; its SmolLM numbers do not transfer to your model.

  • 2 OLMo 2 Furious, Sections 2.3, 3.1 to 3.4 and 6.3Allen Institute for AI · support

    Read the base training recipe (Section 2.3), the stability deep dive (repeated n-grams, initialization, norm and z-loss changes, embedding weight decay; Sections 3.1 to 3.4) and stability operations (Section 6.3) as the real narrative behind your tiny-run contracts.

  • OPT: Open Pre-trained Transformer Language Models, Section 2.5 (Zhang et al., 2022)Meta AI · support

    Read Table 1 and Section 2.5: at least 35 manual restarts, loss divergences handled by lowering the learning rate and restarting from an earlier checkpoint, and mid-run clipping changes. Use it as the failed-run case study when you write your own run log.

  • Scaling Laws and Compute-Optimal Training Beyond Fixed Training Durations (Hagele et al., 2024) with MiniCPM Section 4EPFL; Tsinghua and ModelBest · support

    Read Hagele Sections 2 and 3 (constant learning rate plus cooldown matches cosine and allows mid-run evaluation) and MiniCPM Section 4 (warmup-stable-decay with a short decay phase). MiniCPM is at https://arxiv.org/abs/2404.06395. Both use sub-billion or small models.

  • Tensor Programs V: Tuning Large Neural Networks via Zero-Shot Hyperparameter Transfer (Yang et al., 2022)Microsoft and OpenAI · support

    Read Algorithm 1 (muTransfer) and Table 1 (which hyperparameters transfer and which do not), then one transfer figure. Transfer holds within one architecture, optimizer and data family.

  • Mixed Precision Training (Micikevicius et al., 2018)NVIDIA and Baidu · reference

    Read Section 3: FP32 master weights, loss scaling and FP32 accumulation, and the rule to unscale gradients before clipping. It predates BF16, which needs little or no loss scaling.

  • An Empirical Model of Large-Batch Training (McCandlish et al., 2018)OpenAI · reference

    Read Section 2: the gradient noise scale, the critical batch size and the steps-versus-examples trade-off in Figure 1. The noise scale grows as loss falls, so measure it at more than one point.

  • Modern LLM Notebook - Training and AccountingWalking Labs · support

    Use notebooks-en/part2-training/10-training-loss.ipynb and the appendix notebooks B-flops-memory-accounting.ipynb and C-mixed-precision-training.ipynb for the compact trainer, FLOP and memory accounting and mixed precision. Seed one numerical failure and reconcile the estimate with measurement.

  • TensorTonic - Training Reliability DrillsTensorTonic · support

    Solve Mixed-Precision Training Memory Accountant (cs336-l02-training-memory-accountant), Transformer Training FLOP Estimator (cs336-l02-training-flop-estimator), Gradient Accumulation Equivalence (cs336-l02-gradient-accumulation-step) and Generate a Warmup-Stable-Decay Schedule (cs336-l11-wsd-learning-rate). Validate each against your training harness. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution.

  • Decoder-Only Transformer Stack - Reliable TrainingRoadmap-Final · support

    Use the existing training, resume and arithmetic contracts as the small controlled system. Add stored evidence for data, numerical, state and throughput failure injections.

  • PyTorch 2.14 - AMP Examples and ProfilerPyTorch · reference

    AMP examples: Gradient clipping and Gradient accumulation, including effective-batch scale updates and skipped optimizer steps. Profiler reference: record_function, schedule and memory capture. Use with PyTorch 2.14.1.