-
Notifications
You must be signed in to change notification settings - Fork 414
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
Restore backward after each batch for grad accum #1917
base: main
Are you sure you want to change the base?
Changes from 3 commits
b62af9f
3f8c7aa
494b96b
99acd4e
474b533
32d652d
8e978e7
a878829
83cba27
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -130,7 +130,8 @@ def __init__(self, cfg: DictConfig) -> None: | |
|
||
# _is_rank_zero is used primarily for logging. In the future, the logger | ||
# should directly take care of this | ||
_, rank = training.get_world_size_and_rank() | ||
self._world_size, rank = training.get_world_size_and_rank() | ||
self._rank = rank | ||
self._is_rank_zero = rank == 0 | ||
|
||
# Training cfg | ||
|
@@ -631,7 +632,7 @@ def train(self) -> None: | |
# clean up before training begins | ||
training.cleanup_before_training() | ||
|
||
_, rank = training.get_world_size_and_rank() | ||
self._world_size, rank = training.get_world_size_and_rank() | ||
|
||
# zero out the gradients before starting training | ||
if not self._optimizer_in_bwd: | ||
|
@@ -697,15 +698,24 @@ def train(self) -> None: | |
# Compute loss | ||
# Loss is normalized by default so we multiply by the number of tokens | ||
# This way we can normalize by the total number of tokens if we're accumulating gradients | ||
running_loss += self._loss_fn(logits, labels) * current_num_tokens | ||
current_loss = self._loss_fn(logits, labels) * current_num_tokens | ||
|
||
# free logits otherwise it peaks backward memory | ||
del logits | ||
|
||
running_loss += current_loss | ||
felipemello1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if (idx + 1) % self._gradient_accumulation_steps != 0: | ||
with training.no_sync(self._model): | ||
current_loss.backward() | ||
else: | ||
current_loss.backward() | ||
|
||
# Step with optimizer | ||
if (idx + 1) % self._gradient_accumulation_steps == 0: | ||
loss = running_loss / num_tokens | ||
loss.backward() | ||
local_num_tokens = num_tokens.detach().clone() | ||
torch.distributed.all_reduce(num_tokens) | ||
training.scale_grads(self._model, self._world_size / num_tokens) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. there are so many lines taking care of the all_reduce, backward, etc, that it makes me wonder if this should be a utility. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah maybe. In this case I feel like it's important enough (and tricky enough) logic to be done very explicitly. Whatever route we go I will ultimately make it more explicit what's happening here |
||
if self._clip_grad_norm is not None: | ||
if self._optimizer_in_bwd: | ||
raise NotImplementedError( | ||
|
@@ -722,7 +732,7 @@ def train(self) -> None: | |
# Update the number of steps when the weights are updated | ||
self.global_step += 1 | ||
|
||
loss_to_log = loss.item() | ||
loss_to_log = running_loss.item() / num_tokens | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should probably normalize by local_num_tokens? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Update: I am probably gonna keep it like this since it should be representative of the loss we are actually using to step (even though it means our loss curves will look slightly different than they do today) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i think it makes sense. Will it break all regression tests though? |
||
pbar.update(1) | ||
pbar.set_description( | ||
f"{curr_epoch + 1}|{self.global_step}|Loss: {loss_to_log}" | ||
|
@@ -743,7 +753,8 @@ def train(self) -> None: | |
else self._optim_ckpt_wrapper | ||
), | ||
), | ||
"tokens_per_second_per_gpu": num_tokens / time_per_step, | ||
"tokens_per_second_per_gpu": local_num_tokens | ||
/ time_per_step, | ||
} | ||
if self._log_peak_memory_stats: | ||
log_dict.update( | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,10 +5,22 @@ | |
# LICENSE file in the root directory of this source tree. | ||
|
||
|
||
import contextlib | ||
import logging | ||
import os | ||
from itertools import chain | ||
from typing import Any, Callable, cast, Dict, List, Optional, Set, Tuple, Type | ||
from typing import ( | ||
Any, | ||
Callable, | ||
cast, | ||
Dict, | ||
Generator, | ||
List, | ||
Optional, | ||
Set, | ||
Tuple, | ||
Type, | ||
) | ||
|
||
import torch | ||
import torch.distributed as dist | ||
|
@@ -679,3 +691,12 @@ def shard_model( | |
|
||
# Finally shard the entire model to account for any stragglers | ||
fully_shard(model, **fsdp_kwargs) | ||
|
||
|
||
@contextlib.contextmanager | ||
def no_sync(model: nn.Module) -> Generator[None, None, None]: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. name could be more descriptive, maybe no_grad_sync |
||
model.set_requires_gradient_sync(False) | ||
try: | ||
yield | ||
finally: | ||
model.set_requires_gradient_sync(True) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does this really need its own file? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Where do you wanna put it then? Otherwise I am gonna copy-paste this in every recipe which is worse imo |
||
# All rights reserved. | ||
# | ||
# This source code is licensed under the BSD-style license found in the | ||
# LICENSE file in the root directory of this source tree. | ||
|
||
import torch | ||
from torch import nn | ||
|
||
|
||
def scale_grads(m: nn.Module, scaler: torch.Tensor) -> None: | ||
for p in m.parameters(): | ||
if p.grad is not None: | ||
p.grad *= scaler | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there any concern here around overflows for lower dtypes? We could do a scaler range check based on dtype. Or is it better to leave it to the recipe to safely choose scaler values? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If there was ever a issue with numerical stability, another option for scaling the loss would be:
This might over complicate things but I wanted to leave this here if in the future it turns out a reduced gradient/loss is necessary for smaller dtypes.