Skip to content

Commit

Permalink
[Fix] Call clip gradients if clip val greater than 0 (#6330)
Browse files Browse the repository at this point in the history
* Call clip gradients if clip val greater than 0

* format

* Format

* Move to top of file
  • Loading branch information
SeanNaren authored Mar 4, 2021
1 parent 8e3524d commit 39231ae
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
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 All @@ -11,6 +12,22 @@
from tests.helpers.runif import RunIf


@pytest.mark.parametrize("clip_val", [0, 10])
@RunIf(min_gpus=1, skip_windows=True, amp_native=True, fairscale=True)
@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()


@RunIf(fairscale=True)
@pytest.mark.parametrize(["accelerator"], [("ddp_sharded", ), ("ddp_sharded_spawn", )])
def test_sharded_ddp_choice(tmpdir, accelerator):
Expand Down

0 comments on commit 39231ae

Please sign in to comment.