Unit 10 of 11 · about 6 hours · measure

Step timelines, tokens per second and memory and operation accounting

Parameter and FLOP arithmetic is already familiar. The new task is reconciling those estimates with a real run, including evaluation, publication and failed attempts rather than timing only convenient kernels.

You'll be able to

  • Attribute a training timeline to input wait, transfer, forward, backward, optimizer, evaluation and checkpoint work.
  • Reconcile predicted tensor-state bytes and operation counts with measured runs and named residual costs.
  • Diagnose a seeded throughput regression without changing the model's token exposure or update semantics.

Covers

Input, forward, backward, optimizer, checkpoint and evaluation step timelinesTokens per second, peak memory, state memory and operation accounting
1

Read

In this order, only the parts listed

0 of 3 done

  1. OLMo-core: throughput numerator and intervalOLMo-core and Official Training Scripts

    SpeedMonitorCallback.pre_load_batch, pre_step and post_step; get_device_peak_flops_per_second

    Do not use the fallback peak FLOP rate for an unrecognized GPU: the implementation assumes a different device. Supply verified specifications for your GPU or omit MFU.

  2. PyTorch 2.14: bounded profile capturePyTorch 2.14 - AMP Examples and Profiler

    Overview and API Reference: profile activities, schedule, profile_memory, record_shapes, with_flops, key_averages and export_chrome_trace

    Use a short capture on your machine, with CPU-only activities as the fallback. The FLOP option estimates selected operators; it is not a complete hardware instruction counter.

  3. Appendix B: inspect the accounting assumptionsModern LLM Notebook - Training and Accounting

    Sections 2 Activation Memory, 3 FLOPs, 4 Backpropagation and 6 Training Memory

    Recompute Section 2's FFN subtotal: , not 6.33. Do not copy Section 4's extra factor of 2: forward plus backward is approximately three times forward for the stated dense-matmul model, not six. Section 6's listed FP32 weights, gradients and two moments total 16 bytes per parameter before its listed BF16 copy, which would add 2 more. Treat activation formulas as implementation-dependent estimates, not exact peaks.

2

Focus on

  • Use processed input tokens per elapsed second for execution throughput and report valid-target throughput separately. Give both warmed-up training-only time and end-to-end time including evaluation, checkpoint publication and restarts.
  • Annotate phase boundaries before collecting traces. CUDA launches are asynchronous: use synchronized interval boundaries or device events on your GPU, and read overlapping work as a timeline rather than summing nested operator totals.
  • Build a dtype-specific ledger of unique parameter storage, gradients and moments after state initialization, then add saved activations, temporary copies, workspaces and inputs. Report allocated and reserved memory separately; allocator reserve is not live tensor storage.
  • Under the declared multiply-add convention, a matmul costs approximately FLOPs. Backward is approximately twice forward when both operand gradients are needed; embeddings, frozen inputs, recomputation, loss and optimizer operations require their own accounting.
Common mistakes · 3
  • Calling profiler operator FLOPs a complete count, or dividing them by an unrelated peak precision to claim MFU. State included operations and the device precision first.
  • Adding every per-operator memory allocation to estimate peak live memory. Tensors are freed and storage can be reused; peak is simultaneous liveness, not cumulative allocations.
  • Claiming an optimization from a profiled run alone. Measure a separate clean timing run, then rerun loss, gradient and resume controls.
3

Try it yourself

Closed-book, before checking anything

First derive the free drills' small examples: parameter shapes [4, 3] and [3], 2-byte parameters, 4-byte gradients and Adam moments, plus a [2, 4] 2-byte activation give 226 bytes without a master copy. A forward matmul [2, 4, 4] plus 32 attention FLOPs gives forward 96, backward 192 and total 288 FLOPs under the drill's convention. Then capture an annotated step of your PyTorch 2.14.1 decoder, seed an input-wait delay, and show that its trace localizes the added wait without changing batch hashes or final updates. Reconcile one state-memory prediction and one forward/backward operation prediction with your capture; timings are observations, never targets.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Why can two runs have equal training-only tokens per second but different study cost?Answer

    They may differ in evaluation, checkpoint, startup, retry and failed-run overhead. End-to-end elapsed time and total attempts expose those costs.

  2. 2.Does switching FP32-parameter AdamW to autocast halve persistent optimizer memory?Answer

    No. Stored parameters, gradients and moments can remain FP32. Most savings then come from lower-precision intermediates, with any cast-copy cost counted separately.

  3. 3.The trace shows long input wait while GPU kernels are short. What is the next controlled change?Answer

    Change only the input path, for example by replaying the same preloaded batches. Keep batch order and updates fixed, and verify end-to-end time separately.

5

Practice

  • TensorTonic: Mixed-Precision Training Memory Accountant

    Implement memory_accountant; public examples cover BF16 parameters with FP32 Adam gradients/state, FP32 SGD without activations and BF16 AdaGrad

    This free problem excludes master copies and allocator overhead. Add those only if your measured implementation actually has them. The section mini-project supplies the measured reconciliation.

  • TensorTonic: Transformer Training FLOP Estimator

    Implement flop_estimator; public examples cover one matmul plus attention, two matmuls and a zero-batch matmul

    The free tests exercise the supplied shape arithmetic, not a decoder's full operation graph. Extend your existing foundation solution with an included/excluded-operation ledger rather than treating it as a hardware oracle.

You're done when

Both drills pass, one memory and one operation estimate have measured reconciliations, and the input-delay regression is localized while the unchanged batch/update controls pass.

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.

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

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

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.

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

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

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

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