memef4rmer/edit_anything
0
1"""SAMPLING ONLY."""2import torch3 4from .dpm_solver import NoiseScheduleVP, model_wrapper, DPM_Solver5 6 7MODEL_TYPES = {8 "eps": "noise",9 "v": "v"10}11 12 13class DPMSolverSampler(object):14 def __init__(self, model, **kwargs):15 super().__init__()16 self.model = model17 to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device)18 self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod))19 20 def register_buffer(self, name, attr):21 if type(attr) == torch.Tensor:22 if attr.device != torch.device("cuda"):23 attr = attr.to(torch.device("cuda"))24 setattr(self, name, attr)25 26 @torch.no_grad()27 def sample(self,28 S,29 batch_size,30 shape,31 conditioning=None,32 callback=None,33 normals_sequence=None,34 img_callback=None,35 quantize_x0=False,36 eta=0.,37 mask=None,38 x0=None,39 temperature=1.,40 noise_dropout=0.,41 score_corrector=None,42 corrector_kwargs=None,43 verbose=True,44 x_T=None,45 log_every_t=100,46 unconditional_guidance_scale=1.,47 unconditional_conditioning=None,48 # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...49 **kwargs50 ):51 if conditioning is not None:52 if isinstance(conditioning, dict):53 cbs = conditioning[list(conditioning.keys())[0]].shape[0]54 if cbs != batch_size:55 print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")56 else:57 if conditioning.shape[0] != batch_size:58 print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")59 60 # sampling61 C, H, W = shape62 size = (batch_size, C, H, W)63 64 print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}')65 66 device = self.model.betas.device67 if x_T is None:68 img = torch.randn(size, device=device)69 else:70 img = x_T71 72 ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod)73 74 model_fn = model_wrapper(75 lambda x, t, c: self.model.apply_model(x, t, c),76 ns,77 model_type=MODEL_TYPES[self.model.parameterization],78 guidance_type="classifier-free",79 condition=conditioning,80 unconditional_condition=unconditional_conditioning,81 guidance_scale=unconditional_guidance_scale,82 )83 84 dpm_solver = DPM_Solver(model_fn, ns, predict_x0=True, thresholding=False)85 x = dpm_solver.sample(img, steps=S, skip_type="time_uniform", method="multistep", order=2, lower_order_final=True)86 87 return x.to(device), None