3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
8 # Minimal implementation of Jonathan Ho, Ajay Jain, Pieter Abbeel
9 # "Denoising Diffusion Probabilistic Models" (2020)
11 # https://arxiv.org/abs/2006.11239
13 import matplotlib.pyplot as plt
17 ######################################################################
21 result = torch.empty(nb).normal_(0, std)
22 result = result + torch.sign(torch.rand(result.size()) - p) / 2
25 ######################################################################
27 model = nn.Sequential(
35 ######################################################################
42 train_input = sample_phi(nb_samples)[:, None]
45 beta = torch.linspace(1e-4, 0.02, T)
47 alpha_bar = alpha.log().cumsum(0).exp()
50 for k in range(nb_epochs):
53 optimizer = torch.optim.Adam(model.parameters(), lr = 1e-4 * (1 - k / nb_epochs) )
55 for x0 in train_input.split(batch_size):
56 t = torch.randint(T, (x0.size(0), 1))
57 eps = torch.randn(x0.size())
58 input = alpha_bar[t].sqrt() * x0 + (1 - alpha_bar[t]).sqrt() * eps
59 input = torch.cat((input, 2 * t / T - 1), 1)
61 loss = (eps - output).pow(2).mean()
66 acc_loss += loss.item()
68 if k%10 == 0: print(k, loss.item())
70 ######################################################################
73 x = torch.randn(10000, 1)
75 for t in range(T-1, -1, -1):
76 z = torch.zeros(x.size()) if t == 0 else torch.randn(x.size())
77 input = torch.cat((x, torch.ones(x.size(0), 1) * 2 * t / T - 1), 1)
78 x = 1 / alpha[t].sqrt() * (x - (1 - alpha[t])/(1 - alpha_bar[t]).sqrt() * model(input)) \
81 ######################################################################
85 ax = fig.add_subplot(1, 1, 1)
86 ax.set_xlim(-1.25, 1.25)
88 d = train_input.flatten().detach().numpy()
89 ax.hist(d, 25, (-1, 1),
91 histtype = 'stepfilled', color = 'lightblue', label = 'Train')
93 d = x.flatten().detach().numpy()
94 ax.hist(d, 25, (-1, 1),
96 histtype = 'step', color = 'red', label = 'Synthesis')
98 ax.legend(frameon = False, loc = 2)
100 filename = 'diffusion.pdf'
101 print(f'saving {filename}')
102 fig.savefig(filename, bbox_inches='tight')
106 ######################################################################