Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support wrapping multiple models in Accelerator.accumulate() #1708

Merged
merged 5 commits into from
Jul 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions src/accelerate/accelerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -885,13 +885,14 @@ def gradient_accumulation_steps(self, gradient_accumulation_steps):
self.gradient_state.plugin_kwargs.update({"num_steps": gradient_accumulation_steps})

@contextmanager
def accumulate(self, model):
def accumulate(self, *models):
"""
A context manager that will lightly wrap around and perform gradient accumulation automatically

Args:
model (`torch.nn.Module`):
PyTorch Module that was prepared with `Accelerator.prepare`
*models (list of `torch.nn.Module`):
PyTorch Modules that was prepared with `Accelerator.prepare`. Models passed to `accumulate()` will skip
gradient syncing during backward pass in distributed training

Example:

Expand All @@ -912,12 +913,9 @@ def accumulate(self, model):
```
"""
self._do_sync()
if self.sync_gradients:
context = contextlib.nullcontext
else:
context = self.no_sync

with context(model):
with contextlib.ExitStack() as cm_stack:
for m in models:
cm_stack.enter_context(contextlib.nullcontext() if self.sync_gradients else self.no_sync(m))
yield

@contextmanager
Expand Down