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-06-01 15:00:32 +00:00
|
|
|
import os
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2021-07-01 21:16:14 +00:00
|
|
|
import pytest
|
2019-10-23 10:10:13 +00:00
|
|
|
import torch
|
|
|
|
|
2021-02-08 10:52:02 +00:00
|
|
|
import tests.helpers.pipelines as tpipes
|
|
|
|
import tests.helpers.utils as tutils
|
2020-03-06 21:11:05 +00:00
|
|
|
from pytorch_lightning import Trainer
|
2021-01-07 10:50:08 +00:00
|
|
|
from pytorch_lightning.callbacks import Callback, EarlyStopping, ModelCheckpoint
|
2021-02-09 10:10:52 +00:00
|
|
|
from tests.helpers import BoringModel
|
2021-02-09 17:25:57 +00:00
|
|
|
from tests.helpers.datamodules import ClassifDataModule
|
2021-03-02 09:36:01 +00:00
|
|
|
from tests.helpers.runif import RunIf
|
2021-02-09 17:25:57 +00:00
|
|
|
from tests.helpers.simple_models import ClassificationModel
|
2021-01-23 23:52:04 +00:00
|
|
|
|
2020-06-01 15:00:32 +00:00
|
|
|
|
2021-01-08 21:13:12 +00:00
|
|
|
def test_cpu_slurm_save_load(tmpdir):
|
2020-06-01 15:00:32 +00:00
|
|
|
"""Verify model save/load/checkpoint on CPU."""
|
2021-01-07 10:50:08 +00:00
|
|
|
model = BoringModel()
|
2020-06-01 15:00:32 +00:00
|
|
|
|
|
|
|
# logger file to get meta
|
|
|
|
logger = tutils.get_default_logger(tmpdir)
|
|
|
|
version = logger.version
|
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(
|
2020-06-29 01:36:46 +00:00
|
|
|
default_root_dir=tmpdir,
|
2020-06-01 15:00:32 +00:00
|
|
|
max_epochs=1,
|
|
|
|
logger=logger,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.2,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
2020-12-09 19:14:34 +00:00
|
|
|
callbacks=[ModelCheckpoint(dirpath=tmpdir)],
|
2020-06-01 15:00:32 +00:00
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
2020-06-01 15:00:32 +00:00
|
|
|
real_global_step = trainer.global_step
|
|
|
|
|
|
|
|
# traning complete
|
2021-05-04 10:50:56 +00:00
|
|
|
assert trainer.state.finished, 'cpu model failed to complete'
|
2020-06-01 15:00:32 +00:00
|
|
|
|
|
|
|
# predict with trained model before saving
|
|
|
|
# make a prediction
|
|
|
|
dataloaders = model.test_dataloader()
|
|
|
|
if not isinstance(dataloaders, list):
|
|
|
|
dataloaders = [dataloaders]
|
|
|
|
|
|
|
|
for dataloader in dataloaders:
|
|
|
|
for batch in dataloader:
|
|
|
|
break
|
|
|
|
|
|
|
|
model.eval()
|
2021-01-07 10:50:08 +00:00
|
|
|
pred_before_saving = model(batch)
|
2020-06-01 15:00:32 +00:00
|
|
|
|
|
|
|
# test HPC saving
|
|
|
|
# simulate snapshot on slurm
|
2020-09-12 12:42:27 +00:00
|
|
|
saved_filepath = trainer.checkpoint_connector.hpc_save(trainer.weights_save_path, logger)
|
2020-06-01 15:00:32 +00:00
|
|
|
assert os.path.exists(saved_filepath)
|
|
|
|
|
|
|
|
# new logger file to get meta
|
|
|
|
logger = tutils.get_default_logger(tmpdir, version=version)
|
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
model = BoringModel()
|
|
|
|
|
|
|
|
class _StartCallback(Callback):
|
|
|
|
# set the epoch start hook so we can predict before the model does the full training
|
|
|
|
def on_train_epoch_start(self, trainer, model):
|
|
|
|
assert trainer.global_step == real_global_step and trainer.global_step > 0
|
|
|
|
# predict with loaded model to make sure answers are the same
|
|
|
|
mode = model.training
|
|
|
|
model.eval()
|
|
|
|
new_pred = model(batch)
|
|
|
|
assert torch.eq(pred_before_saving, new_pred).all()
|
|
|
|
model.train(mode)
|
|
|
|
|
2020-06-01 15:00:32 +00:00
|
|
|
trainer = Trainer(
|
2020-06-29 01:36:46 +00:00
|
|
|
default_root_dir=tmpdir,
|
2020-06-01 15:00:32 +00:00
|
|
|
max_epochs=1,
|
|
|
|
logger=logger,
|
2021-01-07 10:50:08 +00:00
|
|
|
callbacks=[_StartCallback(), ModelCheckpoint(dirpath=tmpdir)],
|
2020-06-01 15:00:32 +00:00
|
|
|
)
|
|
|
|
# by calling fit again, we trigger training, loading weights from the cluster
|
|
|
|
# and our hook to predict using current model before any more weight updates
|
|
|
|
trainer.fit(model)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
|
2021-01-08 21:13:12 +00:00
|
|
|
def test_early_stopping_cpu_model(tmpdir):
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
class ModelTrainVal(BoringModel):
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
def validation_step(self, *args, **kwargs):
|
|
|
|
output = super().validation_step(*args, **kwargs)
|
|
|
|
self.log('val_loss', output['x'])
|
|
|
|
return output
|
2021-01-07 10:50:08 +00:00
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
tutils.reset_seed()
|
2021-01-07 10:50:08 +00:00
|
|
|
stopping = EarlyStopping(monitor="val_loss", min_delta=0.1)
|
2019-10-23 10:10:13 +00:00
|
|
|
trainer_options = dict(
|
2020-10-08 10:30:33 +00:00
|
|
|
callbacks=[stopping],
|
2021-01-07 10:50:08 +00:00
|
|
|
default_root_dir=tmpdir,
|
2019-10-23 10:10:13 +00:00
|
|
|
gradient_clip_val=1.0,
|
2020-06-17 12:03:28 +00:00
|
|
|
overfit_batches=0.20,
|
2019-10-23 10:10:13 +00:00
|
|
|
track_grad_norm=2,
|
2021-01-07 10:50:08 +00:00
|
|
|
progress_bar_refresh_rate=0,
|
|
|
|
accumulate_grad_batches=2,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.1,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.1,
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
model = ModelTrainVal()
|
2020-06-27 01:38:25 +00:00
|
|
|
tpipes.run_model_test(trainer_options, model, on_gpu=False)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# test freeze on cpu
|
|
|
|
model.freeze()
|
|
|
|
model.unfreeze()
|
|
|
|
|
|
|
|
|
2021-03-02 09:36:01 +00:00
|
|
|
@RunIf(skip_windows=True)
|
2021-01-08 21:13:12 +00:00
|
|
|
def test_multi_cpu_model_ddp(tmpdir):
|
2020-04-16 03:17:31 +00:00
|
|
|
"""Make sure DDP works."""
|
|
|
|
tutils.set_random_master_port()
|
|
|
|
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=tmpdir,
|
2020-04-24 18:45:43 +00:00
|
|
|
progress_bar_refresh_rate=0,
|
2020-04-16 03:17:31 +00:00
|
|
|
max_epochs=1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.4,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
2020-04-16 03:17:31 +00:00
|
|
|
gpus=None,
|
|
|
|
num_processes=2,
|
2020-12-09 08:18:23 +00:00
|
|
|
accelerator='ddp_cpu',
|
2020-04-16 03:17:31 +00:00
|
|
|
)
|
|
|
|
|
2021-02-09 17:25:57 +00:00
|
|
|
dm = ClassifDataModule()
|
|
|
|
model = ClassificationModel()
|
|
|
|
tpipes.run_model_test(trainer_options, model, data=dm, on_gpu=False)
|
2020-04-16 03:17:31 +00:00
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_lbfgs_cpu_model(tmpdir):
|
2021-01-07 10:50:08 +00:00
|
|
|
"""Test each of the trainer options. Testing LBFGS optimizer"""
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
class ModelSpecifiedOptimizer(BoringModel):
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
def __init__(self, optimizer_name, learning_rate):
|
|
|
|
super().__init__()
|
|
|
|
self.optimizer_name = optimizer_name
|
|
|
|
self.learning_rate = learning_rate
|
|
|
|
self.save_hyperparameters()
|
|
|
|
|
2019-10-23 10:10:13 +00:00
|
|
|
trainer_options = dict(
|
2020-04-10 16:02:59 +00:00
|
|
|
default_root_dir=tmpdir,
|
2020-06-01 15:00:32 +00:00
|
|
|
max_epochs=1,
|
2020-04-02 22:53:00 +00:00
|
|
|
progress_bar_refresh_rate=0,
|
2021-01-07 10:50:08 +00:00
|
|
|
weights_summary="top",
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.2,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
model = ModelSpecifiedOptimizer(optimizer_name="LBFGS", learning_rate=0.004)
|
2021-02-09 17:25:57 +00:00
|
|
|
tpipes.run_model_test_without_loggers(trainer_options, model, min_acc=0.01)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_default_logger_callbacks_cpu_model(tmpdir):
|
2019-12-04 11:48:53 +00:00
|
|
|
"""Test each of the trainer options."""
|
2019-10-23 10:10:13 +00:00
|
|
|
trainer_options = dict(
|
2020-04-10 16:02:59 +00:00
|
|
|
default_root_dir=tmpdir,
|
2019-12-07 13:50:21 +00:00
|
|
|
max_epochs=1,
|
2019-10-23 10:10:13 +00:00
|
|
|
gradient_clip_val=1.0,
|
2020-06-17 12:03:28 +00:00
|
|
|
overfit_batches=0.20,
|
2020-04-02 22:53:00 +00:00
|
|
|
progress_bar_refresh_rate=0,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.01,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.01,
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
model = BoringModel()
|
|
|
|
tpipes.run_model_test_without_loggers(trainer_options, model, min_acc=0.01)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# test freeze on cpu
|
|
|
|
model.freeze()
|
|
|
|
model.unfreeze()
|
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_running_test_after_fitting(tmpdir):
|
2019-12-04 11:48:53 +00:00
|
|
|
"""Verify test() on fitted model."""
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
class ModelTrainValTest(BoringModel):
|
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
def validation_step(self, *args, **kwargs):
|
|
|
|
output = super().validation_step(*args, **kwargs)
|
|
|
|
self.log('val_loss', output['x'])
|
|
|
|
return output
|
2021-01-07 10:50:08 +00:00
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
def test_step(self, *args, **kwargs):
|
|
|
|
output = super().test_step(*args, **kwargs)
|
|
|
|
self.log('test_loss', output['y'])
|
|
|
|
return output
|
2021-01-07 10:50:08 +00:00
|
|
|
|
|
|
|
model = ModelTrainValTest()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# logger file to get meta
|
2020-04-22 00:33:10 +00:00
|
|
|
logger = tutils.get_default_logger(tmpdir)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# logger file to get weights
|
2019-11-28 17:06:05 +00:00
|
|
|
checkpoint = tutils.init_checkpoint_callback(logger)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2020-05-01 14:43:58 +00:00
|
|
|
# fit model
|
|
|
|
trainer = Trainer(
|
2020-04-10 16:02:59 +00:00
|
|
|
default_root_dir=tmpdir,
|
2020-04-02 22:53:00 +00:00
|
|
|
progress_bar_refresh_rate=0,
|
2020-06-01 15:00:32 +00:00
|
|
|
max_epochs=2,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.4,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
|
|
|
limit_test_batches=0.2,
|
2020-12-09 19:14:34 +00:00
|
|
|
callbacks=[checkpoint],
|
2020-06-27 01:38:25 +00:00
|
|
|
logger=logger,
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2021-05-04 10:50:56 +00:00
|
|
|
assert trainer.state.finished, f"Training failed with {trainer.state}"
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
trainer.test()
|
|
|
|
|
|
|
|
# test we have good test accuracy
|
2021-01-07 10:50:08 +00:00
|
|
|
tutils.assert_ok_model_acc(trainer, key='test_loss', thr=0.5)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
|
2020-04-22 00:33:10 +00:00
|
|
|
def test_running_test_no_val(tmpdir):
|
2021-01-07 10:50:08 +00:00
|
|
|
"""Verify `test()` works on a model with no `val_dataloader`. It performs
|
|
|
|
train and test only"""
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
class ModelTrainTest(BoringModel):
|
|
|
|
|
|
|
|
def val_dataloader(self):
|
|
|
|
pass
|
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
def test_step(self, *args, **kwargs):
|
|
|
|
output = super().test_step(*args, **kwargs)
|
|
|
|
self.log('test_loss', output['y'])
|
|
|
|
return output
|
2021-01-07 10:50:08 +00:00
|
|
|
|
|
|
|
model = ModelTrainTest()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# logger file to get meta
|
2020-04-22 00:33:10 +00:00
|
|
|
logger = tutils.get_default_logger(tmpdir)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# logger file to get weights
|
2019-11-28 17:06:05 +00:00
|
|
|
checkpoint = tutils.init_checkpoint_callback(logger)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2020-05-01 14:43:58 +00:00
|
|
|
# fit model
|
|
|
|
trainer = Trainer(
|
2020-06-29 01:36:46 +00:00
|
|
|
default_root_dir=tmpdir,
|
2020-04-02 22:53:00 +00:00
|
|
|
progress_bar_refresh_rate=0,
|
2019-12-07 13:50:21 +00:00
|
|
|
max_epochs=1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=0.4,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.2,
|
|
|
|
limit_test_batches=0.2,
|
2020-12-09 19:14:34 +00:00
|
|
|
callbacks=[checkpoint],
|
2020-01-23 16:12:51 +00:00
|
|
|
logger=logger,
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2021-05-04 10:50:56 +00:00
|
|
|
assert trainer.state.finished, f"Training failed with {trainer.state}"
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
trainer.test()
|
|
|
|
|
|
|
|
# test we have good test accuracy
|
2021-01-07 10:50:08 +00:00
|
|
|
tutils.assert_ok_model_acc(trainer, key='test_loss')
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_simple_cpu(tmpdir):
|
2019-12-04 11:48:53 +00:00
|
|
|
"""Verify continue training session on CPU."""
|
2021-01-07 10:50:08 +00:00
|
|
|
model = BoringModel()
|
2019-10-23 10:10:13 +00:00
|
|
|
|
2020-05-01 14:43:58 +00:00
|
|
|
# fit model
|
|
|
|
trainer = Trainer(
|
2020-04-10 16:02:59 +00:00
|
|
|
default_root_dir=tmpdir,
|
2019-12-07 13:50:21 +00:00
|
|
|
max_epochs=1,
|
2020-06-17 12:03:28 +00:00
|
|
|
limit_val_batches=0.1,
|
2020-06-17 17:42:28 +00:00
|
|
|
limit_train_batches=20,
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
# traning complete
|
2021-05-04 10:50:56 +00:00
|
|
|
assert trainer.state.finished, 'amp + ddp model failed to complete'
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
|
2019-12-03 13:01:04 +00:00
|
|
|
def test_cpu_model(tmpdir):
|
2019-12-04 11:48:53 +00:00
|
|
|
"""Make sure model trains on CPU."""
|
2019-10-23 10:10:13 +00:00
|
|
|
trainer_options = dict(
|
2021-02-11 14:32:07 +00:00
|
|
|
default_root_dir=tmpdir, progress_bar_refresh_rate=0, max_epochs=1, limit_train_batches=4, limit_val_batches=4
|
2021-01-08 21:13:12 +00:00
|
|
|
)
|
|
|
|
|
2021-02-11 14:32:07 +00:00
|
|
|
model = BoringModel()
|
2021-01-08 21:13:12 +00:00
|
|
|
tpipes.run_model_test(trainer_options, model, on_gpu=False)
|
|
|
|
|
|
|
|
|
|
|
|
def test_all_features_cpu_model(tmpdir):
|
|
|
|
"""Test each of the trainer options."""
|
|
|
|
trainer_options = dict(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
gradient_clip_val=1.0,
|
|
|
|
overfit_batches=0.20,
|
|
|
|
track_grad_norm=2,
|
|
|
|
progress_bar_refresh_rate=0,
|
|
|
|
accumulate_grad_batches=2,
|
|
|
|
max_epochs=1,
|
|
|
|
limit_train_batches=0.4,
|
2020-12-01 00:09:46 +00:00
|
|
|
limit_val_batches=0.4,
|
2019-10-23 10:10:13 +00:00
|
|
|
)
|
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
model = BoringModel()
|
|
|
|
|
|
|
|
tpipes.run_model_test(trainer_options, model, on_gpu=False, min_acc=0.01)
|
2019-10-23 10:10:13 +00:00
|
|
|
|
|
|
|
|
2021-07-01 21:16:14 +00:00
|
|
|
@pytest.mark.parametrize("n_hidden_states", [1, 2])
|
|
|
|
def test_tbptt_cpu_model(tmpdir, n_hidden_states):
|
2019-12-04 11:48:53 +00:00
|
|
|
"""Test truncated back propagation through time works."""
|
2019-10-31 10:45:28 +00:00
|
|
|
truncated_bptt_steps = 2
|
|
|
|
sequence_size = 30
|
|
|
|
batch_size = 30
|
|
|
|
|
|
|
|
x_seq = torch.rand(batch_size, sequence_size, 1)
|
|
|
|
y_seq_list = torch.rand(batch_size, sequence_size, 1).tolist()
|
|
|
|
|
|
|
|
class MockSeq2SeqDataset(torch.utils.data.Dataset):
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2019-10-31 10:45:28 +00:00
|
|
|
def __getitem__(self, i):
|
|
|
|
return x_seq, y_seq_list
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return 1
|
|
|
|
|
2021-01-07 10:50:08 +00:00
|
|
|
class BpttTestModel(BoringModel):
|
2021-02-06 11:07:26 +00:00
|
|
|
|
2021-07-01 21:16:14 +00:00
|
|
|
def __init__(self, batch_size, in_features, out_features, n_hidden_states, *args, **kwargs):
|
2020-05-24 22:59:08 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
2019-10-31 10:45:28 +00:00
|
|
|
self.test_hidden = None
|
2021-01-07 10:50:08 +00:00
|
|
|
self.batch_size = batch_size
|
|
|
|
self.layer = torch.nn.Linear(in_features, out_features)
|
2021-07-01 21:16:14 +00:00
|
|
|
self.n_hidden_states = n_hidden_states
|
2019-10-31 10:45:28 +00:00
|
|
|
|
|
|
|
def training_step(self, batch, batch_idx, hiddens):
|
|
|
|
assert hiddens == self.test_hidden, "Hidden state not persistent between tbptt steps"
|
2021-07-01 21:16:14 +00:00
|
|
|
if self.n_hidden_states == 1:
|
|
|
|
self.test_hidden = torch.rand(1)
|
|
|
|
else:
|
|
|
|
self.test_hidden = tuple([torch.rand(1)] * self.n_hidden_states)
|
2019-10-31 10:45:28 +00:00
|
|
|
|
|
|
|
x_tensor, y_list = batch
|
|
|
|
assert x_tensor.shape[1] == truncated_bptt_steps, "tbptt split Tensor failed"
|
|
|
|
|
|
|
|
y_tensor = torch.tensor(y_list, dtype=x_tensor.dtype)
|
|
|
|
assert y_tensor.shape[1] == truncated_bptt_steps, "tbptt split list failed"
|
|
|
|
|
2020-03-27 07:17:56 +00:00
|
|
|
pred = self(x_tensor.view(batch_size, truncated_bptt_steps))
|
2021-01-07 10:50:08 +00:00
|
|
|
loss_val = torch.nn.functional.mse_loss(pred, y_tensor.view(batch_size, truncated_bptt_steps))
|
2019-10-31 10:45:28 +00:00
|
|
|
return {
|
2021-01-07 10:50:08 +00:00
|
|
|
"loss": loss_val,
|
|
|
|
"hiddens": self.test_hidden,
|
2019-10-31 10:45:28 +00:00
|
|
|
}
|
|
|
|
|
2020-08-09 10:00:15 +00:00
|
|
|
def training_epoch_end(self, training_step_outputs):
|
|
|
|
training_step_outputs = training_step_outputs[0]
|
|
|
|
assert len(training_step_outputs) == (sequence_size / truncated_bptt_steps)
|
2021-01-07 10:50:08 +00:00
|
|
|
loss = torch.stack([x["loss"] for x in training_step_outputs]).mean()
|
|
|
|
self.log("train_loss", loss)
|
2020-08-09 10:00:15 +00:00
|
|
|
|
|
|
|
def train_dataloader(self):
|
|
|
|
return torch.utils.data.DataLoader(
|
|
|
|
dataset=MockSeq2SeqDataset(),
|
|
|
|
batch_size=batch_size,
|
|
|
|
shuffle=False,
|
|
|
|
sampler=None,
|
|
|
|
)
|
|
|
|
|
2021-07-01 21:16:14 +00:00
|
|
|
model = BpttTestModel(
|
|
|
|
batch_size=batch_size,
|
|
|
|
in_features=truncated_bptt_steps,
|
|
|
|
out_features=truncated_bptt_steps,
|
|
|
|
n_hidden_states=n_hidden_states
|
|
|
|
)
|
2020-08-19 23:08:46 +00:00
|
|
|
model.example_input_array = torch.randn(5, truncated_bptt_steps)
|
2020-08-09 10:00:15 +00:00
|
|
|
|
|
|
|
# fit model
|
|
|
|
trainer = Trainer(
|
|
|
|
default_root_dir=tmpdir,
|
|
|
|
max_epochs=1,
|
|
|
|
truncated_bptt_steps=truncated_bptt_steps,
|
|
|
|
limit_val_batches=0,
|
|
|
|
weights_summary=None,
|
|
|
|
)
|
2021-01-12 00:36:48 +00:00
|
|
|
trainer.fit(model)
|
2021-07-01 21:16:14 +00:00
|
|
|
assert trainer.state.finished, f"Training model with `{n_hidden_states}` hidden state failed with {trainer.state}"
|