From: Francois Fleuret Date: Sun, 14 Aug 2022 08:46:35 +0000 (+0200) Subject: Update. X-Git-Url: https://fleuret.org/cgi-bin/gitweb/gitweb.cgi?a=commitdiff_plain;h=560b7d51f52c7328e9d87ce717dacc4da7977de7;p=pytorch.git Update. --- diff --git a/minidiffusion.py b/minidiffusion.py index 42dff7c..879b796 100755 --- a/minidiffusion.py +++ b/minidiffusion.py @@ -14,6 +14,8 @@ from torch import nn device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') +print(f'device {device}') + ###################################################################### def sample_gaussian_mixture(nb): @@ -205,6 +207,24 @@ model.to(device) print(f'nb_parameters {sum([ p.numel() for p in model.parameters() ])}') +###################################################################### +# Generate + +def generate(size, alpha, alpha_bar, sigma, model): + with torch.no_grad(): + x = torch.randn(size, device = device) + + 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 + ###################################################################### # Train @@ -240,36 +260,19 @@ for k in range(args.nb_epochs): ema.copy() -###################################################################### -# Generate - -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_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 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) + x = generate((10000, 1), alpha, alpha_bar, sigma, model) ax.set_xlim(-1.25, 1.25) ax.spines.right.set_visible(False) @@ -289,7 +292,7 @@ if train_input.dim() == 2: elif train_input.size(1) == 2: - x = generate((1000, 2), model) + x = generate((1000, 2), alpha, alpha_bar, sigma, model) ax.set_xlim(-1.5, 1.5) ax.set_ylim(-1.5, 1.5) @@ -316,7 +319,8 @@ if train_input.dim() == 2: plt.show() elif train_input.dim() == 4: - x = generate((128,) + train_input.size()[1:], model) + + x = generate((128,) + train_input.size()[1:], alpha, alpha_bar, sigma, 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)