Update.
[pytorch.git] / minidiffusion.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 # Minimal implementation of Jonathan Ho, Ajay Jain, Pieter Abbeel
9 # "Denoising Diffusion Probabilistic Models" (2020)
10 #
11 # https://arxiv.org/abs/2006.11239
12
13 import matplotlib.pyplot as plt
14 import torch
15 from torch import nn
16
17 ######################################################################
18
19 def sample_phi(nb):
20     p, std = 0.3, 0.2
21     result = torch.empty(nb).normal_(0, std)
22     result = result + torch.sign(torch.rand(result.size()) - p) / 2
23     return result
24
25 ######################################################################
26
27 model = nn.Sequential(
28     nn.Linear(2, 32),
29     nn.ReLU(),
30     nn.Linear(32, 32),
31     nn.ReLU(),
32     nn.Linear(32, 1),
33 )
34
35 ######################################################################
36 # Train
37
38 nb_samples = 25000
39 nb_epochs = 250
40 batch_size = 100
41
42 train_input = sample_phi(nb_samples)[:, None]
43
44 T = 1000
45 beta = torch.linspace(1e-4, 0.02, T)
46 alpha = 1 - beta
47 alpha_bar = alpha.log().cumsum(0).exp()
48 sigma = beta.sqrt()
49
50 for k in range(nb_epochs):
51     acc_loss = 0
52     optimizer = torch.optim.Adam(model.parameters(), lr = 1e-4 * (1 - k / nb_epochs) )
53
54     for x0 in train_input.split(batch_size):
55         t = torch.randint(T, (x0.size(0), 1))
56         eps = torch.randn(x0.size())
57         input = alpha_bar[t].sqrt() * x0 + (1 - alpha_bar[t]).sqrt() * eps
58         input = torch.cat((input, 2 * t / T - 1), 1)
59         output = model(input)
60         loss = (eps - output).pow(2).mean()
61         optimizer.zero_grad()
62         loss.backward()
63         optimizer.step()
64
65         acc_loss += loss.item()
66
67     if k%10 == 0: print(k, loss.item())
68
69 ######################################################################
70 # Generate
71
72 x = torch.randn(10000, 1)
73
74 for t in range(T-1, -1, -1):
75     z = torch.zeros(x.size()) if t == 0 else torch.randn(x.size())
76     input = torch.cat((x, torch.ones(x.size(0), 1) * 2 * t / T - 1), 1)
77     x = 1 / alpha[t].sqrt() * (x - (1 - alpha[t])/(1 - alpha_bar[t]).sqrt() * model(input)) + sigma[t] * z
78
79 ######################################################################
80 # Plot
81
82 fig = plt.figure()
83 ax = fig.add_subplot(1, 1, 1)
84 ax.set_xlim(-1.25, 1.25)
85
86 d = train_input.flatten().detach().numpy()
87 ax.hist(d, 25, (-1, 1),
88         density = True,
89         histtype = 'stepfilled', color = 'lightblue', label = 'Train')
90
91 d = x.flatten().detach().numpy()
92 ax.hist(d, 25, (-1, 1),
93         density = True,
94         histtype = 'step', color = 'red', label = 'Synthesis')
95
96 ax.legend(frameon = False, loc = 2)
97
98 filename = 'diffusion.pdf'
99 print(f'saving {filename}')
100 fig.savefig(filename, bbox_inches='tight')
101
102 plt.show()
103
104 ######################################################################