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

Added gradient clip test for native AMP #3754

Merged
merged 2 commits into from
Oct 1, 2020
Merged
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
31 changes: 31 additions & 0 deletions tests/trainer/test_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from pytorch_lightning.trainer.logging import TrainerLoggingMixin
from pytorch_lightning.utilities.cloud_io import load as pl_load
from pytorch_lightning.utilities.exceptions import MisconfigurationException
from pytorch_lightning.utilities import NATIVE_AMP_AVALAIBLE
from tests.base import EvalModelTemplate


Expand Down Expand Up @@ -867,6 +868,36 @@ def _optimizer_step(*args, **kwargs):
trainer.fit(model)


@pytest.mark.skipif(not torch.cuda.is_available(), reason="test requires GPU machine")
@pytest.mark.skipif(not NATIVE_AMP_AVALAIBLE, reason="test requires native AMP.")
def test_gradient_clipping_fp16(tmpdir):
"""
Test gradient clipping with fp16
"""

model = EvalModelTemplate()

# test that gradient is clipped correctly
def _optimizer_step(*args, **kwargs):
parameters = model.parameters()
grad_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), 2) for p in parameters]), 2)
assert (grad_norm - 1.0).abs() < 0.01, "Gradient norm != 1.0: {grad_norm}".format(grad_norm=grad_norm)

trainer = Trainer(
max_steps=1,
max_epochs=1,
precision=16,
gpus=1,
gradient_clip_val=1.0,
default_root_dir=tmpdir,
)

# for the test
model.optimizer_step = _optimizer_step
model.prev_called_batch_idx = 0

trainer.fit(model)

def test_gpu_choice(tmpdir):
trainer_options = dict(
default_root_dir=tmpdir,
Expand Down