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 import matplotlib.pyplot as plt
9 import torch
10 from torch import nn
11
12 ######################################################################
13
14 def sample_phi(nb):
15     p, std = 0.3, 0.2
16     result = torch.empty(nb).normal_(0, std)
17     result = result + torch.sign(torch.rand(result.size()) - p) / 2
18     return result
19
20 ######################################################################
21
22 model = nn.Sequential(
23     nn.Linear(2, 32),
24     nn.ReLU(),
25     nn.Linear(32, 32),
26     nn.ReLU(),
27     nn.Linear(32, 1),
28 )
29
30 ######################################################################
31 # Train
32
33 nb_samples = 25000
34 nb_epochs = 250
35 batch_size = 100
36
37 train_input = sample_phi(nb_samples)[:, None]
38
39 T = 1000
40 beta = torch.linspace(1e-4, 0.02, T)
41 alpha = 1 - beta
42 alpha_bar = alpha.log().cumsum(0).exp()
43 sigma = beta.sqrt()
44
45 for k in range(nb_epochs):
46     acc_loss = 0
47     optimizer = torch.optim.Adam(model.parameters(), lr = 1e-4 * (1 - k / nb_epochs) )
48
49     for x0 in train_input.split(batch_size):
50         t = torch.randint(T, (x0.size(0), 1))
51         eps = torch.randn(x0.size())
52         input = alpha_bar[t].sqrt() * x0 + (1 - alpha_bar[t]).sqrt() * eps
53         input = torch.cat((input, 2 * t / T - 1), 1)
54         output = model(input)
55         loss = (eps - output).pow(2).mean()
56         optimizer.zero_grad()
57         loss.backward()
58         optimizer.step()
59
60         acc_loss += loss.item()
61
62     if k%10 == 0: print(k, loss.item())
63
64 ######################################################################
65 # Plot
66
67 x = torch.randn(10000, 1)
68
69 for t in range(T-1, -1, -1):
70     z = torch.zeros(x.size()) if t == 0 else torch.randn(x.size())
71     input = torch.cat((x, torch.ones(x.size(0), 1) * 2 * t / T - 1), 1)
72     x = 1 / alpha[t].sqrt() * (x - (1 - alpha[t])/(1 - alpha_bar[t]).sqrt() * model(input)) + sigma[t] * z
73
74 fig = plt.figure()
75 ax = fig.add_subplot(1, 1, 1)
76 ax.set_xlim(-1.25, 1.25)
77
78 d = train_input.flatten().detach().numpy()
79 ax.hist(d, 25, (-1, 1), histtype = 'stepfilled', color = 'lightblue', density = True, label = 'Train')
80
81 d = x.flatten().detach().numpy()
82 ax.hist(d, 25, (-1, 1), histtype = 'step', color = 'red', density = True, label = 'Synthesis')
83
84 ax.legend(frameon = False, loc = 2)
85
86 filename = 'diffusion.pdf'
87 fig.savefig(filename, bbox_inches='tight')
88
89 plt.show()
90
91 ######################################################################