Path: blob/master/modules/models/diffusion/uni_pc/sampler.py
3078 views
"""SAMPLING ONLY."""12import torch34from .uni_pc import NoiseScheduleVP, model_wrapper, UniPC5from modules import shared, devices678class UniPCSampler(object):9def __init__(self, model, **kwargs):10super().__init__()11self.model = model12to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)13self.before_sample = None14self.after_sample = None15self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod))1617def register_buffer(self, name, attr):18if type(attr) == torch.Tensor:19if attr.device != devices.device:20attr = attr.to(devices.device)21setattr(self, name, attr)2223def set_hooks(self, before_sample, after_sample, after_update):24self.before_sample = before_sample25self.after_sample = after_sample26self.after_update = after_update2728@torch.no_grad()29def sample(self,30S,31batch_size,32shape,33conditioning=None,34callback=None,35normals_sequence=None,36img_callback=None,37quantize_x0=False,38eta=0.,39mask=None,40x0=None,41temperature=1.,42noise_dropout=0.,43score_corrector=None,44corrector_kwargs=None,45verbose=True,46x_T=None,47log_every_t=100,48unconditional_guidance_scale=1.,49unconditional_conditioning=None,50# this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...51**kwargs52):53if conditioning is not None:54if isinstance(conditioning, dict):55ctmp = conditioning[list(conditioning.keys())[0]]56while isinstance(ctmp, list):57ctmp = ctmp[0]58cbs = ctmp.shape[0]59if cbs != batch_size:60print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")6162elif isinstance(conditioning, list):63for ctmp in conditioning:64if ctmp.shape[0] != batch_size:65print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")6667else:68if conditioning.shape[0] != batch_size:69print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")7071# sampling72C, H, W = shape73size = (batch_size, C, H, W)74# print(f'Data shape for UniPC sampling is {size}')7576device = self.model.betas.device77if x_T is None:78img = torch.randn(size, device=device)79else:80img = x_T8182ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)8384# SD 1.X is "noise", SD 2.X is "v"85model_type = "v" if self.model.parameterization == "v" else "noise"8687model_fn = model_wrapper(88lambda x, t, c: self.model.apply_model(x, t, c),89ns,90model_type=model_type,91guidance_type="classifier-free",92#condition=conditioning,93#unconditional_condition=unconditional_conditioning,94guidance_scale=unconditional_guidance_scale,95)9697uni_pc = UniPC(model_fn, ns, predict_x0=True, thresholding=False, variant=shared.opts.uni_pc_variant, condition=conditioning, unconditional_condition=unconditional_conditioning, before_sample=self.before_sample, after_sample=self.after_sample, after_update=self.after_update)98x = uni_pc.sample(img, steps=S, skip_type=shared.opts.uni_pc_skip_type, method="multistep", order=shared.opts.uni_pc_order, lower_order_final=shared.opts.uni_pc_lower_order_final)99100return x.to(device), None101102103