Pick gradient accumulation steps for a global batch
Why it matters Every LLM training config sets accumulation steps from this equation.
Global batch = micro batch * accumulation steps * data-parallel GPUs.
Write accum_steps(global_batch, micro_batch, n_gpus). Return the accumulation steps, or raise ValueError if global_batch is not divisible by micro_batch * n_gpus.
def accum_steps(global_batch, micro_batch, n_gpus)Example
accum_steps(1024, 8, 16) is 8.
Understand the idea
The batch size the optimizer sees is the global batch. It is built from three factors: the micro batch each GPU processes at once, the number of data-parallel GPUs, and how many micro batches you accumulate gradients over before taking an optimizer step. Accumulation lets you reach a large global batch without more GPU memory. Worked example: global batch 2048, micro batch 4, 32 GPUs. One accumulation step covers 4 * 32 = 128 samples, so you need 2048 / 128 = 16 steps. For global batch 1000 with micro 8 and 16 GPUs, one step covers 128 samples, and 1000 / 128 is not a whole number, so you must raise ValueError rather than silently training on 896 or 1024 samples. Rule: per_step = micro_batch * n_gpus; if global_batch % per_step is not 0, raise ValueError; else return global_batch // per_step as an int. Used in: configuring DeepSpeed, FSDP and Hugging Face Trainer runs, where a mismatched batch silently changes the learning rate behaviour.