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

add option to clip grad by value #810

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ def multiply(obj, num):
]
self.scheduler = LRScheduler(self.optimizer, self.config["optim"])

self.clip_grad_norm = self.config["optim"].get("clip_grad_norm")
self.clip_grad_norm = self.config["optim"].get("clip_grad_norm",None)
self.clip_grad_value = self.config["optim"].get("clip_grad_value",None)
self.ema_decay = self.config["optim"].get("ema_decay")
if self.ema_decay:
self.ema = ExponentialMovingAverage(
Expand Down
20 changes: 13 additions & 7 deletions src/fairchem/core/trainers/base_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,9 @@ def load_extras(self) -> None:
self.clip_grad_norm = aii(
self.config["optim"].get("clip_grad_norm", None), (int, float)
)
self.clip_grad_value = aii(
self.config["optim"].get("clip_grad_value", None), (int, float)
)
self.ema_decay = aii(self.config["optim"].get("ema_decay"), float)
if self.ema_decay:
self.ema = ExponentialMovingAverage(
Expand Down Expand Up @@ -889,15 +892,18 @@ def _backward(self, loss) -> None:
"Please check if all shared parameters are used "
"and point to PyTorch parameters."
)
if self.clip_grad_norm:
if self.clip_grad_norm or self.clip_grad_value:
if self.scaler:
self.scaler.unscale_(self.optimizer)
grad_norm = torch.nn.utils.clip_grad_norm_(
self.model.parameters(),
max_norm=self.clip_grad_norm,
)
if self.logger is not None:
self.logger.log({"grad_norm": grad_norm}, step=self.step, split="train")
if self.clip_grad_norm:
grad_norm = torch.nn.utils.clip_grad_norm_(
self.model.parameters(),
max_norm=self.clip_grad_norm,
)
if self.logger is not None:
self.logger.log({"grad_norm": grad_norm}, step=self.step, split="train")
if self.clip_grad_value:
torch.nn.utils.clip_grad_value_(self.model.parameters(), clip_value=self.clip_grad_value)
if self.scaler:
self.scaler.step(self.optimizer)
self.scaler.update()
Expand Down