|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from diffusers import DiffusionPipeline |
|
import tqdm |
|
import torch |
|
|
|
|
|
class DDPM(DiffusionPipeline): |
|
|
|
modeling_file = "modeling_ddpm.py" |
|
|
|
def __init__(self, unet, noise_scheduler): |
|
super().__init__() |
|
self.register_modules(unet=unet, noise_scheduler=noise_scheduler) |
|
|
|
def __call__(self, generator=None, torch_device=None): |
|
torch_device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
self.unet.to(torch_device) |
|
|
|
image = self.noise_scheduler.sample_noise((1, self.unet.in_channels, self.unet.resolution, self.unet.resolution), device=torch_device, generator=generator) |
|
for t in tqdm.tqdm(reversed(range(len(self.noise_scheduler))), total=len(self.noise_scheduler)): |
|
|
|
clip_image_coeff = 1 / torch.sqrt(self.noise_scheduler.get_alpha_prod(t)) |
|
clip_noise_coeff = torch.sqrt(1 / self.noise_scheduler.get_alpha_prod(t) - 1) |
|
image_coeff = (1 - self.noise_scheduler.get_alpha_prod(t - 1)) * torch.sqrt(self.noise_scheduler.get_alpha(t)) / (1 - self.noise_scheduler.get_alpha_prod(t)) |
|
clip_coeff = torch.sqrt(self.noise_scheduler.get_alpha_prod(t - 1)) * self.noise_scheduler.get_beta(t) / (1 - self.noise_scheduler.get_alpha_prod(t)) |
|
|
|
|
|
with torch.no_grad(): |
|
noise_residual = self.unet(image, t) |
|
|
|
|
|
|
|
pred_mean = clip_image_coeff * image - clip_noise_coeff * noise_residual |
|
pred_mean = torch.clamp(pred_mean, -1, 1) |
|
prev_image = clip_coeff * pred_mean + image_coeff * image |
|
|
|
|
|
prev_variance = self.noise_scheduler.sample_variance(t, prev_image.shape, device=torch_device, generator=generator) |
|
|
|
|
|
sampled_prev_image = prev_image + prev_variance |
|
image = sampled_prev_image |
|
|
|
return image |
|
|