2020-12-17 09:21:00 +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.
|
2019-08-14 12:41:32 +00:00
|
|
|
"""
|
2019-10-18 22:26:31 +00:00
|
|
|
To run this template just do:
|
2020-04-03 21:57:34 +00:00
|
|
|
python generative_adversarial_net.py
|
2019-08-14 12:41:32 +00:00
|
|
|
|
2020-04-03 19:01:40 +00:00
|
|
|
After a few epochs, launch TensorBoard to see the images being generated at every batch:
|
2019-08-14 12:41:32 +00:00
|
|
|
|
|
|
|
tensorboard --logdir default
|
|
|
|
"""
|
2020-12-29 08:19:02 +00:00
|
|
|
import os
|
2021-01-03 22:13:22 +00:00
|
|
|
from argparse import ArgumentParser, Namespace
|
2019-08-14 12:38:49 +00:00
|
|
|
|
2019-10-22 08:32:40 +00:00
|
|
|
import numpy as np
|
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
2020-10-21 16:07:18 +00:00
|
|
|
import torch.nn.functional as F # noqa
|
2020-12-29 08:19:02 +00:00
|
|
|
import torchvision
|
|
|
|
import torchvision.transforms as transforms
|
2021-01-03 22:13:22 +00:00
|
|
|
from torch.utils.data import DataLoader
|
|
|
|
from torchvision.datasets import MNIST
|
2019-08-14 12:38:49 +00:00
|
|
|
|
2020-12-17 09:21:00 +00:00
|
|
|
from pl_examples import cli_lightning_logo
|
2020-12-29 08:19:02 +00:00
|
|
|
from pytorch_lightning.core import LightningDataModule, LightningModule
|
2020-02-27 21:07:51 +00:00
|
|
|
from pytorch_lightning.trainer import Trainer
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Generator(nn.Module):
|
2020-12-17 10:13:48 +00:00
|
|
|
"""
|
|
|
|
>>> Generator(img_shape=(1, 8, 8)) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
|
|
|
Generator(
|
|
|
|
(model): Sequential(...)
|
|
|
|
)
|
|
|
|
"""
|
2021-01-30 10:17:12 +00:00
|
|
|
|
2020-12-17 10:13:48 +00:00
|
|
|
def __init__(self, latent_dim: int = 100, img_shape: tuple = (1, 28, 28)):
|
2020-03-27 12:36:50 +00:00
|
|
|
super().__init__()
|
2019-08-14 12:38:49 +00:00
|
|
|
self.img_shape = img_shape
|
|
|
|
|
|
|
|
def block(in_feat, out_feat, normalize=True):
|
|
|
|
layers = [nn.Linear(in_feat, out_feat)]
|
|
|
|
if normalize:
|
|
|
|
layers.append(nn.BatchNorm1d(out_feat, 0.8))
|
|
|
|
layers.append(nn.LeakyReLU(0.2, inplace=True))
|
|
|
|
return layers
|
|
|
|
|
|
|
|
self.model = nn.Sequential(
|
|
|
|
*block(latent_dim, 128, normalize=False),
|
|
|
|
*block(128, 256),
|
|
|
|
*block(256, 512),
|
|
|
|
*block(512, 1024),
|
|
|
|
nn.Linear(1024, int(np.prod(img_shape))),
|
2021-01-30 10:17:12 +00:00
|
|
|
nn.Tanh(),
|
2019-08-14 12:38:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
def forward(self, z):
|
|
|
|
img = self.model(z)
|
|
|
|
img = img.view(img.size(0), *self.img_shape)
|
|
|
|
return img
|
|
|
|
|
|
|
|
|
|
|
|
class Discriminator(nn.Module):
|
2020-12-17 10:13:48 +00:00
|
|
|
"""
|
|
|
|
>>> Discriminator(img_shape=(1, 28, 28)) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
|
|
|
Discriminator(
|
|
|
|
(model): Sequential(...)
|
|
|
|
)
|
|
|
|
"""
|
2021-01-30 10:17:12 +00:00
|
|
|
|
2019-08-14 12:38:49 +00:00
|
|
|
def __init__(self, img_shape):
|
2020-03-27 12:36:50 +00:00
|
|
|
super().__init__()
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
self.model = nn.Sequential(
|
|
|
|
nn.Linear(int(np.prod(img_shape)), 512),
|
|
|
|
nn.LeakyReLU(0.2, inplace=True),
|
|
|
|
nn.Linear(512, 256),
|
|
|
|
nn.LeakyReLU(0.2, inplace=True),
|
|
|
|
nn.Linear(256, 1),
|
|
|
|
)
|
|
|
|
|
|
|
|
def forward(self, img):
|
|
|
|
img_flat = img.view(img.size(0), -1)
|
|
|
|
validity = self.model(img_flat)
|
|
|
|
|
|
|
|
return validity
|
|
|
|
|
|
|
|
|
2020-02-27 21:07:51 +00:00
|
|
|
class GAN(LightningModule):
|
2020-12-17 10:13:48 +00:00
|
|
|
"""
|
|
|
|
>>> GAN(img_shape=(1, 8, 8)) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
|
|
|
GAN(
|
|
|
|
(generator): Generator(
|
|
|
|
(model): Sequential(...)
|
|
|
|
)
|
|
|
|
(discriminator): Discriminator(
|
|
|
|
(model): Sequential(...)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
"""
|
2021-01-30 10:17:12 +00:00
|
|
|
|
2020-12-17 10:13:48 +00:00
|
|
|
def __init__(
|
2021-01-30 10:17:12 +00:00
|
|
|
self,
|
|
|
|
img_shape: tuple = (1, 28, 28),
|
|
|
|
lr: float = 0.0002,
|
|
|
|
b1: float = 0.5,
|
|
|
|
b2: float = 0.999,
|
|
|
|
latent_dim: int = 100,
|
2020-12-17 10:13:48 +00:00
|
|
|
):
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
self.save_hyperparameters()
|
|
|
|
|
|
|
|
# networks
|
|
|
|
self.generator = Generator(latent_dim=self.hparams.latent_dim, img_shape=img_shape)
|
|
|
|
self.discriminator = Discriminator(img_shape=img_shape)
|
|
|
|
|
|
|
|
self.validation_z = torch.randn(8, self.hparams.latent_dim)
|
|
|
|
|
|
|
|
self.example_input_array = torch.zeros(2, self.hparams.latent_dim)
|
|
|
|
|
2020-10-21 16:07:18 +00:00
|
|
|
@staticmethod
|
|
|
|
def add_argparse_args(parent_parser: ArgumentParser):
|
|
|
|
parser = ArgumentParser(parents=[parent_parser], add_help=False)
|
|
|
|
parser.add_argument("--lr", type=float, default=0.0002, help="adam: learning rate")
|
2021-01-30 10:17:12 +00:00
|
|
|
parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient")
|
|
|
|
parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of second order momentum of gradient")
|
|
|
|
parser.add_argument("--latent_dim", type=int, default=100, help="dimensionality of the latent space")
|
2020-10-21 16:07:18 +00:00
|
|
|
|
|
|
|
return parser
|
|
|
|
|
2019-08-14 12:38:49 +00:00
|
|
|
def forward(self, z):
|
|
|
|
return self.generator(z)
|
|
|
|
|
2020-10-21 16:07:18 +00:00
|
|
|
@staticmethod
|
|
|
|
def adversarial_loss(y_hat, y):
|
|
|
|
return F.binary_cross_entropy_with_logits(y_hat, y)
|
2019-08-14 12:38:49 +00:00
|
|
|
|
2019-12-04 11:57:10 +00:00
|
|
|
def training_step(self, batch, batch_idx, optimizer_idx):
|
2019-08-14 12:38:49 +00:00
|
|
|
imgs, _ = batch
|
2020-05-31 12:31:21 +00:00
|
|
|
|
|
|
|
# sample noise
|
2020-10-21 16:07:18 +00:00
|
|
|
z = torch.randn(imgs.shape[0], self.hparams.latent_dim)
|
2020-05-31 12:31:21 +00:00
|
|
|
z = z.type_as(imgs)
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
# train generator
|
2019-12-04 11:57:10 +00:00
|
|
|
if optimizer_idx == 0:
|
2019-08-14 12:38:49 +00:00
|
|
|
# ground truth result (ie: all fake)
|
2019-12-04 13:28:46 +00:00
|
|
|
# put on GPU because we created this tensor inside training_loop
|
2019-08-14 12:38:49 +00:00
|
|
|
valid = torch.ones(imgs.size(0), 1)
|
2020-04-02 15:46:20 +00:00
|
|
|
valid = valid.type_as(imgs)
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
# adversarial loss is binary cross-entropy
|
2020-05-31 12:31:21 +00:00
|
|
|
g_loss = self.adversarial_loss(self.discriminator(self(z)), valid)
|
2019-10-14 10:56:33 +00:00
|
|
|
tqdm_dict = {'g_loss': g_loss}
|
2020-09-30 12:31:16 +00:00
|
|
|
self.log_dict(tqdm_dict)
|
|
|
|
return g_loss
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
# train discriminator
|
2019-12-04 11:57:10 +00:00
|
|
|
if optimizer_idx == 1:
|
2019-08-14 12:38:49 +00:00
|
|
|
# Measure discriminator's ability to classify real from generated samples
|
|
|
|
|
|
|
|
# how well can it label as real?
|
|
|
|
valid = torch.ones(imgs.size(0), 1)
|
2020-04-02 15:46:20 +00:00
|
|
|
valid = valid.type_as(imgs)
|
2019-12-04 13:28:46 +00:00
|
|
|
|
2019-08-14 12:38:49 +00:00
|
|
|
real_loss = self.adversarial_loss(self.discriminator(imgs), valid)
|
|
|
|
|
|
|
|
# how well can it label as fake?
|
|
|
|
fake = torch.zeros(imgs.size(0), 1)
|
2020-05-31 12:31:21 +00:00
|
|
|
fake = fake.type_as(imgs)
|
2019-12-04 13:28:46 +00:00
|
|
|
|
2021-01-30 10:17:12 +00:00
|
|
|
fake_loss = self.adversarial_loss(self.discriminator(self(z).detach()), fake)
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
# discriminator loss is the average of these
|
|
|
|
d_loss = (real_loss + fake_loss) / 2
|
2019-10-14 10:56:33 +00:00
|
|
|
tqdm_dict = {'d_loss': d_loss}
|
2020-09-30 12:31:16 +00:00
|
|
|
self.log_dict(tqdm_dict)
|
2020-08-25 15:05:03 +00:00
|
|
|
|
2020-09-30 12:31:16 +00:00
|
|
|
return d_loss
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
def configure_optimizers(self):
|
2020-10-21 16:07:18 +00:00
|
|
|
lr = self.hparams.lr
|
|
|
|
b1 = self.hparams.b1
|
|
|
|
b2 = self.hparams.b2
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
opt_g = torch.optim.Adam(self.generator.parameters(), lr=lr, betas=(b1, b2))
|
|
|
|
opt_d = torch.optim.Adam(self.discriminator.parameters(), lr=lr, betas=(b1, b2))
|
|
|
|
return [opt_g, opt_d], []
|
|
|
|
|
2019-10-14 10:56:33 +00:00
|
|
|
def on_epoch_end(self):
|
2020-05-31 12:31:21 +00:00
|
|
|
z = self.validation_z.type_as(self.generator.model[0].weight)
|
2019-10-14 10:56:33 +00:00
|
|
|
|
|
|
|
# log sampled images
|
2020-03-27 07:17:56 +00:00
|
|
|
sample_imgs = self(z)
|
2019-10-14 10:56:33 +00:00
|
|
|
grid = torchvision.utils.make_grid(sample_imgs)
|
2020-05-12 03:32:44 +00:00
|
|
|
self.logger.experiment.add_image('generated_images', grid, self.current_epoch)
|
2019-10-14 10:56:33 +00:00
|
|
|
|
|
|
|
|
2020-10-21 16:07:18 +00:00
|
|
|
class MNISTDataModule(LightningDataModule):
|
2020-12-17 10:13:48 +00:00
|
|
|
"""
|
|
|
|
>>> MNISTDataModule() # doctest: +ELLIPSIS
|
|
|
|
<...generative_adversarial_net.MNISTDataModule object at ...>
|
|
|
|
"""
|
2021-01-30 10:17:12 +00:00
|
|
|
|
2020-10-21 16:07:18 +00:00
|
|
|
def __init__(self, batch_size: int = 64, data_path: str = os.getcwd(), num_workers: int = 4):
|
|
|
|
super().__init__()
|
|
|
|
self.batch_size = batch_size
|
|
|
|
self.data_path = data_path
|
|
|
|
self.num_workers = num_workers
|
|
|
|
|
2021-01-30 10:17:12 +00:00
|
|
|
self.transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])
|
2020-10-21 16:07:18 +00:00
|
|
|
self.dims = (1, 28, 28)
|
|
|
|
|
|
|
|
def prepare_data(self, stage=None):
|
|
|
|
# Use this method to do things that might write to disk or that need to be done only from a single GPU
|
|
|
|
# in distributed settings. Like downloading the dataset for the first time.
|
|
|
|
MNIST(self.data_path, train=True, download=True, transform=transforms.ToTensor())
|
|
|
|
|
|
|
|
def setup(self, stage=None):
|
|
|
|
# There are also data operations you might want to perform on every GPU, such as applying transforms
|
|
|
|
# defined explicitly in your datamodule or assigned in init.
|
|
|
|
self.mnist_train = MNIST(self.data_path, train=True, transform=self.transform)
|
|
|
|
|
|
|
|
def train_dataloader(self):
|
|
|
|
return DataLoader(self.mnist_train, batch_size=self.batch_size, num_workers=self.num_workers)
|
|
|
|
|
|
|
|
|
2020-06-01 15:38:52 +00:00
|
|
|
def main(args: Namespace) -> None:
|
2019-10-14 10:56:33 +00:00
|
|
|
# ------------------------
|
|
|
|
# 1 INIT LIGHTNING MODEL
|
|
|
|
# ------------------------
|
2021-01-28 00:56:30 +00:00
|
|
|
model = GAN(lr=args.lr, b1=args.b1, b2=args.b2, latent_dim=args.latent_dim)
|
2019-08-14 12:38:49 +00:00
|
|
|
|
2019-10-14 10:56:33 +00:00
|
|
|
# ------------------------
|
|
|
|
# 2 INIT TRAINER
|
|
|
|
# ------------------------
|
2020-05-31 12:31:21 +00:00
|
|
|
# If use distubuted training PyTorch recommends to use DistributedDataParallel.
|
|
|
|
# See: https://pytorch.org/docs/stable/nn.html#torch.nn.DataParallel
|
2020-10-21 16:07:18 +00:00
|
|
|
dm = MNISTDataModule.from_argparse_args(args)
|
|
|
|
trainer = Trainer.from_argparse_args(args)
|
2019-10-14 10:56:33 +00:00
|
|
|
|
|
|
|
# ------------------------
|
|
|
|
# 3 START TRAINING
|
|
|
|
# ------------------------
|
2020-10-21 16:07:18 +00:00
|
|
|
trainer.fit(model, dm)
|
2019-08-14 12:38:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2020-12-17 09:21:00 +00:00
|
|
|
cli_lightning_logo()
|
2019-08-14 12:38:49 +00:00
|
|
|
parser = ArgumentParser()
|
2020-10-21 16:07:18 +00:00
|
|
|
|
|
|
|
# Add program level args, if any.
|
|
|
|
# ------------------------
|
|
|
|
# Add LightningDataLoader args
|
|
|
|
parser = MNISTDataModule.add_argparse_args(parser)
|
|
|
|
# Add model specific args
|
|
|
|
parser = GAN.add_argparse_args(parser)
|
|
|
|
# Add trainer args
|
|
|
|
parser = Trainer.add_argparse_args(parser)
|
|
|
|
# Parse all arguments
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
main(args)
|