2023-01-29 23:51:06 -07:00
|
|
|
import math
|
2023-01-30 00:11:30 -07:00
|
|
|
import ldm.models.diffusion.ddim
|
|
|
|
import ldm.models.diffusion.plms
|
2023-01-29 23:51:06 -07:00
|
|
|
|
2022-09-06 14:10:12 -06:00
|
|
|
import numpy as np
|
2022-09-03 03:08:45 -06:00
|
|
|
import torch
|
2022-11-02 03:45:03 -06:00
|
|
|
|
2023-01-29 23:51:06 -07:00
|
|
|
from modules.shared import state
|
|
|
|
from modules import sd_samplers_common, prompt_parser, shared
|
2023-02-10 04:30:20 -07:00
|
|
|
import modules.models.diffusion.uni_pc
|
2022-09-05 17:09:01 -06:00
|
|
|
|
|
|
|
|
2023-01-30 00:11:30 -07:00
|
|
|
samplers_data_compvis = [
|
|
|
|
sd_samplers_common.SamplerData('DDIM', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.ddim.DDIMSampler, model), [], {}),
|
|
|
|
sd_samplers_common.SamplerData('PLMS', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.plms.PLMSSampler, model), [], {}),
|
2023-02-10 04:30:20 -07:00
|
|
|
sd_samplers_common.SamplerData('UniPC', lambda model: VanillaStableDiffusionSampler(modules.models.diffusion.uni_pc.UniPCSampler, model), [], {}),
|
2023-01-30 00:11:30 -07:00
|
|
|
]
|
|
|
|
|
|
|
|
|
2022-09-03 03:08:45 -06:00
|
|
|
class VanillaStableDiffusionSampler:
|
|
|
|
def __init__(self, constructor, sd_model):
|
|
|
|
self.sampler = constructor(sd_model)
|
2023-02-10 04:30:20 -07:00
|
|
|
self.is_ddim = hasattr(self.sampler, 'p_sample_ddim')
|
2022-11-26 06:10:46 -07:00
|
|
|
self.is_plms = hasattr(self.sampler, 'p_sample_plms')
|
2023-02-10 04:30:20 -07:00
|
|
|
self.is_unipc = isinstance(self.sampler, modules.models.diffusion.uni_pc.UniPCSampler)
|
|
|
|
self.orig_p_sample_ddim = None
|
|
|
|
if self.is_plms:
|
|
|
|
self.orig_p_sample_ddim = self.sampler.p_sample_plms
|
|
|
|
elif self.is_ddim:
|
|
|
|
self.orig_p_sample_ddim = self.sampler.p_sample_ddim
|
2022-09-03 03:08:45 -06:00
|
|
|
self.mask = None
|
|
|
|
self.nmask = None
|
|
|
|
self.init_latent = None
|
2022-09-13 12:49:58 -06:00
|
|
|
self.sampler_noises = None
|
2022-09-15 04:10:16 -06:00
|
|
|
self.step = 0
|
2022-10-18 08:23:38 -06:00
|
|
|
self.stop_at = None
|
2022-09-28 09:09:06 -06:00
|
|
|
self.eta = None
|
2022-10-06 05:12:52 -06:00
|
|
|
self.config = None
|
2022-10-18 08:23:38 -06:00
|
|
|
self.last_latent = None
|
2022-09-15 04:10:16 -06:00
|
|
|
|
2022-10-19 16:09:43 -06:00
|
|
|
self.conditioning_key = sd_model.model.conditioning_key
|
|
|
|
|
2022-09-13 12:49:58 -06:00
|
|
|
def number_of_needed_noises(self, p):
|
|
|
|
return 0
|
2022-09-03 03:08:45 -06:00
|
|
|
|
2022-10-18 08:23:38 -06:00
|
|
|
def launch_sampling(self, steps, func):
|
|
|
|
state.sampling_steps = steps
|
|
|
|
state.sampling_step = 0
|
|
|
|
|
|
|
|
try:
|
|
|
|
return func()
|
2023-01-29 23:51:06 -07:00
|
|
|
except sd_samplers_common.InterruptedException:
|
2022-10-18 08:23:38 -06:00
|
|
|
return self.last_latent
|
|
|
|
|
2022-09-15 04:10:16 -06:00
|
|
|
def p_sample_ddim_hook(self, x_dec, cond, ts, unconditional_conditioning, *args, **kwargs):
|
2023-02-10 04:30:20 -07:00
|
|
|
x_dec, ts, cond, unconditional_conditioning = self.before_sample(x_dec, ts, cond, unconditional_conditioning)
|
|
|
|
|
2023-05-10 02:19:16 -06:00
|
|
|
res = self.orig_p_sample_ddim(x_dec, cond, ts, *args, unconditional_conditioning=unconditional_conditioning, **kwargs)
|
2023-02-10 04:30:20 -07:00
|
|
|
|
|
|
|
x_dec, ts, cond, unconditional_conditioning, res = self.after_sample(x_dec, ts, cond, unconditional_conditioning, res)
|
|
|
|
|
|
|
|
return res
|
|
|
|
|
|
|
|
def before_sample(self, x, ts, cond, unconditional_conditioning):
|
2022-10-18 08:23:38 -06:00
|
|
|
if state.interrupted or state.skipped:
|
2023-01-29 23:51:06 -07:00
|
|
|
raise sd_samplers_common.InterruptedException
|
2022-10-18 08:23:38 -06:00
|
|
|
|
|
|
|
if self.stop_at is not None and self.step > self.stop_at:
|
2023-01-29 23:51:06 -07:00
|
|
|
raise sd_samplers_common.InterruptedException
|
2022-10-18 08:23:38 -06:00
|
|
|
|
2022-10-20 10:45:03 -06:00
|
|
|
# Have to unwrap the inpainting conditioning here to perform pre-processing
|
2022-10-19 14:47:45 -06:00
|
|
|
image_conditioning = None
|
2023-03-24 20:48:16 -06:00
|
|
|
uc_image_conditioning = None
|
2022-10-19 14:47:45 -06:00
|
|
|
if isinstance(cond, dict):
|
2023-03-24 20:48:16 -06:00
|
|
|
if self.conditioning_key == "crossattn-adm":
|
|
|
|
image_conditioning = cond["c_adm"]
|
|
|
|
uc_image_conditioning = unconditional_conditioning["c_adm"]
|
|
|
|
else:
|
|
|
|
image_conditioning = cond["c_concat"][0]
|
2022-10-19 14:47:45 -06:00
|
|
|
cond = cond["c_crossattn"][0]
|
|
|
|
unconditional_conditioning = unconditional_conditioning["c_crossattn"][0]
|
2022-10-18 08:23:38 -06:00
|
|
|
|
2022-10-05 14:16:27 -06:00
|
|
|
conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
|
2022-09-15 04:10:16 -06:00
|
|
|
unconditional_conditioning = prompt_parser.reconstruct_cond_batch(unconditional_conditioning, self.step)
|
|
|
|
|
2023-05-10 02:05:02 -06:00
|
|
|
assert all(len(conds) == 1 for conds in conds_list), 'composition via AND is not supported for DDIM/PLMS samplers'
|
2022-10-05 14:16:27 -06:00
|
|
|
cond = tensor
|
|
|
|
|
2022-10-08 06:25:59 -06:00
|
|
|
# for DDIM, shapes must match, we can't just process cond and uncond independently;
|
|
|
|
# filling unconditional_conditioning with repeats of the last vector to match length is
|
|
|
|
# not 100% correct but should work well enough
|
|
|
|
if unconditional_conditioning.shape[1] < cond.shape[1]:
|
|
|
|
last_vector = unconditional_conditioning[:, -1:]
|
|
|
|
last_vector_repeated = last_vector.repeat([1, cond.shape[1] - unconditional_conditioning.shape[1], 1])
|
|
|
|
unconditional_conditioning = torch.hstack([unconditional_conditioning, last_vector_repeated])
|
|
|
|
elif unconditional_conditioning.shape[1] > cond.shape[1]:
|
|
|
|
unconditional_conditioning = unconditional_conditioning[:, :cond.shape[1]]
|
|
|
|
|
2022-09-15 04:10:16 -06:00
|
|
|
if self.mask is not None:
|
|
|
|
img_orig = self.sampler.model.q_sample(self.init_latent, ts)
|
2023-02-10 04:30:20 -07:00
|
|
|
x = img_orig * self.mask + self.nmask * x
|
2022-09-15 04:10:16 -06:00
|
|
|
|
2022-10-20 10:45:03 -06:00
|
|
|
# Wrap the image conditioning back up since the DDIM code can accept the dict directly.
|
|
|
|
# Note that they need to be lists because it just concatenates them later.
|
2022-10-19 14:47:45 -06:00
|
|
|
if image_conditioning is not None:
|
2023-03-24 20:48:16 -06:00
|
|
|
if self.conditioning_key == "crossattn-adm":
|
|
|
|
cond = {"c_adm": image_conditioning, "c_crossattn": [cond]}
|
|
|
|
unconditional_conditioning = {"c_adm": uc_image_conditioning, "c_crossattn": [unconditional_conditioning]}
|
|
|
|
else:
|
|
|
|
cond = {"c_concat": [image_conditioning], "c_crossattn": [cond]}
|
|
|
|
unconditional_conditioning = {"c_concat": [image_conditioning], "c_crossattn": [unconditional_conditioning]}
|
2022-10-19 14:47:45 -06:00
|
|
|
|
2023-02-10 04:30:20 -07:00
|
|
|
return x, ts, cond, unconditional_conditioning
|
|
|
|
|
2023-02-10 05:47:08 -07:00
|
|
|
def update_step(self, last_latent):
|
2022-09-15 04:10:16 -06:00
|
|
|
if self.mask is not None:
|
2023-02-10 05:47:08 -07:00
|
|
|
self.last_latent = self.init_latent * self.mask + self.nmask * last_latent
|
2022-09-15 04:10:16 -06:00
|
|
|
else:
|
2023-02-10 05:47:08 -07:00
|
|
|
self.last_latent = last_latent
|
2022-10-18 08:23:38 -06:00
|
|
|
|
2023-01-29 23:51:06 -07:00
|
|
|
sd_samplers_common.store_latent(self.last_latent)
|
2022-09-15 04:10:16 -06:00
|
|
|
|
|
|
|
self.step += 1
|
2022-10-18 08:23:38 -06:00
|
|
|
state.sampling_step = self.step
|
|
|
|
shared.total_tqdm.update()
|
|
|
|
|
2023-02-10 05:47:08 -07:00
|
|
|
def after_sample(self, x, ts, cond, uncond, res):
|
|
|
|
if not self.is_unipc:
|
|
|
|
self.update_step(res[1])
|
|
|
|
|
2023-02-10 04:30:20 -07:00
|
|
|
return x, ts, cond, uncond, res
|
2022-09-03 03:08:45 -06:00
|
|
|
|
2023-02-10 05:47:08 -07:00
|
|
|
def unipc_after_update(self, x, model_x):
|
|
|
|
self.update_step(x)
|
|
|
|
|
2022-09-28 09:09:06 -06:00
|
|
|
def initialize(self, p):
|
2023-01-29 23:51:06 -07:00
|
|
|
self.eta = p.eta if p.eta is not None else shared.opts.eta_ddim
|
2023-01-30 00:47:09 -07:00
|
|
|
if self.eta != 0.0:
|
|
|
|
p.extra_generation_params["Eta DDIM"] = self.eta
|
2022-09-28 09:09:06 -06:00
|
|
|
|
2023-03-11 02:09:36 -07:00
|
|
|
if self.is_unipc:
|
|
|
|
keys = [
|
|
|
|
('UniPC variant', 'uni_pc_variant'),
|
|
|
|
('UniPC skip type', 'uni_pc_skip_type'),
|
|
|
|
('UniPC order', 'uni_pc_order'),
|
|
|
|
('UniPC lower order final', 'uni_pc_lower_order_final'),
|
|
|
|
]
|
|
|
|
|
|
|
|
for name, key in keys:
|
|
|
|
v = getattr(shared.opts, key)
|
|
|
|
if v != shared.opts.get_default(key):
|
|
|
|
p.extra_generation_params[name] = v
|
|
|
|
|
2022-09-28 09:09:06 -06:00
|
|
|
for fieldname in ['p_sample_ddim', 'p_sample_plms']:
|
|
|
|
if hasattr(self.sampler, fieldname):
|
|
|
|
setattr(self.sampler, fieldname, self.p_sample_ddim_hook)
|
2023-02-10 04:30:20 -07:00
|
|
|
if self.is_unipc:
|
2023-02-10 05:47:08 -07:00
|
|
|
self.sampler.set_hooks(lambda x, t, c, u: self.before_sample(x, t, c, u), lambda x, t, c, u, r: self.after_sample(x, t, c, u, r), lambda x, mx: self.unipc_after_update(x, mx))
|
2022-09-28 09:09:06 -06:00
|
|
|
|
|
|
|
self.mask = p.mask if hasattr(p, 'mask') else None
|
|
|
|
self.nmask = p.nmask if hasattr(p, 'nmask') else None
|
|
|
|
|
2023-03-11 02:09:36 -07:00
|
|
|
|
2022-10-29 08:23:19 -06:00
|
|
|
def adjust_steps_if_invalid(self, p, num_steps):
|
2023-02-10 06:00:09 -07:00
|
|
|
if ((self.config.name == 'DDIM') and p.ddim_discretize == 'uniform') or (self.config.name == 'PLMS') or (self.config.name == 'UniPC'):
|
2023-03-10 17:56:14 -07:00
|
|
|
if self.config.name == 'UniPC' and num_steps < shared.opts.uni_pc_order:
|
|
|
|
num_steps = shared.opts.uni_pc_order
|
2022-10-29 08:23:19 -06:00
|
|
|
valid_step = 999 / (1000 // num_steps)
|
2023-01-29 23:51:06 -07:00
|
|
|
if valid_step == math.floor(valid_step):
|
2022-10-29 08:23:19 -06:00
|
|
|
return int(valid_step) + 1
|
2023-03-10 17:56:14 -07:00
|
|
|
|
2022-10-29 08:23:19 -06:00
|
|
|
return num_steps
|
|
|
|
|
2022-10-19 14:47:45 -06:00
|
|
|
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
|
2023-01-29 23:51:06 -07:00
|
|
|
steps, t_enc = sd_samplers_common.setup_img2img_steps(p, steps)
|
2022-10-29 08:23:19 -06:00
|
|
|
steps = self.adjust_steps_if_invalid(p, steps)
|
2022-09-28 13:30:52 -06:00
|
|
|
self.initialize(p)
|
|
|
|
|
2022-10-29 08:23:19 -06:00
|
|
|
self.sampler.make_schedule(ddim_num_steps=steps, ddim_eta=self.eta, ddim_discretize=p.ddim_discretize, verbose=False)
|
2022-09-03 03:08:45 -06:00
|
|
|
x1 = self.sampler.stochastic_encode(x, torch.tensor([t_enc] * int(x.shape[0])).to(shared.device), noise=noise)
|
|
|
|
|
2022-09-19 07:42:56 -06:00
|
|
|
self.init_latent = x
|
2022-10-20 14:49:14 -06:00
|
|
|
self.last_latent = x
|
2022-09-15 23:51:21 -06:00
|
|
|
self.step = 0
|
2022-09-03 03:08:45 -06:00
|
|
|
|
2022-10-19 15:14:24 -06:00
|
|
|
# Wrap the conditioning models with additional image conditioning for inpainting model
|
|
|
|
if image_conditioning is not None:
|
2023-03-24 20:48:16 -06:00
|
|
|
if self.conditioning_key == "crossattn-adm":
|
|
|
|
conditioning = {"c_adm": image_conditioning, "c_crossattn": [conditioning]}
|
|
|
|
unconditional_conditioning = {"c_adm": torch.zeros_like(image_conditioning), "c_crossattn": [unconditional_conditioning]}
|
|
|
|
else:
|
|
|
|
conditioning = {"c_concat": [image_conditioning], "c_crossattn": [conditioning]}
|
|
|
|
unconditional_conditioning = {"c_concat": [image_conditioning], "c_crossattn": [unconditional_conditioning]}
|
2023-01-14 06:29:23 -07:00
|
|
|
|
2022-10-21 08:46:32 -06:00
|
|
|
samples = self.launch_sampling(t_enc + 1, lambda: self.sampler.decode(x1, conditioning, t_enc, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning))
|
2022-09-03 03:08:45 -06:00
|
|
|
|
|
|
|
return samples
|
|
|
|
|
2022-10-19 14:47:45 -06:00
|
|
|
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
|
2022-09-28 09:09:06 -06:00
|
|
|
self.initialize(p)
|
|
|
|
|
2022-09-08 10:20:41 -06:00
|
|
|
self.init_latent = None
|
2022-10-20 14:49:14 -06:00
|
|
|
self.last_latent = x
|
2022-09-15 23:51:21 -06:00
|
|
|
self.step = 0
|
2022-09-08 10:20:41 -06:00
|
|
|
|
2022-10-29 08:23:19 -06:00
|
|
|
steps = self.adjust_steps_if_invalid(p, steps or p.steps)
|
2022-09-19 07:42:56 -06:00
|
|
|
|
2022-10-19 14:47:45 -06:00
|
|
|
# Wrap the conditioning models with additional image conditioning for inpainting model
|
2022-11-26 06:10:46 -07:00
|
|
|
# dummy_for_plms is needed because PLMS code checks the first item in the dict to have the right shape
|
2022-10-19 14:47:45 -06:00
|
|
|
if image_conditioning is not None:
|
2023-03-24 20:48:16 -06:00
|
|
|
if self.conditioning_key == "crossattn-adm":
|
|
|
|
conditioning = {"dummy_for_plms": np.zeros((conditioning.shape[0],)), "c_crossattn": [conditioning], "c_adm": image_conditioning}
|
|
|
|
unconditional_conditioning = {"c_crossattn": [unconditional_conditioning], "c_adm": torch.zeros_like(image_conditioning)}
|
|
|
|
else:
|
|
|
|
conditioning = {"dummy_for_plms": np.zeros((conditioning.shape[0],)), "c_crossattn": [conditioning], "c_concat": [image_conditioning]}
|
|
|
|
unconditional_conditioning = {"c_crossattn": [unconditional_conditioning], "c_concat": [image_conditioning]}
|
2022-10-19 14:47:45 -06:00
|
|
|
|
2022-10-29 08:23:19 -06:00
|
|
|
samples_ddim = self.launch_sampling(steps, lambda: self.sampler.sample(S=steps, conditioning=conditioning, batch_size=int(x.shape[0]), shape=x[0].shape, verbose=False, unconditional_guidance_scale=p.cfg_scale, unconditional_conditioning=unconditional_conditioning, x_T=x, eta=self.eta)[0])
|
2022-09-13 11:12:24 -06:00
|
|
|
|
2022-09-03 03:08:45 -06:00
|
|
|
return samples_ddim
|