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

Fix freezing modules in Ghost Clipping #729

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
14 changes: 14 additions & 0 deletions opacus/grad_sample/grad_sample_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,20 @@ def __init__(
force_functorch=force_functorch,
)

def requires_grad_(self, requires_grad: bool = True) -> nn.Module:
"Rewrite requires_grad_ to add/remove hooks based on requires_grad value"
if requires_grad:
# Attack hook to the module
self.add_hooks(
loss_reduction=self.loss_reduction,
batch_first=self.batch_first,
force_functorch=self.force_functorch,
)
else:
# Remove hooks
self.remove_hooks()
return super().requires_grad_(requires_grad)

def forward(self, *args, **kwargs):
return self._module(*args, **kwargs)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def __init__(
strict=strict,
force_functorch=force_functorch,
)
self.trainable_parameters = [p for _, p in trainable_parameters(self._module)]
self.all_parameters = [p for p in self.parameters()]
self.max_grad_norm = max_grad_norm
self.use_ghost_clipping = use_ghost_clipping
self._per_sample_gradient_norms = None
Expand All @@ -130,7 +130,12 @@ def get_clipping_coef(self) -> torch.Tensor:
def get_norm_sample(self) -> torch.Tensor:
"""Get per-example gradient norms."""
norm_sample = torch.stack(
[param._norm_sample for param in self.trainable_parameters], dim=0
[
param._norm_sample
for param in self.all_parameters
if param.requires_grad
],
dim=0,
).norm(2, dim=0)
self.per_sample_gradient_norms = norm_sample
return norm_sample
Expand Down
Loading