Files
Machine-Learning-Collection/ML/Pytorch/GANs/ProGAN/train.py

178 lines
6.1 KiB
Python
Raw Normal View History

2021-01-30 21:49:15 +01:00
""" Training of ProGAN using WGAN-GP loss"""
import torch
2021-03-17 22:48:26 +01:00
import torch.nn as nn
2021-01-30 21:49:15 +01:00
import torch.optim as optim
2021-03-17 22:48:26 +01:00
import torchvision
2021-01-30 21:49:15 +01:00
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
2021-03-17 22:48:26 +01:00
from utils import gradient_penalty, plot_to_tensorboard, save_checkpoint, load_checkpoint
2021-01-30 21:49:15 +01:00
from model import Discriminator, Generator
from math import log2
from tqdm import tqdm
2021-03-17 22:48:26 +01:00
import time
2021-03-11 15:50:44 +01:00
import config
2021-01-30 21:49:15 +01:00
torch.backends.cudnn.benchmarks = True
2021-03-11 15:50:44 +01:00
2021-01-30 21:49:15 +01:00
def get_loader(image_size):
transform = transforms.Compose(
[
transforms.Resize((image_size, image_size)),
transforms.ToTensor(),
transforms.Normalize(
2021-03-11 15:50:44 +01:00
[0.5 for _ in range(config.CHANNELS_IMG)],
[0.5 for _ in range(config.CHANNELS_IMG)],
2021-01-30 21:49:15 +01:00
),
]
)
2021-03-17 22:48:26 +01:00
batch_size = config.BATCH_SIZES[int(log2(image_size/4))]
dataset = datasets.ImageFolder(root="celeb_dataset", transform=transform)
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=config.NUM_WORKERS, pin_memory=True)
2021-01-30 21:49:15 +01:00
return loader, dataset
def train_fn(
critic,
gen,
loader,
dataset,
step,
alpha,
opt_critic,
opt_gen,
tensorboard_step,
writer,
2021-03-11 15:50:44 +01:00
scaler_gen,
scaler_critic,
2021-01-30 21:49:15 +01:00
):
2021-03-17 22:48:26 +01:00
start = time.time()
total_time = 0
2021-03-11 15:50:44 +01:00
loop = tqdm(loader, leave=True)
2021-03-17 22:48:26 +01:00
losses_critic = []
2021-03-11 15:50:44 +01:00
for batch_idx, (real, _) in enumerate(loop):
real = real.to(config.DEVICE)
2021-01-30 21:49:15 +01:00
cur_batch_size = real.shape[0]
2021-03-17 22:48:26 +01:00
model_start = time.time()
for _ in range(4):
# Train Critic: max E[critic(real)] - E[critic(fake)]
# which is equivalent to minimizing the negative of the expression
for _ in range(config.CRITIC_ITERATIONS):
noise = torch.randn(cur_batch_size, config.Z_DIM, 1, 1).to(config.DEVICE)
with torch.cuda.amp.autocast():
fake = gen(noise, alpha, step)
critic_real = critic(real, alpha, step).reshape(-1)
critic_fake = critic(fake, alpha, step).reshape(-1)
gp = gradient_penalty(critic, real, fake, alpha, step, device=config.DEVICE)
loss_critic = (
-(torch.mean(critic_real) - torch.mean(critic_fake))
+ config.LAMBDA_GP * gp
)
losses_critic.append(loss_critic.item())
opt_critic.zero_grad()
scaler_critic.scale(loss_critic).backward()
scaler_critic.step(opt_critic)
scaler_critic.update()
#loss_critic.backward(retain_graph=True)
#opt_critic.step()
# Train Generator: max E[critic(gen_fake)] <-> min -E[critic(gen_fake)]
with torch.cuda.amp.autocast():
fake = gen(noise, alpha, step)
gen_fake = critic(fake, alpha, step).reshape(-1)
loss_gen = -torch.mean(gen_fake)
opt_gen.zero_grad()
scaler_gen.scale(loss_gen).backward()
scaler_gen.step(opt_gen)
scaler_gen.update()
#gen.zero_grad()
#loss_gen.backward()
#opt_gen.step()
2021-01-30 21:49:15 +01:00
# Update alpha and ensure less than 1
alpha += cur_batch_size / (
2021-03-17 22:48:26 +01:00
(config.PROGRESSIVE_EPOCHS[step]*0.5) * len(dataset) # - step
2021-01-30 21:49:15 +01:00
)
alpha = min(alpha, 1)
2021-03-17 22:48:26 +01:00
total_time += time.time()-model_start
2021-01-30 21:49:15 +01:00
2021-03-17 22:48:26 +01:00
if batch_idx % 10 == 0:
print(alpha)
2021-01-30 21:49:15 +01:00
with torch.no_grad():
2021-03-17 22:48:26 +01:00
fixed_fakes = gen(config.FIXED_NOISE, alpha, step)
2021-01-30 21:49:15 +01:00
plot_to_tensorboard(
2021-03-17 22:48:26 +01:00
writer, loss_critic, loss_gen, real, fixed_fakes, tensorboard_step
2021-01-30 21:49:15 +01:00
)
tensorboard_step += 1
2021-03-17 22:48:26 +01:00
mean_loss = sum(losses_critic) / len(losses_critic)
loop.set_postfix(loss=mean_loss)
2021-03-11 15:50:44 +01:00
2021-03-17 22:48:26 +01:00
print(f'Fraction spent on model training: {total_time/(time.time()-start)}')
2021-01-30 21:49:15 +01:00
return tensorboard_step, alpha
def main():
# initialize gen and disc, note: discriminator should be called critic,
# according to WGAN paper (since it no longer outputs between [0, 1])
2021-03-17 22:48:26 +01:00
gen = Generator(config.Z_DIM, config.IN_CHANNELS, img_size=config.IMAGE_SIZE, img_channels=config.CHANNELS_IMG).to(config.DEVICE)
critic = Discriminator(config.IMAGE_SIZE, config.Z_DIM, config.IN_CHANNELS, img_channels=config.CHANNELS_IMG).to(config.DEVICE)
# initializate optimizer
2021-03-11 15:50:44 +01:00
opt_gen = optim.Adam(gen.parameters(), lr=config.LEARNING_RATE, betas=(0.0, 0.99))
2021-03-17 22:48:26 +01:00
opt_critic = optim.Adam(critic.parameters(), lr=config.LEARNING_RATE, betas=(0.0, 0.99))
2021-03-11 15:50:44 +01:00
scaler_critic = torch.cuda.amp.GradScaler()
scaler_gen = torch.cuda.amp.GradScaler()
2021-01-30 21:49:15 +01:00
# for tensorboard plotting
2021-03-17 22:48:26 +01:00
writer = SummaryWriter(f"logs/gan")
2021-03-11 15:50:44 +01:00
if config.LOAD_MODEL:
load_checkpoint(
config.CHECKPOINT_GEN, gen, opt_gen, config.LEARNING_RATE,
)
load_checkpoint(
config.CHECKPOINT_CRITIC, critic, opt_critic, config.LEARNING_RATE,
)
2021-01-30 21:49:15 +01:00
gen.train()
critic.train()
tensorboard_step = 0
2021-03-17 22:48:26 +01:00
step = int(log2(config.START_TRAIN_AT_IMG_SIZE/4))
2021-01-30 21:49:15 +01:00
2021-03-17 22:48:26 +01:00
for num_epochs in config.PROGRESSIVE_EPOCHS[step:]:
alpha = 0.01
loader, dataset = get_loader(4 * 2 ** step) # 4->0, 8->1, 16->2, 32->3
print(f"Current image size: {4*2**step}")
2021-01-30 21:49:15 +01:00
for epoch in range(num_epochs):
print(f"Epoch [{epoch+1}/{num_epochs}]")
tensorboard_step, alpha = train_fn(
critic,
gen,
loader,
dataset,
step,
alpha,
opt_critic,
opt_gen,
tensorboard_step,
writer,
2021-03-11 15:50:44 +01:00
scaler_gen,
scaler_critic,
2021-01-30 21:49:15 +01:00
)
2021-03-11 15:50:44 +01:00
if config.SAVE_MODEL:
save_checkpoint(gen, opt_gen, filename=config.CHECKPOINT_GEN)
save_checkpoint(critic, opt_critic, filename=config.CHECKPOINT_CRITIC)
2021-03-17 22:48:26 +01:00
step += 1
2021-01-30 21:49:15 +01:00
if __name__ == "__main__":
2021-03-17 22:48:26 +01:00
main()