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

move out zero grad logic into separate function #969

Closed
wants to merge 1 commit into from
Closed
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
18 changes: 17 additions & 1 deletion torchtnt/framework/auto_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,22 @@ def step_lr_scheduler(self) -> None:
"""
none_throws(self.lr_scheduler).step()

def zero_grad(self) -> None:
"""
Zeroes the gradients of the module's parameters. Override this if you need to log the gradients before zeroing them.
Example of overriding:
class CustomAutoUnit(MyAutoUnit):
...
def zero_grad(self):
# log before zeroing gradients
super().zero_grad()
"""

optimizer = none_throws(self.optimizer)
optimizer.zero_grad(set_to_none=True)

def _update_weights(self, state: State) -> Optional[torch.Tensor]:
"""
Updates weights of the module, handles clip gradient norm, etc.
Expand Down Expand Up @@ -892,7 +908,7 @@ def _update_weights(self, state: State) -> Optional[torch.Tensor]:
with get_timing_context(
state, f"{self.__class__.__name__}.optimizer_zero_grad"
):
optimizer.zero_grad(set_to_none=True)
self.zero_grad()

if self.step_lr_interval == "step":
self._update_lr_and_swa(state, self.train_progress.num_steps_completed)
Expand Down
Loading