From a3c7617d0b5770edf6030502e4eac477a7218820 Mon Sep 17 00:00:00 2001 From: Francois Fleuret Date: Sat, 13 Aug 2022 23:08:35 +0200 Subject: [PATCH] Update. --- minidiffusion.py | 215 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 146 insertions(+), 69 deletions(-) diff --git a/minidiffusion.py b/minidiffusion.py index 075eb82..2c54d19 100755 --- a/minidiffusion.py +++ b/minidiffusion.py @@ -9,7 +9,7 @@ import math, argparse import matplotlib.pyplot as plt -import torch +import torch, torchvision from torch import nn device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') @@ -18,31 +18,51 @@ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def sample_gaussian_mixture(nb): p, std = 0.3, 0.2 - result = torch.empty(nb, 1, device = device).normal_(0, std) - result = result + torch.sign(torch.rand(result.size(), device = device) - p) / 2 + result = torch.empty(nb, 1).normal_(0, std) + result = result + torch.sign(torch.rand(result.size()) - p) / 2 return result -def sample_arc(nb): - theta = torch.rand(nb, device = device) * math.pi - rho = torch.rand(nb, device = device) * 0.1 + 0.7 - result = torch.empty(nb, 2, device = device) - result[:, 0] = theta.cos() * rho - result[:, 1] = theta.sin() * rho +def sample_two_discs(nb): + a = torch.rand(nb) * math.pi * 2 + b = torch.rand(nb).sqrt() + q = (torch.rand(nb) <= 0.5).long() + b = b * (0.3 + 0.2 * q) + result = torch.empty(nb, 2) + result[:, 0] = a.cos() * b - 0.5 + q + result[:, 1] = a.sin() * b - 0.5 + q + return result + +def sample_disc_grid(nb): + a = torch.rand(nb) * math.pi * 2 + b = torch.rand(nb).sqrt() + q = torch.randint(5, (nb,)) / 2.5 - 2 / 2.5 + r = torch.randint(5, (nb,)) / 2.5 - 2 / 2.5 + b = b * 0.1 + result = torch.empty(nb, 2) + result[:, 0] = a.cos() * b + q + result[:, 1] = a.sin() * b + r return result def sample_spiral(nb): - u = torch.rand(nb, device = device) - rho = u * 0.65 + 0.25 + torch.rand(nb, device = device) * 0.15 + u = torch.rand(nb) + rho = u * 0.65 + 0.25 + torch.rand(nb) * 0.15 theta = u * math.pi * 3 - result = torch.empty(nb, 2, device = device) + result = torch.empty(nb, 2) result[:, 0] = theta.cos() * rho result[:, 1] = theta.sin() * rho return result +def sample_mnist(nb): + train_set = torchvision.datasets.MNIST(root = './data/', train = True, download = True) + result = train_set.data[:nb].to(device).view(-1, 1, 28, 28).float() + return result + samplers = { 'gaussian_mixture': sample_gaussian_mixture, - 'arc': sample_arc, + 'two_discs': sample_two_discs, + 'disc_grid': sample_disc_grid, 'spiral': sample_spiral, + 'mnist': sample_mnist, } ###################################################################### @@ -120,27 +140,65 @@ class EMA: p.copy_(self.ema[p]) ###################################################################### -# Train + +class ConvNet(nn.Module): + def __init__(self, in_channels, out_channels): + super().__init__() + + ks, nc = 5, 64 + + self.core = nn.Sequential( + nn.Conv2d(in_channels, nc, ks, padding = ks//2), + nn.ReLU(), + nn.Conv2d(nc, nc, ks, padding = ks//2), + nn.ReLU(), + nn.Conv2d(nc, nc, ks, padding = ks//2), + nn.ReLU(), + nn.Conv2d(nc, nc, ks, padding = ks//2), + nn.ReLU(), + nn.Conv2d(nc, nc, ks, padding = ks//2), + nn.ReLU(), + nn.Conv2d(nc, out_channels, ks, padding = ks//2), + ) + + def forward(self, x): + return self.core(x) + +###################################################################### +# Data try: - train_input = samplers[args.data](args.nb_samples) + train_input = samplers[args.data](args.nb_samples).to(device) except KeyError: print(f'unknown data {args.data}') exit(1) +train_mean, train_std = train_input.mean(), train_input.std() + ###################################################################### +# Model + +if train_input.dim() == 2: + nh = 64 + + model = nn.Sequential( + nn.Linear(train_input.size(1) + 1, nh), + nn.ReLU(), + nn.Linear(nh, nh), + nn.ReLU(), + nn.Linear(nh, nh), + nn.ReLU(), + nn.Linear(nh, train_input.size(1)), + ) + +elif train_input.dim() == 4: -nh = 64 + model = ConvNet(train_input.size(1) + 1, train_input.size(1)) -model = nn.Sequential( - nn.Linear(train_input.size(1) + 1, nh), - nn.ReLU(), - nn.Linear(nh, nh), - nn.ReLU(), - nn.Linear(nh, nh), - nn.ReLU(), - nn.Linear(nh, train_input.size(1)), -).to(device) +model.to(device) + +###################################################################### +# Train T = 1000 beta = torch.linspace(1e-4, 0.02, T, device = device) @@ -156,18 +214,18 @@ for k in range(args.nb_epochs): optimizer = torch.optim.Adam(model.parameters(), lr = args.learning_rate) for x0 in train_input.split(args.batch_size): - t = torch.randint(T, (x0.size(0), 1), device = device) - eps = torch.randn(x0.size(), device = device) - input = alpha_bar[t].sqrt() * x0 + (1 - alpha_bar[t]).sqrt() * eps - input = torch.cat((input, 2 * t / T - 1), 1) - output = model(input) - loss = (eps - output).pow(2).mean() + x0 = (x0 - train_mean) / train_std + t = torch.randint(T, (x0.size(0),) + (1,) * (x0.dim() - 1), device = x0.device) + eps = torch.randn_like(x0) + input = torch.sqrt(alpha_bar[t]) * x0 + torch.sqrt(1 - alpha_bar[t]) * eps + input = torch.cat((input, t.expand_as(x0[:,:1]) / (T - 1) - 0.5), 1) + loss = (eps - model(input)).pow(2).mean() + acc_loss += loss.item() * x0.size(0) + optimizer.zero_grad() loss.backward() optimizer.step() - acc_loss += loss.item() * x0.size(0) - ema.step() if k%10 == 0: print(f'{k} {acc_loss / train_input.size(0)}') @@ -177,58 +235,77 @@ ema.copy() ###################################################################### # Generate -x = torch.randn(10000, train_input.size(1), device = device) +def generate(size, model): + with torch.no_grad(): + x = torch.randn(size, device = device) -for t in range(T-1, -1, -1): - z = torch.zeros(x.size(), device = device) if t == 0 else torch.randn(x.size(), device = device) - input = torch.cat((x, torch.ones(x.size(0), 1, device = device) * 2 * t / T - 1), 1) - x = 1 / alpha[t].sqrt() * (x - (1 - alpha[t])/(1 - alpha_bar[t]).sqrt() * model(input)) \ - + sigma[t] * z + for t in range(T-1, -1, -1): + z = torch.zeros_like(x) if t == 0 else torch.randn_like(x) + input = torch.cat((x, torch.full_like(x[:,:1], t / (T - 1) - 0.5)), 1) + x = 1/torch.sqrt(alpha[t]) \ + * (x - (1-alpha[t]) / torch.sqrt(1-alpha_bar[t]) * model(input)) \ + + sigma[t] * z + + x = x * train_std + train_mean + + return x ###################################################################### # Plot -fig = plt.figure() -ax = fig.add_subplot(1, 1, 1) +model.eval() + +if train_input.dim() == 2: + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1) + + if train_input.size(1) == 1: + + x = generate((10000, 1), model) + + ax.set_xlim(-1.25, 1.25) -if train_input.size(1) == 1: + d = train_input.flatten().detach().to('cpu').numpy() + ax.hist(d, 25, (-1, 1), + density = True, + histtype = 'stepfilled', color = 'lightblue', label = 'Train') - ax.set_xlim(-1.25, 1.25) + d = x.flatten().detach().to('cpu').numpy() + ax.hist(d, 25, (-1, 1), + density = True, + histtype = 'step', color = 'red', label = 'Synthesis') - d = train_input.flatten().detach().to('cpu').numpy() - ax.hist(d, 25, (-1, 1), - density = True, - histtype = 'stepfilled', color = 'lightblue', label = 'Train') + ax.legend(frameon = False, loc = 2) - d = x.flatten().detach().to('cpu').numpy() - ax.hist(d, 25, (-1, 1), - density = True, - histtype = 'step', color = 'red', label = 'Synthesis') + elif train_input.size(1) == 2: - ax.legend(frameon = False, loc = 2) + x = generate((1000, 2), model) -elif train_input.size(1) == 2: + ax.set_xlim(-1.25, 1.25) + ax.set_ylim(-1.25, 1.25) + ax.set(aspect = 1) - ax.set_xlim(-1.25, 1.25) - ax.set_ylim(-1.25, 1.25) - ax.set(aspect = 1) + d = train_input[:x.size(0)].detach().to('cpu').numpy() + ax.scatter(d[:, 0], d[:, 1], + color = 'lightblue', label = 'Train') - d = train_input[:200].detach().to('cpu').numpy() - ax.scatter(d[:, 0], d[:, 1], - color = 'lightblue', label = 'Train') + d = x.detach().to('cpu').numpy() + ax.scatter(d[:, 0], d[:, 1], + facecolors = 'none', color = 'red', label = 'Synthesis') - d = x[:200].detach().to('cpu').numpy() - ax.scatter(d[:, 0], d[:, 1], - color = 'red', label = 'Synthesis') + ax.legend(frameon = False, loc = 2) - ax.legend(frameon = False, loc = 2) + filename = f'diffusion_{args.data}.pdf' + print(f'saving {filename}') + fig.savefig(filename, bbox_inches='tight') -filename = f'diffusion_{args.data}.pdf' -print(f'saving {filename}') -fig.savefig(filename, bbox_inches='tight') + if hasattr(plt.get_current_fig_manager(), 'window'): + plt.get_current_fig_manager().window.setGeometry(2, 2, 1024, 768) + plt.show() -if hasattr(plt.get_current_fig_manager(), 'window'): - plt.get_current_fig_manager().window.setGeometry(2, 2, 1024, 768) - plt.show() +elif train_input.dim() == 4: + x = generate((128,) + train_input.size()[1:], model) + x = 1 - x.clamp(min = 0, max = 255) / 255 + torchvision.utils.save_image(x, f'diffusion_{args.data}.png', nrow = 16, pad_value = 0.8) ###################################################################### -- 2.20.1