Unit 1 of 11 · about 4 hours · derive, implement

Token-weighted loss denominators, microbatches, accumulation and seen-token counts

The next-token objective is already familiar. Here the risk is a trainer that silently changes its weighting when masks, sequence lengths or accumulation change.

You'll be able to

  • Derive one token-weighted objective across uneven microbatches and a partial accumulation window.
  • Separate input tokens, valid loss tokens, attempted steps and successful optimizer updates.
  • Test a real trainer's denominator against a concatenated-batch gradient oracle.

Covers

Token-weighted causal loss, valid-token masks and denominator checksMicrobatches, accumulation, global batch tokens, optimizer steps and seen-token counts
1

Read

In this order, only the parts listed

0 of 1 done

  1. OLMo-core: the effective-batch loss contractOLMo-core and Official Training Scripts

    TransformerTrainModule.train_batch: label generation, batch_num_tokens_for_loss, instance_mask handling, microbatch splitting, summed loss and backward

    Read this single-device path, not pipeline parallelism. The instance-filter path deliberately includes excluded instances in the denominator; do not use that reported loss as the valid-token mean.

2

Focus on

  • The LLM Foundations unit on the next-token objective covers shifts and masks. For this run, define the valid-token mask after shifting and packing, not from the raw input length.
  • For microbatch loss sums and valid counts , backpropagate . Averaging microbatch means is correct only when their valid counts are equal.
  • Log processed input tokens, valid targets and per-source exposure separately. A skipped optimizer update still consumed data and compute; it must not disappear from the ledger.
  • A zero-valid-token window has no mean objective. Reject or skip it explicitly before division, and record the decision.
Common mistakes · 3
  • Dividing every microbatch by the configured accumulation length when the final window is shorter. Normalize by the actual valid count in that window.
  • Calling nanoGPT's last-microbatch training loss the effective-batch loss. Accumulate detached loss sums and counts for logging too.
  • Assuming input tokens equal supervised targets. Padding, ignored labels and boundary policies can make those counts different.
3

Try it yourself

Closed-book, before checking anything

Closed-book, derive the loss for two microbatches with loss sums 4 and 6 and valid counts 2 and 6: the token mean is 1.25, not the mean-of-means 1.5. Then use PyTorch 2.14.1 on CPU to compare summed-loss accumulation with concatenated-batch gradients on fixed logits with unequal masks. Disable dropout and use explicit floating-point tolerances.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Why can repartitioning the same valid targets into uneven microbatches change a mean-of-means gradient?Answer

    Each microbatch mean receives equal weight despite different valid counts, changing the per-token weights. Summing valid losses and dividing once by the total count preserves the additive objective. Adding only ignored padding does not itself change either masked mean.

  2. 2.One device processes two sequences of length 64 per microbatch, with four microbatches per update. What can you count without inspecting labels?Answer

    512 input-token positions per attempted update. The valid-target count needs the shifted-label mask, and the successful-update count needs the optimizer outcome.

  3. 3.When should full-batch and accumulated gradients agree?Answer

    When they evaluate the same additive objective at the same weights with the same data and stochastic choices, without batch-dependent operations or intermediate updates. Floating-point reduction order still permits small differences.

5

Practice

  • TensorTonic: Gradient Accumulation Equivalence

    Implement gradient_accumulation_step; public cases Uneven microbatches, Two equal microbatches and Zero loss

    The free problem weights linear-model squared error by examples, not language-model tokens. Transfer its denominator argument to valid targets in lmlab and add a partial-window test; the public cases do not test masking or autograd gradients.

You're done when

The public cases pass, and your masked accumulated gradient matches the concatenated oracle within a stated tolerance, including an uneven final window and explicit empty-window handling.

Only when you can do this without notes.

Leads to

Notes

Resources · 1 for this unit, 17 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.

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.

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

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