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>
10 import matplotlib.pyplot as plt
15 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
17 ######################################################################
19 def sample_gaussian_mixture(nb):
21 result = torch.empty(nb, 1, device = device).normal_(0, std)
22 result = result + torch.sign(torch.rand(result.size(), device = device) - p) / 2
26 theta = torch.rand(nb, device = device) * math.pi
27 rho = torch.rand(nb, device = device) * 0.1 + 0.7
28 result = torch.empty(nb, 2, device = device)
29 result[:, 0] = theta.cos() * rho
30 result[:, 1] = theta.sin() * rho
33 def sample_spiral(nb):
34 u = torch.rand(nb, device = device)
35 rho = u * 0.65 + 0.25 + torch.rand(nb, device = device) * 0.15
36 theta = u * math.pi * 3
37 result = torch.empty(nb, 2, device = device)
38 result[:, 0] = theta.cos() * rho
39 result[:, 1] = theta.sin() * rho
43 'gaussian_mixture': sample_gaussian_mixture,
45 'spiral': sample_spiral,
48 ######################################################################
50 parser = argparse.ArgumentParser(
51 description = '''A minimal implementation of Jonathan Ho, Ajay Jain, Pieter Abbeel
52 "Denoising Diffusion Probabilistic Models" (2020)
53 https://arxiv.org/abs/2006.11239''',
55 formatter_class = argparse.ArgumentDefaultsHelpFormatter
58 parser.add_argument('--seed',
59 type = int, default = 0,
60 help = 'Random seed, < 0 is no seeding')
62 parser.add_argument('--nb_epochs',
63 type = int, default = 100,
64 help = 'How many epochs')
66 parser.add_argument('--batch_size',
67 type = int, default = 25,
70 parser.add_argument('--nb_samples',
71 type = int, default = 25000,
72 help = 'Number of training examples')
74 parser.add_argument('--learning_rate',
75 type = float, default = 1e-3,
76 help = 'Learning rate')
78 parser.add_argument('--ema_decay',
79 type = float, default = 0.9999,
80 help = 'EMA decay, < 0 is no EMA')
82 data_list = ', '.join( [ str(k) for k in samplers ])
84 parser.add_argument('--data',
85 type = str, default = 'gaussian_mixture',
86 help = f'Toy data-set to use: {data_list}')
88 args = parser.parse_args()
91 # torch.backends.cudnn.deterministic = True
92 # torch.backends.cudnn.benchmark = False
93 # torch.use_deterministic_algorithms(True)
94 torch.manual_seed(args.seed)
95 if torch.cuda.is_available():
96 torch.cuda.manual_seed_all(args.seed)
98 ######################################################################
101 def __init__(self, model, decay):
104 if self.decay < 0: return
106 with torch.no_grad():
107 for p in model.parameters():
108 self.ema[p] = p.clone()
111 if self.decay < 0: return
112 with torch.no_grad():
113 for p in self.model.parameters():
114 self.ema[p].copy_(self.decay * self.ema[p] + (1 - self.decay) * p)
117 if self.decay < 0: return
118 with torch.no_grad():
119 for p in self.model.parameters():
122 ######################################################################
126 train_input = samplers[args.data](args.nb_samples)
128 print(f'unknown data {args.data}')
131 ######################################################################
135 model = nn.Sequential(
136 nn.Linear(train_input.size(1) + 1, nh),
142 nn.Linear(nh, train_input.size(1)),
146 beta = torch.linspace(1e-4, 0.02, T, device = device)
148 alpha_bar = alpha.log().cumsum(0).exp()
151 ema = EMA(model, decay = args.ema_decay)
153 for k in range(args.nb_epochs):
156 optimizer = torch.optim.Adam(model.parameters(), lr = args.learning_rate)
158 for x0 in train_input.split(args.batch_size):
159 t = torch.randint(T, (x0.size(0), 1), device = device)
160 eps = torch.randn(x0.size(), device = device)
161 input = alpha_bar[t].sqrt() * x0 + (1 - alpha_bar[t]).sqrt() * eps
162 input = torch.cat((input, 2 * t / T - 1), 1)
163 output = model(input)
164 loss = (eps - output).pow(2).mean()
165 optimizer.zero_grad()
169 acc_loss += loss.item() * x0.size(0)
173 if k%10 == 0: print(f'{k} {acc_loss / train_input.size(0)}')
177 ######################################################################
180 x = torch.randn(10000, train_input.size(1), device = device)
182 for t in range(T-1, -1, -1):
183 z = torch.zeros(x.size(), device = device) if t == 0 else torch.randn(x.size(), device = device)
184 input = torch.cat((x, torch.ones(x.size(0), 1, device = device) * 2 * t / T - 1), 1)
185 x = 1 / alpha[t].sqrt() * (x - (1 - alpha[t])/(1 - alpha_bar[t]).sqrt() * model(input)) \
188 ######################################################################
192 ax = fig.add_subplot(1, 1, 1)
194 if train_input.size(1) == 1:
196 ax.set_xlim(-1.25, 1.25)
198 d = train_input.flatten().detach().to('cpu').numpy()
199 ax.hist(d, 25, (-1, 1),
201 histtype = 'stepfilled', color = 'lightblue', label = 'Train')
203 d = x.flatten().detach().to('cpu').numpy()
204 ax.hist(d, 25, (-1, 1),
206 histtype = 'step', color = 'red', label = 'Synthesis')
208 ax.legend(frameon = False, loc = 2)
210 elif train_input.size(1) == 2:
212 ax.set_xlim(-1.25, 1.25)
213 ax.set_ylim(-1.25, 1.25)
216 d = train_input[:200].detach().to('cpu').numpy()
217 ax.scatter(d[:, 0], d[:, 1],
218 color = 'lightblue', label = 'Train')
220 d = x[:200].detach().to('cpu').numpy()
221 ax.scatter(d[:, 0], d[:, 1],
222 color = 'red', label = 'Synthesis')
224 ax.legend(frameon = False, loc = 2)
226 filename = f'diffusion_{args.data}.pdf'
227 print(f'saving {filename}')
228 fig.savefig(filename, bbox_inches='tight')
230 if hasattr(plt.get_current_fig_manager(), 'window'):
231 plt.get_current_fig_manager().window.setGeometry(2, 2, 1024, 768)
234 ######################################################################