Unit 6 of 8 · about 5 hours · implement, measure

Schedules, gradient accumulation and clipping

Schedules, batch size and clipping jointly set the update scale. Each one silently changes what the learning rate means, so they must be reasoned about as one mechanism.

You'll be able to

  • Implement linear warmup followed by cosine decay with the scheduler stepped in the right order.
  • Implement gradient accumulation that matches a full-batch gradient up to floating-point order, and state the effective batch size.
  • Apply global-norm clipping after unscaling in mixed precision, and run an LR range test to set bounds.

Covers

Warmup, cosine schedules and schedule orderGradient accumulation and effective batch sizeGradient clipping by global normLearning-rate range tests
1

Read

In this order, only the parts listed

0 of 6 done

  1. Schedules and warmupD2L - optimization and regularization slice

    Schedulers and Policies: factor, multi-factor, cosine with formula, and warmup

  2. Gradient clipping by global normD2L - optimization and regularization slice

    Gradient Clipping: Lipschitz bound, the projection, and its limits

    Read the Gradient Clipping section only. Skip the RNN implementation around it.

  3. Clip API semanticsPyTorch - optimization and automatic mixed precision examples

    clip_grad_norm_ page: global-norm definition over concatenated per-parameter norms, in-place edit, returned total norm, error_if_nonfinite

  4. Scaler order with clippingPyTorch - optimization and automatic mixed precision examples

    Adding GradScaler and Inspecting/modifying gradients: autocast forward, scale, backward, unscale, clip, step, update, zero_grad

  5. LR range testCyclical Learning Rates for Training Neural Networks (Smith, 2017)

    Abstract and range-test description: linearly increasing the rate for a few epochs to read reasonable bounds

  6. HOML: PyTorch schedulers and gradient clippingHands-On Machine Learning with Scikit-Learn and PyTorch

    Chapter 11, Gradient Clipping (printed pp. 382-383) and Learning Rate Scheduling from Cosine Annealing through 1cycle Scheduling (pp. 400-405)

    The warm-up loop on p. 402 calls warmup_scheduler.step() at the start of each epoch. On PyTorch 2.14 that trains at 40, 70 and 100 percent of the rate and never at the 10 percent the text promises; step at the end of each epoch to get 10, 40, 70, 100.

2

Focus on

  • Cosine decay sets from a closed form with fixed . Stepping the scheduler per step versus per epoch changes the curve, so record which one the code does.
  • Accumulation adds microbatch gradients and steps once. Scaling each microbatch's mean loss by reproduces the full-batch mean gradient when the microbatches are equal in size and nothing updates between them. Batch-norm statistics and dropout masks still differ, and the summation order changes, so agreement is to floating-point tolerance.
  • Scaled gradients must be unscaled before clipping. Clipping scaled values applies the threshold in the wrong units; the recipe unscales first so max_norm keeps its unscaled meaning.
  • The range test raises the rate linearly and reads bounds off the loss: flat start, steady fall, then divergence. It sets a search interval, not an optimum.
Common mistakes · 3
  • Calling scheduler.step() before optimizer.step(). PyTorch warns because the first scheduled rate is skipped; assert the rate used on step one. Forgetting zero_grad at the start of each accumulation cycle silently adds the previous cycle's gradients.
  • Claiming accumulation equals large-batch training. Batch-norm running statistics update per microbatch and dropout draws differ, so the match is statistical, not bitwise.
  • Treating warmup as a universal fix. The Tuning Playbook shows instabilities that need clipping or architecture change; warmup only shortens the risky early phase.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write the cosine formula and evaluate it at halfway: 0.3, 0.01, 20, 10 gives 0.155. Write the clipping rescale and apply it to per-param norms 3 and 4 with 1: total 5, scale 0.2. Write the accumulation average that reproduces a batch-32 mean from four microbatches of 8.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Cosine schedule 0.3, 0.01, 20. What is at 10 and 20?Answer

    . At , , . At , , .

  2. 2.Four microbatches of 8 with mean-reduced losses give microbatch gradients , , and . What update matches batch-32 SGD, and when does it fail to match?Answer

    One optimizer step along . It fails if you add the four gradients without dividing by 4 (a step 4 times too large), if the microbatches differ in size, or if state such as batch-norm statistics updates per microbatch.

  3. 3.Where does clipping go in a GradScaler step, and what breaks if it moves before unscaling?Answer

    After scaler.unscale_ and before scaler.step. Before unscaling, gradients carry the dynamic scale factor, so a fixed max_norm threshold means something different every iteration.

  4. 4.Range-test loss falls slowly, then steeply, then explodes. How do you read it?Answer

    The flat start is below the useful range, the steep fall is the usable interval, and the explosion is the ceiling. Search between the fall and below the ceiling; the test gives bounds, not the best rate.

5

Practice

  • TrenTorch: Gradient Accumulation

    Implement compute_output_head_gradient, accumulate_gradients and train_with_gradient_accumulation; the tests compare the accumulated update with one full-batch step

    Average the microbatch gradients, hold the weights fixed until every microbatch is done, then step once. Then check your PyTorch loop, which divides each microbatch loss by , against a full-batch reference within floating-point tolerance.

  • TrenTorch: Warmup and Cosine Decay

    Implement linear_warmup_lr, cosine_decay_lr and warmup_cosine_lr, with the decay step counted from the end of warmup

    Check the closed form first: base 0.3, minimum 0.01, 20 decay steps, step 10 gives 0.155.

  • D2L Learning-Rate Scheduling: Exercises

    Exercises 1 and 4 (best fixed-rate model, warmup length); run the cosine comparison of exercise 3 on Fashion-MNIST instead of ImageNet

You're done when

Your accumulated run matches the full-batch gradient within floating-point tolerance, your clipped AMP order passes the unscale check, and your range test names defensible bounds.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 8 more in the section

Also in this section

  • Understanding Deep Learning - fitting, gradients and regularizationSimon J. D. Prince · primary

    Use Chapters 6-9 and targeted parts of Chapter 20 for optimization, initialization, measurement, regularization and why training works. Re-derive the update rules you keep in the trainer.

  • Deep-ML candidate - optimization and normalization problemsDeep-ML · optional

    After the platform admission check, use at most one of 146 Momentum, 169 AdamW, 197 Global-Norm Clipping, 109 LayerNorm or 115 BatchNorm as a changed-prompt drill.

  • TrenTorch - training mechanics questionsTrenTorch · support

    Solve only the questions the units name: Weight Initialization, Layer Normalization, Label Smoothing, Gradient Accumulation, and Warmup and Cosine Decay. Read the tests first; they run in the browser IDE.

  • PyTorch GroupNorm referencePyTorch · reference

    Read how input channels are split into num_groups groups and which axes each group normalizes; compare num_groups 1 against num_channels.

  • PyTorch RMSNorm referencePyTorch · reference

    Read the RMS formula and which axes normalized_shape covers; note the missing mean centering and bias.

  • PyTorch torch.optim.AdamW referencePyTorch · reference

    Read the AdamW algorithm box for the decoupled weight-decay step, the bias-corrected moments and the defaults, and follow the Decoupled Weight Decay Regularization link for the argument.

  • PyTorch CrossEntropyLoss referencePyTorch · reference

    Read Shape, Parameters (weight, ignore_index, reduction, label_smoothing) and both Examples; extend the class-index example with ignore_index and a class weight.

  • Deep Learning Tuning Playbook FAQ: debugging optimization failuresGoogle Research · reference

    Read How can optimization failures be debugged and mitigated (identifying unstable workloads, warmup, clipping) and Batch normalization implementation details.