2020-03-03 20:16:57 +00:00
|
|
|
import glob
|
2020-02-18 16:23:22 +00:00
|
|
|
import math
|
2019-10-23 10:10:13 +00:00
|
|
|
import os
|
2020-03-24 18:55:27 +00:00
|
|
|
from argparse import Namespace
|
2020-03-12 16:41:37 +00:00
|
|
|
|
2019-10-23 10:10:13 +00:00
|
|
|
import pytest
|
|
|
|
import torch
|
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
import tests.base.utils as tutils
|
2020-03-12 16:41:37 +00:00
|
|
|
from pytorch_lightning import Trainer
|
2019-10-23 10:10:13 +00:00
|
|
|
from pytorch_lightning.callbacks import (
|
2020-02-18 16:23:22 +00:00
|
|
|
EarlyStopping,
|
2019-10-23 10:10:13 +00:00
|
|
|
ModelCheckpoint,
|
|
|
|
)
|
2020-03-12 16:41:37 +00:00
|
|
|
from pytorch_lightning.core.lightning import load_hparams_from_tags_csv
|
|
|
|
from pytorch_lightning.trainer.logging import TrainerLoggingMixin
|
|
|
|
from pytorch_lightning.utilities.debugging import MisconfigurationException
|
2020-03-25 11:46:27 +00:00
|
|
|
from tests.base import (
|
2020-02-25 18:06:24 +00:00
|
|
|
TestModelBase,
|
2020-03-04 14:33:39 +00:00
|
|
|
DictHparamsModel,
|
2019-10-23 10:10:13 +00:00
|
|
|
LightningTestModel,
|
2020-02-25 18:06:24 +00:00
|
|
|
LightEmptyTestStep,
|
|
|
|
LightValidationStepMixin,
|
|
|
|
LightValidationMultipleDataloadersMixin,
|
|
|
|
LightTrainDataloader,
|
|
|
|
LightTestDataloader,
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-03-05 04:02:19 +00:00
|
|
|
def test_hparams_save_load(tmpdir):
|
|
|
|
model = DictHparamsModel({'in_features': 28 * 28, 'out_features': 10})
|
|
|
|
|
|
|
|
# logger file to get meta
|
|
|
|
trainer_options = dict(
|
|
|
|
default_save_path=tmpdir,
|
|
|
|
max_epochs=2,
|
|
|
|
)
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
result = trainer.fit(model)
|
|
|
|
|
|
|
|
assert result == 1
|
|
|
|
|
|
|
|
# try to load the model now
|
|
|
|
pretrained_model = tutils.load_model_from_checkpoint(
|
|
|
|
trainer.checkpoint_callback.dirpath,
|
|
|
|
module_class=DictHparamsModel
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_no_val_module(tmpdir):
|
2019-12-04 11:48:53 +00:00
|
|
|
"""Tests use case where trainer saves the model, and user loads it from tags independently."""
|
2019-11-28 17:06:05 +00:00
|
|
|
tutils.reset_seed()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2020-02-25 18:06:24 +00:00
|
|
|
class CurrentTestModel(LightTrainDataloader, TestModelBase):
|
2019-10-23 10:10:13 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
model = CurrentTestModel(hparams)
|
|
|
|
|
|
|
|
# logger file to get meta
|
2020-03-25 11:46:27 +00:00
|
|
|
logger = tutils.get_default_testtube_logger(tmpdir, False)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
trainer_options = dict(
|
2019-12-07 13:50:21 +00:00
|
|
|
max_epochs=1,
|
2019-10-23 10:10:13 +00:00
|
|
|
logger=logger,
|
2019-12-04 11:48:53 +00:00
|
|
|
checkpoint_callback=ModelCheckpoint(tmpdir)
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
result = trainer.fit(model)
|
|
|
|
|
|
|
|
# training complete
|
|
|
|
assert result == 1, 'amp + ddp model failed to complete'
|
|
|
|
|
|
|
|
# save model
|
2019-12-04 11:48:53 +00:00
|
|
|
new_weights_path = os.path.join(tmpdir, 'save_test.ckpt')
|
2019-10-23 10:10:13 +00:00
|
|
|
trainer.save_checkpoint(new_weights_path)
|
|
|
|
|
|
|
|
# load new model
|
2020-01-16 12:22:29 +00:00
|
|
|
tags_path = tutils.get_data_path(logger, path_dir=tmpdir)
|
2019-10-23 10:10:13 +00:00
|
|
|
tags_path = os.path.join(tags_path, 'meta_tags.csv')
|
2020-03-03 02:05:38 +00:00
|
|
|
model_2 = LightningTestModel.load_from_checkpoint(
|
|
|
|
checkpoint_path=new_weights_path,
|
|
|
|
tags_csv=tags_path
|
|
|
|
)
|
2019-10-23 10:10:13 +00:00
|
|
|
model_2.eval()
|
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_no_val_end_module(tmpdir):
|
2019-12-04 11:48:53 +00:00
|
|
|
"""Tests use case where trainer saves the model, and user loads it from tags independently."""
|
2019-11-28 17:06:05 +00:00
|
|
|
tutils.reset_seed()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2020-02-25 18:06:24 +00:00
|
|
|
class CurrentTestModel(LightTrainDataloader, LightValidationStepMixin, TestModelBase):
|
2019-10-23 10:10:13 +00:00
|
|
|
pass
|
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2019-10-23 10:10:13 +00:00
|
|
|
model = CurrentTestModel(hparams)
|
|
|
|
|
|
|
|
# logger file to get meta
|
2020-03-25 11:46:27 +00:00
|
|
|
logger = tutils.get_default_testtube_logger(tmpdir, False)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
trainer_options = dict(
|
2019-12-07 13:50:21 +00:00
|
|
|
max_epochs=1,
|
2019-10-23 10:10:13 +00:00
|
|
|
logger=logger,
|
2019-12-04 11:48:53 +00:00
|
|
|
checkpoint_callback=ModelCheckpoint(tmpdir)
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
result = trainer.fit(model)
|
|
|
|
|
|
|
|
# traning complete
|
|
|
|
assert result == 1, 'amp + ddp model failed to complete'
|
|
|
|
|
|
|
|
# save model
|
2019-12-04 11:48:53 +00:00
|
|
|
new_weights_path = os.path.join(tmpdir, 'save_test.ckpt')
|
2019-10-23 10:10:13 +00:00
|
|
|
trainer.save_checkpoint(new_weights_path)
|
|
|
|
|
|
|
|
# load new model
|
2020-01-16 12:22:29 +00:00
|
|
|
tags_path = tutils.get_data_path(logger, path_dir=tmpdir)
|
2019-10-23 10:10:13 +00:00
|
|
|
tags_path = os.path.join(tags_path, 'meta_tags.csv')
|
2020-03-03 02:05:38 +00:00
|
|
|
model_2 = LightningTestModel.load_from_checkpoint(
|
|
|
|
checkpoint_path=new_weights_path,
|
|
|
|
tags_csv=tags_path
|
|
|
|
)
|
2019-10-23 10:10:13 +00:00
|
|
|
model_2.eval()
|
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_gradient_accumulation_scheduling(tmpdir):
|
2019-10-23 10:10:13 +00:00
|
|
|
"""
|
|
|
|
Test grad accumulation by the freq of optimizer updates
|
|
|
|
"""
|
2020-02-01 23:44:05 +00:00
|
|
|
tutils.reset_seed()
|
|
|
|
|
2019-10-23 10:10:13 +00:00
|
|
|
# test incorrect configs
|
|
|
|
with pytest.raises(IndexError):
|
|
|
|
assert Trainer(accumulate_grad_batches={0: 3, 1: 4, 4: 6})
|
|
|
|
assert Trainer(accumulate_grad_batches={-2: 3})
|
|
|
|
|
|
|
|
with pytest.raises(TypeError):
|
|
|
|
assert Trainer(accumulate_grad_batches={})
|
|
|
|
assert Trainer(accumulate_grad_batches=[[2, 3], [4, 6]])
|
|
|
|
assert Trainer(accumulate_grad_batches={1: 2, 3.: 4})
|
|
|
|
assert Trainer(accumulate_grad_batches={1: 2.5, 3: 5})
|
|
|
|
|
|
|
|
# test optimizer call freq matches scheduler
|
2020-03-05 04:02:19 +00:00
|
|
|
def _optimizer_step(self, epoch, batch_idx, optimizer,
|
|
|
|
optimizer_idx, second_order_closure=None):
|
2019-10-23 10:10:13 +00:00
|
|
|
# only test the first 12 batches in epoch
|
2019-12-04 11:57:10 +00:00
|
|
|
if batch_idx < 12:
|
2019-12-07 13:50:21 +00:00
|
|
|
if epoch == 0:
|
2019-10-23 10:10:13 +00:00
|
|
|
# reset counter when starting epoch
|
2019-12-04 11:57:10 +00:00
|
|
|
if batch_idx == 0:
|
|
|
|
self.prev_called_batch_idx = 0
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# use this opportunity to test once
|
|
|
|
assert self.trainer.accumulate_grad_batches == 1
|
|
|
|
|
2019-12-04 11:57:10 +00:00
|
|
|
assert batch_idx == self.prev_called_batch_idx
|
|
|
|
self.prev_called_batch_idx += 1
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2019-12-07 13:50:21 +00:00
|
|
|
elif 1 <= epoch <= 2:
|
2019-10-23 10:10:13 +00:00
|
|
|
# reset counter when starting epoch
|
2019-12-04 11:57:10 +00:00
|
|
|
if batch_idx == 1:
|
|
|
|
self.prev_called_batch_idx = 1
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# use this opportunity to test once
|
|
|
|
assert self.trainer.accumulate_grad_batches == 2
|
|
|
|
|
2019-12-04 11:57:10 +00:00
|
|
|
assert batch_idx == self.prev_called_batch_idx
|
|
|
|
self.prev_called_batch_idx += 2
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
else:
|
2019-12-04 11:57:10 +00:00
|
|
|
if batch_idx == 3:
|
|
|
|
self.prev_called_batch_idx = 3
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# use this opportunity to test once
|
|
|
|
assert self.trainer.accumulate_grad_batches == 4
|
|
|
|
|
2019-12-04 11:57:10 +00:00
|
|
|
assert batch_idx == self.prev_called_batch_idx
|
|
|
|
self.prev_called_batch_idx += 3
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
optimizer.step()
|
|
|
|
|
|
|
|
# clear gradients
|
|
|
|
optimizer.zero_grad()
|
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2019-10-23 10:10:13 +00:00
|
|
|
model = LightningTestModel(hparams)
|
|
|
|
schedule = {1: 2, 3: 4}
|
|
|
|
|
|
|
|
trainer = Trainer(accumulate_grad_batches=schedule,
|
|
|
|
train_percent_check=0.1,
|
|
|
|
val_percent_check=0.1,
|
2019-12-07 13:50:21 +00:00
|
|
|
max_epochs=4,
|
2019-12-03 13:01:04 +00:00
|
|
|
default_save_path=tmpdir)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# for the test
|
2020-03-04 14:33:39 +00:00
|
|
|
trainer.optimizer_step = _optimizer_step
|
2019-12-04 11:57:10 +00:00
|
|
|
model.prev_called_batch_idx = 0
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_loading_meta_tags(tmpdir):
|
2019-11-28 17:06:05 +00:00
|
|
|
tutils.reset_seed()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# save tags
|
2020-03-25 11:46:27 +00:00
|
|
|
logger = tutils.get_default_testtube_logger(tmpdir, False)
|
2019-10-23 10:10:13 +00:00
|
|
|
logger.log_hyperparams(Namespace(some_str='a_str', an_int=1, a_float=2.0))
|
|
|
|
logger.log_hyperparams(hparams)
|
|
|
|
logger.save()
|
|
|
|
|
|
|
|
# load tags
|
2020-01-16 12:22:29 +00:00
|
|
|
path_expt_dir = tutils.get_data_path(logger, path_dir=tmpdir)
|
|
|
|
tags_path = os.path.join(path_expt_dir, 'meta_tags.csv')
|
2020-01-17 11:03:31 +00:00
|
|
|
tags = load_hparams_from_tags_csv(tags_path)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
assert tags.batch_size == 32 and tags.hidden_dim == 1000
|
|
|
|
|
|
|
|
|
|
|
|
def test_dp_output_reduce():
|
|
|
|
mixin = TrainerLoggingMixin()
|
2019-11-28 17:06:05 +00:00
|
|
|
tutils.reset_seed()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# test identity when we have a single gpu
|
|
|
|
out = torch.rand(3, 1)
|
2019-12-04 11:57:10 +00:00
|
|
|
assert mixin.reduce_distributed_output(out, num_gpus=1) is out
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# average when we have multiples
|
2019-12-04 11:57:10 +00:00
|
|
|
assert mixin.reduce_distributed_output(out, num_gpus=2) == out.mean()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# when we have a dict of vals
|
|
|
|
out = {
|
|
|
|
'a': out,
|
|
|
|
'b': {
|
|
|
|
'c': out
|
|
|
|
}
|
|
|
|
}
|
2019-12-04 11:57:10 +00:00
|
|
|
reduced = mixin.reduce_distributed_output(out, num_gpus=3)
|
2019-10-23 10:10:13 +00:00
|
|
|
assert reduced['a'] == out['a']
|
|
|
|
assert reduced['b']['c'] == out['b']['c']
|
|
|
|
|
|
|
|
|
2020-03-12 16:46:25 +00:00
|
|
|
def test_model_checkpoint_options(tmpdir):
|
2019-12-04 11:48:53 +00:00
|
|
|
"""Test ModelCheckpoint options."""
|
2020-03-24 18:55:27 +00:00
|
|
|
|
2019-11-19 23:43:35 +00:00
|
|
|
def mock_save_function(filepath):
|
|
|
|
open(filepath, 'a').close()
|
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2019-12-04 11:48:53 +00:00
|
|
|
_ = LightningTestModel(hparams)
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
# simulated losses
|
2020-03-12 16:46:25 +00:00
|
|
|
save_dir = os.path.join(tmpdir, '1')
|
|
|
|
os.mkdir(save_dir)
|
2019-11-19 23:43:35 +00:00
|
|
|
losses = [10, 9, 2.8, 5, 2.5]
|
|
|
|
|
|
|
|
# -----------------
|
|
|
|
# CASE K=-1 (all)
|
2020-02-16 05:03:05 +00:00
|
|
|
checkpoint_callback = ModelCheckpoint(save_dir, save_top_k=-1, verbose=1)
|
|
|
|
checkpoint_callback.save_function = mock_save_function
|
|
|
|
trainer = Trainer()
|
|
|
|
|
|
|
|
# emulate callback's calls during the training
|
2019-11-19 23:43:35 +00:00
|
|
|
for i, loss in enumerate(losses):
|
2020-02-26 04:17:27 +00:00
|
|
|
trainer.current_epoch = i
|
|
|
|
trainer.callback_metrics = {'val_loss': loss}
|
|
|
|
checkpoint_callback.on_validation_end(trainer, trainer.get_model())
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
file_lists = set(os.listdir(save_dir))
|
|
|
|
|
|
|
|
assert len(file_lists) == len(losses), "Should save all models when save_top_k=-1"
|
|
|
|
|
|
|
|
# verify correct naming
|
2020-03-05 04:02:19 +00:00
|
|
|
for fname in {'epoch=4.ckpt',
|
|
|
|
'epoch=3.ckpt',
|
|
|
|
'epoch=2.ckpt',
|
|
|
|
'epoch=1.ckpt',
|
|
|
|
'epoch=0.ckpt'}:
|
2020-03-03 20:16:57 +00:00
|
|
|
assert fname in file_lists
|
2019-11-19 23:43:35 +00:00
|
|
|
|
2020-03-12 16:46:25 +00:00
|
|
|
save_dir = os.path.join(tmpdir, '2')
|
|
|
|
os.mkdir(save_dir)
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
# -----------------
|
|
|
|
# CASE K=0 (none)
|
2020-02-16 05:03:05 +00:00
|
|
|
checkpoint_callback = ModelCheckpoint(save_dir, save_top_k=0, verbose=1)
|
|
|
|
checkpoint_callback.save_function = mock_save_function
|
|
|
|
trainer = Trainer()
|
|
|
|
|
|
|
|
# emulate callback's calls during the training
|
2019-11-19 23:43:35 +00:00
|
|
|
for i, loss in enumerate(losses):
|
2020-02-26 04:17:27 +00:00
|
|
|
trainer.current_epoch = i
|
|
|
|
trainer.callback_metrics = {'val_loss': loss}
|
|
|
|
checkpoint_callback.on_validation_end(trainer, trainer.get_model())
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
file_lists = os.listdir(save_dir)
|
|
|
|
|
|
|
|
assert len(file_lists) == 0, "Should save 0 models when save_top_k=0"
|
|
|
|
|
2020-03-12 16:46:25 +00:00
|
|
|
save_dir = os.path.join(tmpdir, '3')
|
|
|
|
os.mkdir(save_dir)
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
# -----------------
|
|
|
|
# CASE K=1 (2.5, epoch 4)
|
2020-03-05 04:02:19 +00:00
|
|
|
checkpoint_callback = ModelCheckpoint(save_dir, save_top_k=1, verbose=1, prefix='test_prefix_')
|
2020-02-16 05:03:05 +00:00
|
|
|
checkpoint_callback.save_function = mock_save_function
|
|
|
|
trainer = Trainer()
|
|
|
|
|
|
|
|
# emulate callback's calls during the training
|
2019-11-19 23:43:35 +00:00
|
|
|
for i, loss in enumerate(losses):
|
2020-02-26 04:17:27 +00:00
|
|
|
trainer.current_epoch = i
|
|
|
|
trainer.callback_metrics = {'val_loss': loss}
|
|
|
|
checkpoint_callback.on_validation_end(trainer, trainer.get_model())
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
file_lists = set(os.listdir(save_dir))
|
|
|
|
|
|
|
|
assert len(file_lists) == 1, "Should save 1 model when save_top_k=1"
|
2020-03-05 04:02:19 +00:00
|
|
|
assert 'test_prefix_epoch=4.ckpt' in file_lists
|
2019-11-19 23:43:35 +00:00
|
|
|
|
2020-03-12 16:46:25 +00:00
|
|
|
save_dir = os.path.join(tmpdir, '4')
|
|
|
|
os.mkdir(save_dir)
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
# -----------------
|
|
|
|
# CASE K=2 (2.5 epoch 4, 2.8 epoch 2)
|
|
|
|
# make sure other files don't get deleted
|
|
|
|
|
2020-02-16 05:03:05 +00:00
|
|
|
checkpoint_callback = ModelCheckpoint(save_dir, save_top_k=2, verbose=1)
|
2020-02-27 01:31:40 +00:00
|
|
|
open(f"{save_dir}/other_file.ckpt", 'a').close()
|
2020-02-16 05:03:05 +00:00
|
|
|
checkpoint_callback.save_function = mock_save_function
|
|
|
|
trainer = Trainer()
|
|
|
|
|
|
|
|
# emulate callback's calls during the training
|
2019-11-19 23:43:35 +00:00
|
|
|
for i, loss in enumerate(losses):
|
2020-02-26 04:17:27 +00:00
|
|
|
trainer.current_epoch = i
|
|
|
|
trainer.callback_metrics = {'val_loss': loss}
|
|
|
|
checkpoint_callback.on_validation_end(trainer, trainer.get_model())
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
file_lists = set(os.listdir(save_dir))
|
|
|
|
|
|
|
|
assert len(file_lists) == 3, 'Should save 2 model when save_top_k=2'
|
2020-03-05 04:02:19 +00:00
|
|
|
for fname in {'epoch=4.ckpt',
|
|
|
|
'epoch=2.ckpt',
|
2020-03-03 20:16:57 +00:00
|
|
|
'other_file.ckpt'}:
|
|
|
|
assert fname in file_lists
|
2019-11-19 23:43:35 +00:00
|
|
|
|
2020-03-12 16:46:25 +00:00
|
|
|
save_dir = os.path.join(tmpdir, '5')
|
|
|
|
os.mkdir(save_dir)
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
# -----------------
|
2020-03-25 11:46:27 +00:00
|
|
|
# CASE K=4 (save all 4 base)
|
2019-11-19 23:43:35 +00:00
|
|
|
# multiple checkpoints within same epoch
|
|
|
|
|
2020-02-16 05:03:05 +00:00
|
|
|
checkpoint_callback = ModelCheckpoint(save_dir, save_top_k=4, verbose=1)
|
|
|
|
checkpoint_callback.save_function = mock_save_function
|
|
|
|
trainer = Trainer()
|
|
|
|
|
|
|
|
# emulate callback's calls during the training
|
2019-11-19 23:43:35 +00:00
|
|
|
for loss in losses:
|
2020-02-26 04:17:27 +00:00
|
|
|
trainer.current_epoch = 0
|
|
|
|
trainer.callback_metrics = {'val_loss': loss}
|
|
|
|
checkpoint_callback.on_validation_end(trainer, trainer.get_model())
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
file_lists = set(os.listdir(save_dir))
|
|
|
|
|
|
|
|
assert len(file_lists) == 4, 'Should save all 4 models when save_top_k=4 within same epoch'
|
|
|
|
|
2020-03-12 16:46:25 +00:00
|
|
|
save_dir = os.path.join(tmpdir, '6')
|
|
|
|
os.mkdir(save_dir)
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
# -----------------
|
|
|
|
# CASE K=3 (save the 2nd, 3rd, 4th model)
|
|
|
|
# multiple checkpoints within same epoch
|
|
|
|
|
2020-02-16 05:03:05 +00:00
|
|
|
checkpoint_callback = ModelCheckpoint(save_dir, save_top_k=3, verbose=1)
|
|
|
|
checkpoint_callback.save_function = mock_save_function
|
|
|
|
trainer = Trainer()
|
|
|
|
|
|
|
|
# emulate callback's calls during the training
|
2019-11-19 23:43:35 +00:00
|
|
|
for loss in losses:
|
2020-02-26 04:17:27 +00:00
|
|
|
trainer.current_epoch = 0
|
|
|
|
trainer.callback_metrics = {'val_loss': loss}
|
|
|
|
checkpoint_callback.on_validation_end(trainer, trainer.get_model())
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
file_lists = set(os.listdir(save_dir))
|
|
|
|
|
|
|
|
assert len(file_lists) == 3, 'Should save 3 models when save_top_k=3'
|
2020-03-05 04:02:19 +00:00
|
|
|
for fname in {'epoch=0.ckpt',
|
|
|
|
'epoch=0.ckpt',
|
|
|
|
'epoch=0.ckpt'}:
|
2020-03-03 20:16:57 +00:00
|
|
|
assert fname in file_lists
|
2019-11-19 23:43:35 +00:00
|
|
|
|
|
|
|
|
2019-10-23 10:10:13 +00:00
|
|
|
def test_model_freeze_unfreeze():
|
2019-11-28 17:06:05 +00:00
|
|
|
tutils.reset_seed()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2019-10-23 10:10:13 +00:00
|
|
|
model = LightningTestModel(hparams)
|
|
|
|
|
|
|
|
model.freeze()
|
|
|
|
model.unfreeze()
|
|
|
|
|
|
|
|
|
2020-02-22 01:27:19 +00:00
|
|
|
def test_resume_from_checkpoint_epoch_restored(tmpdir):
|
|
|
|
"""Verify resuming from checkpoint runs the right number of epochs"""
|
|
|
|
import types
|
|
|
|
|
|
|
|
tutils.reset_seed()
|
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2020-02-22 01:27:19 +00:00
|
|
|
|
2020-03-03 20:16:57 +00:00
|
|
|
def _new_model():
|
2020-02-22 01:27:19 +00:00
|
|
|
# Create a model that tracks epochs and batches seen
|
|
|
|
model = LightningTestModel(hparams)
|
|
|
|
model.num_epochs_seen = 0
|
|
|
|
model.num_batches_seen = 0
|
|
|
|
|
|
|
|
def increment_epoch(self):
|
|
|
|
self.num_epochs_seen += 1
|
|
|
|
|
|
|
|
def increment_batch(self, _):
|
|
|
|
self.num_batches_seen += 1
|
|
|
|
|
|
|
|
# Bind the increment_epoch function on_epoch_end so that the
|
|
|
|
# model keeps track of the number of epochs it has seen.
|
|
|
|
model.on_epoch_end = types.MethodType(increment_epoch, model)
|
|
|
|
model.on_batch_start = types.MethodType(increment_batch, model)
|
|
|
|
return model
|
|
|
|
|
2020-03-03 20:16:57 +00:00
|
|
|
model = _new_model()
|
2020-02-22 01:27:19 +00:00
|
|
|
|
|
|
|
trainer_options = dict(
|
|
|
|
show_progress_bar=False,
|
|
|
|
max_epochs=2,
|
|
|
|
train_percent_check=0.65,
|
|
|
|
val_percent_check=1,
|
|
|
|
checkpoint_callback=ModelCheckpoint(tmpdir, save_top_k=-1),
|
|
|
|
logger=False,
|
|
|
|
default_save_path=tmpdir,
|
|
|
|
early_stop_callback=False,
|
2020-03-03 20:16:57 +00:00
|
|
|
val_check_interval=1.,
|
2020-02-22 01:27:19 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
trainer.fit(model)
|
|
|
|
|
|
|
|
training_batches = trainer.num_training_batches
|
|
|
|
|
|
|
|
assert model.num_epochs_seen == 2
|
|
|
|
assert model.num_batches_seen == training_batches * 2
|
|
|
|
|
|
|
|
# Other checkpoints can be uncommented if/when resuming mid-epoch is supported
|
2020-03-03 20:16:57 +00:00
|
|
|
checkpoints = sorted(glob.glob(os.path.join(trainer.checkpoint_callback.dirpath, '*.ckpt')))
|
2020-02-22 01:27:19 +00:00
|
|
|
|
|
|
|
for check in checkpoints:
|
2020-03-03 20:16:57 +00:00
|
|
|
next_model = _new_model()
|
2020-02-22 01:27:19 +00:00
|
|
|
state = torch.load(check)
|
|
|
|
|
|
|
|
# Resume training
|
|
|
|
trainer_options['max_epochs'] = 4
|
|
|
|
new_trainer = Trainer(**trainer_options, resume_from_checkpoint=check)
|
|
|
|
new_trainer.fit(next_model)
|
|
|
|
assert state['global_step'] + next_model.num_batches_seen == training_batches * 4
|
|
|
|
|
|
|
|
|
2020-02-18 16:23:22 +00:00
|
|
|
def _init_steps_model():
|
|
|
|
"""private method for initializing a model with 5% train epochs"""
|
|
|
|
tutils.reset_seed()
|
2020-03-25 11:46:27 +00:00
|
|
|
model, _ = tutils.get_default_model()
|
2020-02-18 16:23:22 +00:00
|
|
|
|
|
|
|
# define train epoch to 5% of data
|
|
|
|
train_percent = 0.05
|
|
|
|
# get number of samples in 1 epoch
|
|
|
|
num_train_samples = math.floor(len(model.train_dataloader()) * train_percent)
|
|
|
|
|
|
|
|
trainer_options = dict(
|
|
|
|
train_percent_check=train_percent,
|
|
|
|
)
|
|
|
|
return model, trainer_options, num_train_samples
|
|
|
|
|
|
|
|
|
|
|
|
def test_trainer_max_steps_and_epochs(tmpdir):
|
|
|
|
"""Verify model trains according to specified max steps"""
|
|
|
|
model, trainer_options, num_train_samples = _init_steps_model()
|
|
|
|
|
|
|
|
# define less train steps than epochs
|
|
|
|
trainer_options.update(dict(
|
2020-02-25 18:06:24 +00:00
|
|
|
default_save_path=tmpdir,
|
2020-02-18 16:23:22 +00:00
|
|
|
max_epochs=5,
|
|
|
|
max_steps=num_train_samples + 10
|
|
|
|
))
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
result = trainer.fit(model)
|
|
|
|
assert result == 1, "Training did not complete"
|
|
|
|
|
|
|
|
# check training stopped at max_steps
|
|
|
|
assert trainer.global_step == trainer.max_steps, "Model did not stop at max_steps"
|
|
|
|
|
|
|
|
# define less train epochs than steps
|
2020-02-25 18:06:24 +00:00
|
|
|
trainer_options.update(dict(
|
|
|
|
max_epochs=2,
|
|
|
|
max_steps=trainer_options['max_epochs'] * 2 * num_train_samples
|
|
|
|
))
|
2020-02-18 16:23:22 +00:00
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
result = trainer.fit(model)
|
|
|
|
assert result == 1, "Training did not complete"
|
|
|
|
|
|
|
|
# check training stopped at max_epochs
|
2020-02-25 18:06:24 +00:00
|
|
|
assert trainer.global_step == num_train_samples * trainer.max_epochs \
|
|
|
|
and trainer.current_epoch == trainer.max_epochs - 1, "Model did not stop at max_epochs"
|
2020-02-18 16:23:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_trainer_min_steps_and_epochs(tmpdir):
|
|
|
|
"""Verify model trains according to specified min steps"""
|
|
|
|
model, trainer_options, num_train_samples = _init_steps_model()
|
|
|
|
|
|
|
|
# define callback for stopping the model and default epochs
|
2020-02-25 18:06:24 +00:00
|
|
|
trainer_options.update(dict(
|
|
|
|
default_save_path=tmpdir,
|
|
|
|
early_stop_callback=EarlyStopping(monitor='val_loss', min_delta=1.0),
|
2020-03-25 11:46:27 +00:00
|
|
|
val_check_interval=2,
|
2020-02-25 18:06:24 +00:00
|
|
|
min_epochs=1,
|
|
|
|
max_epochs=10
|
|
|
|
))
|
2020-02-18 16:23:22 +00:00
|
|
|
|
|
|
|
# define less min steps than 1 epoch
|
|
|
|
trainer_options['min_steps'] = math.floor(num_train_samples / 2)
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
result = trainer.fit(model)
|
|
|
|
assert result == 1, "Training did not complete"
|
|
|
|
|
|
|
|
# check model ran for at least min_epochs
|
|
|
|
assert trainer.global_step >= num_train_samples and \
|
|
|
|
trainer.current_epoch > 0, "Model did not train for at least min_epochs"
|
|
|
|
|
|
|
|
# define less epochs than min_steps
|
|
|
|
trainer_options['min_steps'] = math.floor(num_train_samples * 1.5)
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
result = trainer.fit(model)
|
|
|
|
assert result == 1, "Training did not complete"
|
|
|
|
|
|
|
|
# check model ran for at least num_train_samples*1.5
|
|
|
|
assert trainer.global_step >= math.floor(num_train_samples * 1.5) and \
|
|
|
|
trainer.current_epoch > 0, "Model did not train for at least min_steps"
|
|
|
|
|
2020-02-19 11:00:08 +00:00
|
|
|
|
2020-02-25 20:05:41 +00:00
|
|
|
def test_benchmark_option(tmpdir):
|
|
|
|
"""Verify benchmark option."""
|
|
|
|
tutils.reset_seed()
|
|
|
|
|
|
|
|
class CurrentTestModel(
|
2020-02-26 04:17:27 +00:00
|
|
|
LightValidationMultipleDataloadersMixin,
|
|
|
|
LightTrainDataloader,
|
|
|
|
TestModelBase
|
2020-02-25 20:05:41 +00:00
|
|
|
):
|
|
|
|
pass
|
|
|
|
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2020-02-25 20:05:41 +00:00
|
|
|
model = CurrentTestModel(hparams)
|
|
|
|
|
|
|
|
# verify torch.backends.cudnn.benchmark is not turned on
|
|
|
|
assert not torch.backends.cudnn.benchmark
|
|
|
|
|
|
|
|
# logger file to get meta
|
|
|
|
trainer_options = dict(
|
|
|
|
default_save_path=tmpdir,
|
|
|
|
max_epochs=1,
|
|
|
|
benchmark=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(**trainer_options)
|
|
|
|
result = trainer.fit(model)
|
|
|
|
|
|
|
|
# verify training completed
|
|
|
|
assert result == 1
|
|
|
|
|
|
|
|
# verify torch.backends.cudnn.benchmark is not turned off
|
|
|
|
assert torch.backends.cudnn.benchmark
|
|
|
|
|
|
|
|
|
2020-02-25 03:33:11 +00:00
|
|
|
def test_testpass_overrides(tmpdir):
|
2020-03-25 11:46:27 +00:00
|
|
|
hparams = tutils.get_default_hparams()
|
2020-02-25 03:33:11 +00:00
|
|
|
|
2020-02-25 18:06:24 +00:00
|
|
|
class LocalModel(LightTrainDataloader, TestModelBase):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class LocalModelNoEnd(LightTrainDataloader, LightTestDataloader, LightEmptyTestStep, TestModelBase):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class LocalModelNoStep(LightTrainDataloader, TestModelBase):
|
2020-03-06 00:31:57 +00:00
|
|
|
def test_epoch_end(self, outputs):
|
2020-02-25 03:33:11 +00:00
|
|
|
return {}
|
|
|
|
|
2020-02-25 18:06:24 +00:00
|
|
|
# Misconfig when neither test_step or test_end is implemented
|
|
|
|
with pytest.raises(MisconfigurationException):
|
|
|
|
model = LocalModel(hparams)
|
|
|
|
Trainer().test(model)
|
2020-02-25 03:33:11 +00:00
|
|
|
|
|
|
|
# Misconfig when neither test_step or test_end is implemented
|
|
|
|
with pytest.raises(MisconfigurationException):
|
2020-02-25 18:06:24 +00:00
|
|
|
model = LocalModelNoStep(hparams)
|
2020-02-25 03:33:11 +00:00
|
|
|
Trainer().test(model)
|
|
|
|
|
|
|
|
# No exceptions when one or both of test_step or test_end are implemented
|
2020-02-25 18:06:24 +00:00
|
|
|
model = LocalModelNoEnd(hparams)
|
2020-02-25 03:33:11 +00:00
|
|
|
Trainer().test(model)
|
|
|
|
|
|
|
|
model = LightningTestModel(hparams)
|
|
|
|
Trainer().test(model)
|