Art generation with VQGAN + CLIP in Docker, with a simple web UI for anyone with a GPU. A simplified and expanded take on Kevin Costa's work.
aiai-artclipdockerdocker-composegpuhandcodedimagenetpythonpytorchtorchtorchvisionvqganvqgan-clip
1import torch
2import torch.nn as nn
3
4from core.taming.utils import hinge_d_loss, vanilla_d_loss, adopt_weight, weights_init
5
6from core.taming.modules.discriminator import NLayerDiscriminator
7
8from core.taming.modules.losses import LPIPS
9
10
11class DummyLoss(nn.Module):
12 def __init__(self):
13 super().__init__()
14
15
16class VQLPIPSWithDiscriminator(nn.Module):
17 def __init__(self, disc_start, codebook_weight=1.0, pixelloss_weight=1.0,
18 disc_num_layers=3, disc_in_channels=3, disc_factor=1.0, disc_weight=1.0,
19 perceptual_weight=1.0, use_actnorm=False, disc_conditional=False,
20 disc_ndf=64, disc_loss="hinge", model_dir=None):
21 super().__init__()
22 assert disc_loss in ["hinge", "vanilla"]
23 self.codebook_weight = codebook_weight
24 self.pixel_weight = pixelloss_weight
25 self.perceptual_loss = LPIPS(model_dir=model_dir).eval()
26 self.perceptual_weight = perceptual_weight
27
28 self.discriminator = NLayerDiscriminator(input_nc=disc_in_channels,
29 n_layers=disc_num_layers,
30 use_actnorm=use_actnorm,
31 ndf=disc_ndf
32 ).apply(weights_init)
33 self.discriminator_iter_start = disc_start
34 if disc_loss == "hinge":
35 self.disc_loss = hinge_d_loss
36 elif disc_loss == "vanilla":
37 self.disc_loss = vanilla_d_loss
38 else:
39 raise ValueError(f"Unknown GAN loss '{disc_loss}'.")
40 print(f"VQLPIPSWithDiscriminator running with {disc_loss} loss.")
41 self.disc_factor = disc_factor
42 self.discriminator_weight = disc_weight
43 self.disc_conditional = disc_conditional
44
45 def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
46 if last_layer is not None:
47 nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]
48 g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]
49 else:
50 nll_grads = torch.autograd.grad(nll_loss, self.last_layer[0], retain_graph=True)[0]
51 g_grads = torch.autograd.grad(g_loss, self.last_layer[0], retain_graph=True)[0]
52
53 d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
54 d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
55 d_weight = d_weight * self.discriminator_weight
56 return d_weight
57
58 def forward(self, codebook_loss, inputs, reconstructions, optimizer_idx,
59 global_step, last_layer=None, cond=None, split="train"):
60 rec_loss = torch.abs(inputs.contiguous() - reconstructions.contiguous())
61 if self.perceptual_weight > 0:
62 p_loss = self.perceptual_loss(inputs.contiguous(), reconstructions.contiguous())
63 rec_loss = rec_loss + self.perceptual_weight * p_loss
64 else:
65 p_loss = torch.tensor([0.0])
66
67 nll_loss = rec_loss
68 nll_loss = torch.mean(nll_loss)
69
70 # now the GAN part
71 if optimizer_idx == 0:
72 # generator update
73 if cond is None:
74 assert not self.disc_conditional
75 logits_fake = self.discriminator(reconstructions.contiguous())
76 else:
77 assert self.disc_conditional
78 logits_fake = self.discriminator(torch.cat((reconstructions.contiguous(), cond), dim=1))
79 g_loss = -torch.mean(logits_fake)
80
81 try:
82 d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer=last_layer)
83 except RuntimeError:
84 assert not self.training
85 d_weight = torch.tensor(0.0)
86
87 disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)
88 loss = nll_loss + d_weight * disc_factor * g_loss + self.codebook_weight * codebook_loss.mean()
89
90 return loss
91
92 if optimizer_idx == 1:
93 # second pass for discriminator update
94 if cond is None:
95 logits_real = self.discriminator(inputs.contiguous().detach())
96 logits_fake = self.discriminator(reconstructions.contiguous().detach())
97 else:
98 logits_real = self.discriminator(torch.cat((inputs.contiguous().detach(), cond), dim=1))
99 logits_fake = self.discriminator(torch.cat((reconstructions.contiguous().detach(), cond), dim=1))
100
101 disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.discriminator_iter_start)
102 d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
103
104 return d_loss