device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+print(f'device {device}')
+
######################################################################
def sample_gaussian_mixture(nb):
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
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)
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)
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)