kempnerforge.training.grad¶
Gradient utilities for distributed training.
Handles gradient accumulation with no_sync context for skipping redundant all-reduces during micro-batching.
Functions
|
Skip gradient sync on intermediate accumulation steps. |
|
Whether the FSDP2 unit |
- kempnerforge.training.grad.reduces_every_micro_step(unit)[source]¶
Whether the FSDP2 unit
unitreduces in bf16, and so syncs on every micro-step.FSDP2 reduces in the policy’s
reduce_dtype, else in itsparam_dtype, else in the parameters’ own dtype; in the last case the running sum is kept in that dtype either way. Skipping the sync of a unit that reduces in bf16 would hold its running sum unsharded in bf16; syncing adds each micro-step’s reduced gradient into the sharded gradient, in the parameters’ dtype.- Parameters:
- Return type:
- kempnerforge.training.grad.maybe_no_sync(model, micro_step, grad_accum_steps)[source]¶
Skip gradient sync on intermediate accumulation steps.
On the last micro-step, gradients are synchronized normally. On earlier micro-steps, every FSDP2 unit of
modelthat reduces in fp32 skips its reduce-scatter (and, under HSDP, its all-reduce) and keeps its unsharded gradient until the last micro-step reduces the sum. A unit that reduces in bf16 syncs on every micro-step, so its running sum is kept in the sharded gradient’s dtype, never in bf16. A model whose root is an FSDP2 module and whose units all skip is switched through its root; otherwise each skipping FSDP2 module it holds is switched, also behind atorch.compilewrapper. Sync is turned back on when the block exits. For a model without FSDP2 modules, this is a no-op.- Parameters:
model (torch.nn.Module)
micro_step (int)
grad_accum_steps (int)
- Return type:
Generator[None, None, None]