kempnerforge.training.grad

Gradient utilities for distributed training.

Handles gradient accumulation with no_sync context for skipping redundant all-reduces during micro-batching.

Functions

maybe_no_sync(model, micro_step, ...)

Skip gradient sync on intermediate accumulation steps.

reduces_every_micro_step(unit)

Whether the FSDP2 unit unit reduces in bf16, and so syncs on every micro-step.

kempnerforge.training.grad.reduces_every_micro_step(unit)[source]

Whether the FSDP2 unit unit reduces in bf16, and so syncs on every micro-step.

FSDP2 reduces in the policy’s reduce_dtype, else in its param_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:

unit (torch.distributed.fsdp.FSDPModule)

Return type:

bool

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 model that 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 a torch.compile wrapper. Sync is turned back on when the block exits. For a model without FSDP2 modules, this is a no-op.

Parameters:
Return type:

Generator[None, None, None]