Source code for kempnerforge.training.grad
"""Gradient utilities for distributed training.
Handles gradient accumulation with no_sync context for skipping
redundant all-reduces during micro-batching.
"""
from __future__ import annotations
import contextlib
from collections.abc import Callable, Generator
import torch
from torch.distributed.fsdp import FSDPModule
[docs]
def reduces_every_micro_step(unit: FSDPModule) -> bool:
"""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.
"""
policy = unit._get_fsdp_state()._mp_policy
return (policy.reduce_dtype or policy.param_dtype) == torch.bfloat16
def _gradient_sync_switch(model: torch.nn.Module) -> Callable[[bool], None] | None:
"""The call that turns gradient sync on or off for the FSDP2 units of ``model`` that skip it.
Every unit skips its sync on early micro-steps except one that reduces in bf16
(``reduces_every_micro_step``). When every unit skips, a model with its own
``set_requires_gradient_sync``, such as one whose root is an FSDP2 module, is switched
through it. Otherwise the skipping units are switched one at a time, which reaches
components sharded on their own and modules behind a ``torch.compile`` wrapper. None
when no unit skips.
"""
modules = model.modules() if isinstance(model, torch.nn.Module) else ()
units = [module for module in modules if isinstance(module, FSDPModule)]
skipping = [unit for unit in units if not reduces_every_micro_step(unit)]
switch = getattr(model, "set_requires_gradient_sync", None)
if switch is not None and len(skipping) == len(units):
return switch
if not skipping:
return None
def switch_units(requires_gradient_sync: bool) -> None:
for unit in skipping:
unit.set_requires_gradient_sync(requires_gradient_sync, recurse=False)
return switch_units
[docs]
@contextlib.contextmanager
def maybe_no_sync(
model: torch.nn.Module,
micro_step: int,
grad_accum_steps: int,
) -> Generator[None, None, None]:
"""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.
"""
is_last_step = (micro_step + 1) == grad_accum_steps
switch = None if is_last_step else _gradient_sync_switch(model)
if switch is None:
yield
else:
switch(False)
try:
yield
finally:
switch(True)