lightning/pl_examples/basic_examples/lightning_module_template.py

273 lines
8.6 KiB
Python
Raw Normal View History

2019-08-04 18:19:23 +00:00
"""
Example template for defining a system
"""
import os
from argparse import ArgumentParser
2019-06-27 15:04:02 +00:00
from collections import OrderedDict
2019-06-27 15:04:02 +00:00
import torch
import torch.nn as nn
2019-06-27 15:04:02 +00:00
import torch.nn.functional as F
import torchvision.transforms as transforms
2019-06-27 15:04:02 +00:00
from torch import optim
2019-07-08 22:02:41 +00:00
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
2019-06-27 15:04:02 +00:00
from pytorch_lightning import _logger as log
resolving documentation warnings (#833) * add more underline * fix LightningMudule import error * remove unneeded blank line * escape asterisk to fix inline emphasis warning * add PULL_REQUEST_TEMPLATE.md * add __init__.py and import imagenet_example * fix duplicate label * add noindex option to fix duplicate object warnings * remove unexpected indent * refer explicit LightningModule * fix minor bug * refer EarlyStopping explicitly * restore exclude patterns * change the way how to refer class * remove unused import * update badges & drop Travis/Appveyor (#826) * drop Travis * drop Appveyor * update badges * fix missing PyPI images & CI badges (#853) * docs - anchor links (#848) * docs - add links * add desc. * add Greeting action (#843) * add Greeting action * Update greetings.yml Co-authored-by: William Falcon <waf2107@columbia.edu> * add pep8speaks (#842) * advanced profiler describe + cleaned up tests (#837) * add py36 compatibility * add test case to capture previous bug * clean up tests * clean up tests * Update lightning_module_template.py * Update lightning.py * respond lint issues * break long line * break more lines * checkout conflicting files from master * shorten url * checkout from upstream/master * remove trailing whitespaces * remove unused import LightningModule * fix sphinx bot warnings * Apply suggestions from code review just to trigger CI * Update .github/workflows/greetings.yml Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> Co-authored-by: William Falcon <waf2107@columbia.edu> Co-authored-by: Jeremy Jordan <13970565+jeremyjordan@users.noreply.github.com>
2020-02-27 21:07:51 +00:00
from pytorch_lightning.core import LightningModule
2019-06-27 15:04:02 +00:00
resolving documentation warnings (#833) * add more underline * fix LightningMudule import error * remove unneeded blank line * escape asterisk to fix inline emphasis warning * add PULL_REQUEST_TEMPLATE.md * add __init__.py and import imagenet_example * fix duplicate label * add noindex option to fix duplicate object warnings * remove unexpected indent * refer explicit LightningModule * fix minor bug * refer EarlyStopping explicitly * restore exclude patterns * change the way how to refer class * remove unused import * update badges & drop Travis/Appveyor (#826) * drop Travis * drop Appveyor * update badges * fix missing PyPI images & CI badges (#853) * docs - anchor links (#848) * docs - add links * add desc. * add Greeting action (#843) * add Greeting action * Update greetings.yml Co-authored-by: William Falcon <waf2107@columbia.edu> * add pep8speaks (#842) * advanced profiler describe + cleaned up tests (#837) * add py36 compatibility * add test case to capture previous bug * clean up tests * clean up tests * Update lightning_module_template.py * Update lightning.py * respond lint issues * break long line * break more lines * checkout conflicting files from master * shorten url * checkout from upstream/master * remove trailing whitespaces * remove unused import LightningModule * fix sphinx bot warnings * Apply suggestions from code review just to trigger CI * Update .github/workflows/greetings.yml Co-authored-by: Jirka Borovec <Borda@users.noreply.github.com> Co-authored-by: William Falcon <waf2107@columbia.edu> Co-authored-by: Jeremy Jordan <13970565+jeremyjordan@users.noreply.github.com>
2020-02-27 21:07:51 +00:00
class LightningTemplateModel(LightningModule):
2019-06-27 15:04:02 +00:00
"""
Sample model to show how to define a template.
Example:
>>> # define simple Net for MNIST dataset
>>> params = dict(
... drop_prob=0.2,
... batch_size=2,
... in_features=28 * 28,
... learning_rate=0.001 * 8,
... optimizer_name='adam',
... data_root='./datasets',
... out_features=10,
... hidden_dim=1000,
... )
>>> from argparse import Namespace
>>> hparams = Namespace(**params)
>>> model = LightningTemplateModel(hparams)
2019-06-27 15:04:02 +00:00
"""
def __init__(self, hparams):
"""
Pass in parsed HyperOptArgumentParser to the model
:param hparams:
"""
# init superclass
2019-07-25 16:04:20 +00:00
super(LightningTemplateModel, self).__init__()
2019-07-25 16:09:09 +00:00
self.hparams = hparams
2019-06-27 15:04:02 +00:00
self.batch_size = hparams.batch_size
2019-07-24 20:27:16 +00:00
# if you specify an example input, the summary will show input/output for each layer
self.example_input_array = torch.rand(5, 28 * 28)
2019-07-24 20:20:42 +00:00
2019-06-27 15:04:02 +00:00
# build model
self.__build_model()
# ---------------------
# MODEL SETUP
# ---------------------
def __build_model(self):
"""
Layout model
:return:
"""
2019-08-06 10:08:31 +00:00
self.c_d1 = nn.Linear(in_features=self.hparams.in_features,
out_features=self.hparams.hidden_dim)
2019-06-27 15:04:02 +00:00
self.c_d1_bn = nn.BatchNorm1d(self.hparams.hidden_dim)
self.c_d1_drop = nn.Dropout(self.hparams.drop_prob)
2019-08-06 10:08:31 +00:00
self.c_d2 = nn.Linear(in_features=self.hparams.hidden_dim,
out_features=self.hparams.out_features)
2019-06-27 15:04:02 +00:00
# ---------------------
# TRAINING
# ---------------------
def forward(self, x):
"""
No special modification required for lightning, define as you normally would
:param x:
:return:
"""
x = self.c_d1(x)
x = torch.tanh(x)
x = self.c_d1_bn(x)
x = self.c_d1_drop(x)
x = self.c_d2(x)
logits = F.log_softmax(x, dim=1)
return logits
def loss(self, labels, logits):
nll = F.nll_loss(logits, labels)
return nll
def training_step(self, batch, batch_idx):
2019-06-27 15:04:02 +00:00
"""
Lightning calls this inside the training loop
:param batch:
2019-06-27 15:04:02 +00:00
:return:
"""
# forward pass
x, y = batch
2019-06-27 15:04:02 +00:00
x = x.view(x.size(0), -1)
2019-07-24 17:55:20 +00:00
2019-06-27 15:04:02 +00:00
y_hat = self.forward(x)
# calculate loss
loss_val = self.loss(y, y_hat)
2019-07-24 18:04:17 +00:00
# in DP mode (default) make sure if result is scalar, there's another dim in the beginning
if self.trainer.use_dp or self.trainer.use_ddp2:
2019-07-24 18:04:17 +00:00
loss_val = loss_val.unsqueeze(0)
2019-10-07 21:23:25 +00:00
tqdm_dict = {'train_loss': loss_val}
2019-06-27 15:04:02 +00:00
output = OrderedDict({
2019-10-07 21:23:25 +00:00
'loss': loss_val,
'progress_bar': tqdm_dict,
2019-10-08 00:08:54 +00:00
'log': tqdm_dict
2019-06-27 15:04:02 +00:00
})
2019-07-18 16:11:59 +00:00
# can also return just a scalar instead of a dict (return loss_val)
return output
2019-06-27 15:04:02 +00:00
def validation_step(self, batch, batch_idx):
2019-06-27 15:04:02 +00:00
"""
Lightning calls this inside the validation loop
:param batch:
2019-06-27 15:04:02 +00:00
:return:
"""
x, y = batch
2019-06-27 15:04:02 +00:00
x = x.view(x.size(0), -1)
y_hat = self.forward(x)
loss_val = self.loss(y, y_hat)
# acc
labels_hat = torch.argmax(y_hat, dim=1)
val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0)
2019-07-24 13:29:46 +00:00
val_acc = torch.tensor(val_acc)
if self.on_gpu:
val_acc = val_acc.cuda(loss_val.device.index)
2019-06-27 15:04:02 +00:00
2019-07-24 18:04:17 +00:00
# in DP mode (default) make sure if result is scalar, there's another dim in the beginning
if self.trainer.use_dp or self.trainer.use_ddp2:
2019-07-24 18:04:17 +00:00
loss_val = loss_val.unsqueeze(0)
val_acc = val_acc.unsqueeze(0)
2019-06-27 15:04:02 +00:00
output = OrderedDict({
2019-07-24 18:04:17 +00:00
'val_loss': loss_val,
'val_acc': val_acc,
2019-06-27 15:04:02 +00:00
})
2019-07-18 16:11:59 +00:00
# can also return just a scalar instead of a dict (return loss_val)
return output
2019-06-27 15:04:02 +00:00
def validation_epoch_end(self, outputs):
2019-06-27 15:04:02 +00:00
"""
Called at the end of validation to aggregate outputs
:param outputs: list of individual outputs of each validation step
:return:
"""
2019-07-18 16:11:59 +00:00
# if returned a scalar from validation_step, outputs is a list of tensor scalars
# we return just the average in this case (if we want)
# return torch.stack(outputs).mean()
2019-07-18 16:09:25 +00:00
2019-06-27 15:04:02 +00:00
val_loss_mean = 0
val_acc_mean = 0
for output in outputs:
val_loss = output['val_loss']
# reduce manually when using dp
if self.trainer.use_dp or self.trainer.use_ddp2:
val_loss = torch.mean(val_loss)
val_loss_mean += val_loss
# reduce manually when using dp
val_acc = output['val_acc']
if self.trainer.use_dp or self.trainer.use_ddp2:
2019-08-17 15:11:07 +00:00
val_acc = torch.mean(val_acc)
2019-08-17 15:11:07 +00:00
val_acc_mean += val_acc
2019-06-27 15:04:02 +00:00
val_loss_mean /= len(outputs)
val_acc_mean /= len(outputs)
tqdm_dict = {'val_loss': val_loss_mean, 'val_acc': val_acc_mean}
2019-10-16 13:24:02 +00:00
result = {'progress_bar': tqdm_dict, 'log': tqdm_dict, 'val_loss': val_loss_mean}
return result
2019-06-27 15:04:02 +00:00
# ---------------------
# TRAINING SETUP
# ---------------------
def configure_optimizers(self):
"""
return whatever optimizers we want here
:return: list of optimizers
"""
2019-06-28 17:53:00 +00:00
optimizer = optim.Adam(self.parameters(), lr=self.hparams.learning_rate)
2019-07-24 05:12:45 +00:00
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=10)
return [optimizer], [scheduler]
2019-06-27 15:04:02 +00:00
def __dataloader(self, train):
# this is neede when you want some info about dataset before binding to trainer
self.prepare_data()
2019-06-27 15:04:02 +00:00
# init data generators
2019-08-06 10:08:31 +00:00
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (1.0,))])
dataset = MNIST(root=self.hparams.data_root, train=train,
Clean up dataloader logic (#926) * added get dataloaders directly using a getter * deleted decorator * added prepare_data hook * refactored dataloader init * refactored dataloader init * added dataloader reset flag and main loop * added dataloader reset flag and main loop * added dataloader reset flag and main loop * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixes #909 * fixes #909 * bug fix * Fixes #902
2020-02-25 03:23:25 +00:00
transform=transform, download=False)
2019-06-27 15:04:02 +00:00
# when using multi-node (ddp) we need to add the datasampler
2019-07-08 23:42:53 +00:00
batch_size = self.hparams.batch_size
2019-07-08 22:02:41 +00:00
loader = DataLoader(
2019-06-27 15:04:02 +00:00
dataset=dataset,
2019-07-08 23:42:53 +00:00
batch_size=batch_size,
num_workers=0
2019-06-27 15:04:02 +00:00
)
return loader
Clean up dataloader logic (#926) * added get dataloaders directly using a getter * deleted decorator * added prepare_data hook * refactored dataloader init * refactored dataloader init * added dataloader reset flag and main loop * added dataloader reset flag and main loop * added dataloader reset flag and main loop * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixes #909 * fixes #909 * bug fix * Fixes #902
2020-02-25 03:23:25 +00:00
def prepare_data(self):
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (1.0,))])
_ = MNIST(root=self.hparams.data_root, train=True,
transform=transform, download=True)
Clean up dataloader logic (#926) * added get dataloaders directly using a getter * deleted decorator * added prepare_data hook * refactored dataloader init * refactored dataloader init * added dataloader reset flag and main loop * added dataloader reset flag and main loop * added dataloader reset flag and main loop * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * made changes * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed bad loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixed error in .fit with loaders * fixes #909 * fixes #909 * bug fix * Fixes #902
2020-02-25 03:23:25 +00:00
def train_dataloader(self):
log.info('Training data loader called.')
return self.__dataloader(train=True)
2019-06-27 15:04:02 +00:00
def val_dataloader(self):
log.info('Validation data loader called.')
return self.__dataloader(train=False)
2019-06-27 15:04:02 +00:00
def test_dataloader(self):
log.info('Test data loader called.')
return self.__dataloader(train=False)
2019-06-27 15:04:02 +00:00
@staticmethod
def add_model_specific_args(parent_parser, root_dir): # pragma: no-cover
2019-06-27 15:04:02 +00:00
"""
Parameters you define here will be available to your model through self.hparams
:param parent_parser:
:param root_dir:
:return:
"""
parser = ArgumentParser(parents=[parent_parser])
2019-06-27 15:04:02 +00:00
# param overwrites
# parser.set_defaults(gradient_clip_val=5.0)
2019-06-27 15:04:02 +00:00
# network params
2019-08-05 21:57:39 +00:00
parser.add_argument('--in_features', default=28 * 28, type=int)
2019-07-08 14:57:34 +00:00
parser.add_argument('--out_features', default=10, type=int)
2019-08-05 21:57:39 +00:00
# use 500 for CPU, 50000 for GPU to see speed difference
parser.add_argument('--hidden_dim', default=50000, type=int)
parser.add_argument('--drop_prob', default=0.2, type=float)
parser.add_argument('--learning_rate', default=0.001, type=float)
2019-06-27 15:04:02 +00:00
# data
parser.add_argument('--data_root', default=os.path.join(root_dir, 'mnist'), type=str)
# training params (opt)
2020-02-25 14:46:01 +00:00
parser.add_argument('--epochs', default=20, type=int)
parser.add_argument('--optimizer_name', default='adam', type=str)
parser.add_argument('--batch_size', default=64, type=int)
2019-06-27 15:04:02 +00:00
return parser