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] Call clip gradients if clip val greater than 0 #6330

Merged
merged 5 commits into from
Mar 4, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 3 additions & 0 deletions pytorch_lightning/plugins/precision/sharded_native_amp.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,8 @@ def __init__(self) -> None:
self.scaler = ShardedGradScaler()

def clip_gradients(self, optimizer: 'Optimizer', clip_val: Union[int, float], norm_type: float = 2.0) -> None:
if clip_val <= 0:
return

optimizer = cast(OSS, optimizer)
optimizer.clip_grad_norm(clip_val, norm_type=norm_type)
17 changes: 17 additions & 0 deletions tests/plugins/test_sharded_plugin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
from unittest import mock

import pytest
import torch
Expand Down Expand Up @@ -269,3 +270,19 @@ def test_ddp_sharded_plugin_test_multigpu(tmpdir):
)

trainer.test(model)


@pytest.mark.parametrize("clip_val", [0, 10])
@RunIf(min_gpus=1, skip_windows=True, amp_native=True, fairscale=True)
SeanNaren marked this conversation as resolved.
Show resolved Hide resolved
@mock.patch('fairscale.optim.oss.OSS.clip_grad_norm')
def test_ddp_sharded_precision_16_clip_gradients(mock_oss_clip_grad_norm, clip_val, tmpdir):
"""
Ensure that clip gradients is only called if the value is greater than 0.
"""
model = BoringModel()
trainer = Trainer(accelerator='ddp_sharded', gpus=1, precision=16, fast_dev_run=True, gradient_clip_val=clip_val)
trainer.fit(model)
if clip_val > 0:
mock_oss_clip_grad_norm.assert_called()
else:
mock_oss_clip_grad_norm.assert_not_called()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice usage of mock! love it