MCPcopy Create free account
hub / github.com/VisionXLab/OF-Diff / DDIMSampler

Class DDIMSampler

cldm/ddim_hacked.py:10–317  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8
9
10class DDIMSampler(object):
11 def __init__(self, model, schedule="linear", **kwargs):
12 super().__init__()
13 self.model = model
14 self.ddpm_num_timesteps = model.num_timesteps
15 self.schedule = schedule
16
17 def register_buffer(self, name, attr):
18 if type(attr) == torch.Tensor:
19 if attr.device != torch.device("cuda"):
20 attr = attr.to(torch.device("cuda"))
21 setattr(self, name, attr)
22
23 def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
24 self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
25 num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
26 alphas_cumprod = self.model.alphas_cumprod
27 assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
28 to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
29
30 self.register_buffer('betas', to_torch(self.model.betas))
31 self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
32 self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
33
34 # calculations for diffusion q(x_t | x_{t-1}) and others
35 self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
36 self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
37 self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
38 self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
39 self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
40
41 # ddim sampling parameters
42 ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
43 ddim_timesteps=self.ddim_timesteps,
44 eta=ddim_eta,verbose=verbose)
45 self.register_buffer('ddim_sigmas', ddim_sigmas)
46 self.register_buffer('ddim_alphas', ddim_alphas)
47 self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
48 self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
49 sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
50 (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
51 1 - self.alphas_cumprod / self.alphas_cumprod_prev))
52 self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
53
54 @torch.no_grad()
55 def sample(self,
56 S,
57 batch_size,
58 shape,
59 conditioning=None,
60 callback=None,
61 normals_sequence=None,
62 img_callback=None,
63 quantize_x0=False,
64 eta=0.,
65 mask=None,
66 x0=None,
67 temperature=1.,

Callers 1

sample_logMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected