patrickvonplaten commited on
Commit
9794ca5
1 Parent(s): 7eb5c5a
Files changed (2) hide show
  1. run.py +52 -0
  2. test.png +2 -2
run.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import torch
3
+ from diffusers import UNetModel, DDIMScheduler
4
+ import PIL
5
+ import numpy as np
6
+ import tqdm
7
+
8
+ generator = torch.manual_seed(0)
9
+ torch_device = "cuda" if torch.cuda.is_available() else "cpu"
10
+
11
+ # 1. Load models
12
+ noise_scheduler = DDIMScheduler.from_config("fusing/ddpm-celeba-hq", tensor_format="pt")
13
+ unet = UNetModel.from_pretrained("fusing/ddpm-celeba-hq").to(torch_device)
14
+
15
+ # 2. Sample gaussian noise
16
+ image = torch.randn(
17
+ (1, unet.in_channels, unet.resolution, unet.resolution),
18
+ generator=generator,
19
+ )
20
+ image = image.to(torch_device)
21
+
22
+ # 3. Denoise
23
+ num_inference_steps = 50
24
+ eta = 0.0 # <- deterministic sampling
25
+
26
+ for t in tqdm.tqdm(reversed(range(num_inference_steps)), total=num_inference_steps):
27
+ # 1. predict noise residual
28
+ orig_t = len(noise_scheduler) // num_inference_steps * t
29
+
30
+ with torch.no_grad():
31
+ residual = unet(image, orig_t)
32
+
33
+ # 2. predict previous mean of image x_t-1
34
+ pred_prev_image = noise_scheduler.step(residual, image, t, num_inference_steps, eta)
35
+
36
+ # 3. optionally sample variance
37
+ variance = 0
38
+ if eta > 0:
39
+ noise = torch.randn(image.shape, generator=generator).to(image.device)
40
+ variance = noise_scheduler.get_variance(t).sqrt() * eta * noise
41
+
42
+ # 4. set current image to prev_image: x_t -> x_t-1
43
+ image = pred_prev_image + variance
44
+
45
+ # 5. process image to PIL
46
+ image_processed = image.cpu().permute(0, 2, 3, 1)
47
+ image_processed = (image_processed + 1.0) * 127.5
48
+ image_processed = image_processed.numpy().astype(np.uint8)
49
+ image_pil = PIL.Image.fromarray(image_processed[0])
50
+
51
+ # 6. save image
52
+ image_pil.save("test.png")
test.png CHANGED

Git LFS Details

  • SHA256: 1a0a1d9db98421a9dad0b9f34e728dbf2b05973e0eef929c0fb279b532115604
  • Pointer size: 129 Bytes
  • Size of remote file: 2.31 kB

Git LFS Details

  • SHA256: f2b8e9a9f8c28f16e62be9b93efc402f6d11ab195d374357481c87891055f5ea
  • Pointer size: 131 Bytes
  • Size of remote file: 108 kB