2020-10-13 11:18:07 +00:00
|
|
|
# Copyright The PyTorch Lightning team.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2020-05-28 02:44:46 +00:00
|
|
|
import pytest
|
2021-01-05 06:51:22 +00:00
|
|
|
from torch import optim
|
2020-05-28 02:44:46 +00:00
|
|
|
|
2020-12-14 07:38:10 +00:00
|
|
|
import tests.base.develop_utils as tutils
|
2020-05-28 02:44:46 +00:00
|
|
|
from pytorch_lightning import Trainer
|
2020-09-03 18:17:15 +00:00
|
|
|
from pytorch_lightning.callbacks import LearningRateMonitor
|
2021-01-12 00:36:48 +00:00
|
|
|
from pytorch_lightning.trainer.states import TrainerState
|
2020-09-03 18:17:15 +00:00
|
|
|
from pytorch_lightning.utilities.exceptions import MisconfigurationException
|
2020-12-14 07:38:10 +00:00
|
|
|
from tests.base import BoringModel, EvalModelTemplate
|
2020-05-28 02:44:46 +00:00
|
|
|
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
def test_lr_monitor_single_lr(tmpdir):
|
2020-05-28 02:44:46 +00:00
|
|
|
""" Test that learning rates are extracted and logged for single lr scheduler. """
|
|
|
|
tutils.reset_seed()
|
|
|
|
|
|
|
|
model = EvalModelTemplate()
|
|
|
|
model.configure_optimizers = model.configure_optimizers__single_scheduler
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
lr_monitor = LearningRateMonitor()
|
2020-05-28 02:44:46 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
2020-06-01 15:00:32 +00:00
|
|
|
max_epochs=2,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.5,
|
2020-09-03 18:17:15 +00:00
|
|
|
callbacks=[lr_monitor],
|
2020-05-28 02:44:46 +00:00
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
assert trainer.state == TrainerState.FINISHED, f"Training failed with {trainer.state}"
|
2020-05-28 02:44:46 +00:00
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
assert lr_monitor.lrs, 'No learning rates logged'
|
2020-10-28 16:26:58 +00:00
|
|
|
assert all(v is None for v in lr_monitor.last_momentum_values.values()), \
|
|
|
|
'Momentum should not be logged by default'
|
2020-09-03 18:17:15 +00:00
|
|
|
assert len(lr_monitor.lrs) == len(trainer.lr_schedulers), \
|
2020-05-28 02:44:46 +00:00
|
|
|
'Number of learning rates logged does not match number of lr schedulers'
|
2020-12-14 07:38:10 +00:00
|
|
|
assert lr_monitor.lr_sch_names == list(lr_monitor.lrs.keys()) == ['lr-Adam'], \
|
2020-05-28 02:44:46 +00:00
|
|
|
'Names of learning rates not set correctly'
|
|
|
|
|
|
|
|
|
2021-01-05 06:51:22 +00:00
|
|
|
@pytest.mark.parametrize('opt', ['SGD', 'Adam'])
|
|
|
|
def test_lr_monitor_single_lr_with_momentum(tmpdir, opt):
|
|
|
|
"""
|
|
|
|
Test that learning rates and momentum are extracted and logged for single lr scheduler.
|
|
|
|
"""
|
2021-02-06 12:28:26 +00:00
|
|
|
|
2021-01-05 06:51:22 +00:00
|
|
|
class LogMomentumModel(BoringModel):
|
2021-02-06 12:28:26 +00:00
|
|
|
|
2021-01-05 06:51:22 +00:00
|
|
|
def __init__(self, opt):
|
|
|
|
super().__init__()
|
|
|
|
self.opt = opt
|
2020-10-28 16:26:58 +00:00
|
|
|
|
2021-01-05 06:51:22 +00:00
|
|
|
def configure_optimizers(self):
|
|
|
|
if self.opt == 'SGD':
|
|
|
|
opt_kwargs = {'momentum': 0.9}
|
|
|
|
elif self.opt == 'Adam':
|
|
|
|
opt_kwargs = {'betas': (0.9, 0.999)}
|
|
|
|
|
|
|
|
optimizer = getattr(optim, self.opt)(self.parameters(), lr=1e-2, **opt_kwargs)
|
|
|
|
lr_scheduler = optim.lr_scheduler.OneCycleLR(optimizer, max_lr=1e-2, total_steps=10_000)
|
|
|
|
return [optimizer], [lr_scheduler]
|
2020-10-28 16:26:58 +00:00
|
|
|
|
2021-01-05 06:51:22 +00:00
|
|
|
model = LogMomentumModel(opt=opt)
|
2020-10-28 16:26:58 +00:00
|
|
|
lr_monitor = LearningRateMonitor(log_momentum=True)
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=2,
|
2021-01-05 06:51:22 +00:00
|
|
|
limit_val_batches=2,
|
|
|
|
limit_train_batches=5,
|
|
|
|
log_every_n_steps=1,
|
2020-10-28 16:26:58 +00:00
|
|
|
callbacks=[lr_monitor],
|
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
assert trainer.state == TrainerState.FINISHED, f"Training failed with {trainer.state}"
|
2020-10-28 16:26:58 +00:00
|
|
|
|
|
|
|
assert all(v is not None for v in lr_monitor.last_momentum_values.values()), \
|
|
|
|
'Expected momentum to be logged'
|
|
|
|
assert len(lr_monitor.last_momentum_values) == len(trainer.lr_schedulers), \
|
|
|
|
'Number of momentum values logged does not match number of lr schedulers'
|
2021-01-05 06:51:22 +00:00
|
|
|
assert all(k == f'lr-{opt}-momentum' for k in lr_monitor.last_momentum_values.keys()), \
|
|
|
|
'Names of momentum values not set correctly'
|
|
|
|
|
|
|
|
|
|
|
|
def test_log_momentum_no_momentum_optimizer(tmpdir):
|
|
|
|
"""
|
|
|
|
Test that if optimizer doesn't have momentum then a warning is raised with log_momentum=True.
|
|
|
|
"""
|
2021-02-06 12:28:26 +00:00
|
|
|
|
2021-01-05 06:51:22 +00:00
|
|
|
class LogMomentumModel(BoringModel):
|
2021-02-06 12:28:26 +00:00
|
|
|
|
2021-01-05 06:51:22 +00:00
|
|
|
def configure_optimizers(self):
|
|
|
|
optimizer = optim.ASGD(self.parameters(), lr=1e-2)
|
|
|
|
lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=1)
|
|
|
|
return [optimizer], [lr_scheduler]
|
|
|
|
|
|
|
|
model = LogMomentumModel()
|
|
|
|
lr_monitor = LearningRateMonitor(log_momentum=True)
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=1,
|
|
|
|
limit_val_batches=2,
|
|
|
|
limit_train_batches=5,
|
|
|
|
log_every_n_steps=1,
|
|
|
|
callbacks=[lr_monitor],
|
|
|
|
)
|
|
|
|
with pytest.warns(RuntimeWarning, match="optimizers do not have momentum."):
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
assert trainer.state == TrainerState.FINISHED, f"Training failed with {trainer.state}"
|
2021-01-05 06:51:22 +00:00
|
|
|
|
|
|
|
assert all(v == 0 for v in lr_monitor.last_momentum_values.values()), \
|
|
|
|
'Expected momentum to be logged'
|
|
|
|
assert len(lr_monitor.last_momentum_values) == len(trainer.lr_schedulers), \
|
|
|
|
'Number of momentum values logged does not match number of lr schedulers'
|
|
|
|
assert all(k == 'lr-ASGD-momentum' for k in lr_monitor.last_momentum_values.keys()), \
|
2020-10-28 16:26:58 +00:00
|
|
|
'Names of momentum values not set correctly'
|
|
|
|
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
def test_lr_monitor_no_lr_scheduler(tmpdir):
|
2020-05-28 02:44:46 +00:00
|
|
|
tutils.reset_seed()
|
|
|
|
|
|
|
|
model = EvalModelTemplate()
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
lr_monitor = LearningRateMonitor()
|
2020-05-28 02:44:46 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
2020-06-01 15:00:32 +00:00
|
|
|
max_epochs=2,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.5,
|
2020-09-03 18:17:15 +00:00
|
|
|
callbacks=[lr_monitor],
|
2020-05-28 02:44:46 +00:00
|
|
|
)
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
with pytest.warns(RuntimeWarning, match='have no learning rate schedulers'):
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
assert trainer.state == TrainerState.FINISHED, f"Training failed with {trainer.state}"
|
2020-05-28 02:44:46 +00:00
|
|
|
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
def test_lr_monitor_no_logger(tmpdir):
|
|
|
|
tutils.reset_seed()
|
|
|
|
|
|
|
|
model = EvalModelTemplate()
|
|
|
|
|
|
|
|
lr_monitor = LearningRateMonitor()
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=1,
|
|
|
|
callbacks=[lr_monitor],
|
2021-02-06 12:28:26 +00:00
|
|
|
logger=False,
|
2020-09-03 18:17:15 +00:00
|
|
|
)
|
|
|
|
|
2021-01-05 06:51:22 +00:00
|
|
|
with pytest.raises(MisconfigurationException, match='`Trainer` that has no logger'):
|
2020-09-03 18:17:15 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
|
2020-08-09 16:30:43 +00:00
|
|
|
@pytest.mark.parametrize("logging_interval", ['step', 'epoch'])
|
2020-09-03 18:17:15 +00:00
|
|
|
def test_lr_monitor_multi_lrs(tmpdir, logging_interval):
|
2020-05-28 02:44:46 +00:00
|
|
|
""" Test that learning rates are extracted and logged for multi lr schedulers. """
|
|
|
|
tutils.reset_seed()
|
|
|
|
|
|
|
|
model = EvalModelTemplate()
|
|
|
|
model.configure_optimizers = model.configure_optimizers__multiple_schedulers
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
lr_monitor = LearningRateMonitor(logging_interval=logging_interval)
|
2020-10-22 11:08:03 +00:00
|
|
|
log_every_n_steps = 2
|
|
|
|
|
2020-05-28 02:44:46 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
2020-06-01 15:00:32 +00:00
|
|
|
max_epochs=2,
|
2020-10-22 11:08:03 +00:00
|
|
|
log_every_n_steps=log_every_n_steps,
|
|
|
|
limit_train_batches=7,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.1,
|
2020-09-03 18:17:15 +00:00
|
|
|
callbacks=[lr_monitor],
|
2020-05-28 02:44:46 +00:00
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
assert trainer.state == TrainerState.FINISHED, f"Training failed with {trainer.state}"
|
2020-05-28 02:44:46 +00:00
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
assert lr_monitor.lrs, 'No learning rates logged'
|
|
|
|
assert len(lr_monitor.lrs) == len(trainer.lr_schedulers), \
|
2020-05-28 02:44:46 +00:00
|
|
|
'Number of learning rates logged does not match number of lr schedulers'
|
2020-12-14 07:38:10 +00:00
|
|
|
assert lr_monitor.lr_sch_names == ['lr-Adam', 'lr-Adam-1'], \
|
2020-05-28 02:44:46 +00:00
|
|
|
'Names of learning rates not set correctly'
|
2020-08-09 16:30:43 +00:00
|
|
|
|
|
|
|
if logging_interval == 'step':
|
2020-10-22 11:08:03 +00:00
|
|
|
expected_number_logged = trainer.global_step // log_every_n_steps
|
2020-08-09 16:30:43 +00:00
|
|
|
if logging_interval == 'epoch':
|
|
|
|
expected_number_logged = trainer.max_epochs
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
assert all(len(lr) == expected_number_logged for lr in lr_monitor.lrs.values()), \
|
2020-08-09 16:30:43 +00:00
|
|
|
'Length of logged learning rates do not match the expected number'
|
2020-05-28 02:44:46 +00:00
|
|
|
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
def test_lr_monitor_param_groups(tmpdir):
|
2020-05-28 02:44:46 +00:00
|
|
|
""" Test that learning rates are extracted and logged for single lr scheduler. """
|
|
|
|
tutils.reset_seed()
|
|
|
|
|
|
|
|
model = EvalModelTemplate()
|
|
|
|
model.configure_optimizers = model.configure_optimizers__param_groups
|
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
lr_monitor = LearningRateMonitor()
|
2020-05-28 02:44:46 +00:00
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
2020-06-01 15:00:32 +00:00
|
|
|
max_epochs=2,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.5,
|
2020-09-03 18:17:15 +00:00
|
|
|
callbacks=[lr_monitor],
|
2020-05-28 02:44:46 +00:00
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
|
|
|
assert trainer.state == TrainerState.FINISHED, f"Training failed with {trainer.state}"
|
2020-05-28 02:44:46 +00:00
|
|
|
|
2020-09-03 18:17:15 +00:00
|
|
|
assert lr_monitor.lrs, 'No learning rates logged'
|
|
|
|
assert len(lr_monitor.lrs) == 2 * len(trainer.lr_schedulers), \
|
2020-05-28 02:44:46 +00:00
|
|
|
'Number of learning rates logged does not match number of param groups'
|
2020-12-14 07:38:10 +00:00
|
|
|
assert lr_monitor.lr_sch_names == ['lr-Adam']
|
|
|
|
assert list(lr_monitor.lrs.keys()) == ['lr-Adam/pg1', 'lr-Adam/pg2'], \
|
2020-05-28 02:44:46 +00:00
|
|
|
'Names of learning rates not set correctly'
|
2020-12-14 07:38:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_lr_monitor_custom_name(tmpdir):
|
2021-02-06 12:28:26 +00:00
|
|
|
|
2020-12-14 07:38:10 +00:00
|
|
|
class TestModel(BoringModel):
|
2021-02-06 12:28:26 +00:00
|
|
|
|
2020-12-14 07:38:10 +00:00
|
|
|
def configure_optimizers(self):
|
|
|
|
optimizer, [scheduler] = super().configure_optimizers()
|
|
|
|
lr_scheduler = {'scheduler': scheduler, 'name': 'my_logging_name'}
|
|
|
|
return optimizer, [lr_scheduler]
|
|
|
|
|
|
|
|
lr_monitor = LearningRateMonitor()
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=2,
|
|
|
|
limit_val_batches=0.1,
|
|
|
|
limit_train_batches=0.5,
|
|
|
|
callbacks=[lr_monitor],
|
|
|
|
progress_bar_refresh_rate=0,
|
|
|
|
weights_summary=None,
|
|
|
|
)
|
|
|
|
trainer.fit(TestModel())
|
|
|
|
assert lr_monitor.lr_sch_names == list(lr_monitor.lrs.keys()) == ['my_logging_name']
|