2022-09-03 12:08:45 +03:00
|
|
|
from collections import namedtuple
|
2022-09-06 23:10:12 +03:00
|
|
|
import numpy as np
|
2022-10-29 17:23:19 +03:00
|
|
|
from math import floor
|
2022-09-03 12:08:45 +03:00
|
|
|
import torch
|
|
|
|
import tqdm
|
2022-09-06 23:10:12 +03:00
|
|
|
from PIL import Image
|
2022-09-28 10:49:07 +03:00
|
|
|
import inspect
|
2022-09-03 12:08:45 +03:00
|
|
|
import k_diffusion.sampling
|
2022-09-06 02:09:01 +03:00
|
|
|
import ldm.models.diffusion.ddim
|
|
|
|
import ldm.models.diffusion.plms
|
2022-10-19 13:38:10 +03:00
|
|
|
from modules import prompt_parser, devices, processing, images
|
2022-09-03 12:08:45 +03:00
|
|
|
|
|
|
|
from modules.shared import opts, cmd_opts, state
|
|
|
|
import modules.shared as shared
|
2022-11-02 03:38:17 +03:00
|
|
|
from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-09-03 17:21:15 +03:00
|
|
|
|
2022-10-06 14:12:52 +03:00
|
|
|
SamplerData = namedtuple('SamplerData', ['name', 'constructor', 'aliases', 'options'])
|
2022-09-03 17:21:15 +03:00
|
|
|
|
|
|
|
samplers_k_diffusion = [
|
2022-10-06 14:12:52 +03:00
|
|
|
('Euler a', 'sample_euler_ancestral', ['k_euler_a'], {}),
|
|
|
|
('Euler', 'sample_euler', ['k_euler'], {}),
|
|
|
|
('LMS', 'sample_lms', ['k_lms'], {}),
|
|
|
|
('Heun', 'sample_heun', ['k_heun'], {}),
|
|
|
|
('DPM2', 'sample_dpm_2', ['k_dpm_2'], {}),
|
|
|
|
('DPM2 a', 'sample_dpm_2_ancestral', ['k_dpm_2_a'], {}),
|
2022-11-05 18:32:22 +03:00
|
|
|
('DPM++ 2S a', 'sample_dpmpp_2s_ancestral', ['k_dpmpp_2s_a'], {}),
|
|
|
|
('DPM++ 2M', 'sample_dpmpp_2m', ['k_dpmpp_2m'], {}),
|
2022-11-22 17:24:50 +03:00
|
|
|
('DPM++ SDE', 'sample_dpmpp_sde', ['k_dpmpp_sde'], {}),
|
2022-10-06 14:12:52 +03:00
|
|
|
('DPM fast', 'sample_dpm_fast', ['k_dpm_fast'], {}),
|
|
|
|
('DPM adaptive', 'sample_dpm_adaptive', ['k_dpm_ad'], {}),
|
|
|
|
('LMS Karras', 'sample_lms', ['k_lms_ka'], {'scheduler': 'karras'}),
|
|
|
|
('DPM2 Karras', 'sample_dpm_2', ['k_dpm_2_ka'], {'scheduler': 'karras'}),
|
|
|
|
('DPM2 a Karras', 'sample_dpm_2_ancestral', ['k_dpm_2_a_ka'], {'scheduler': 'karras'}),
|
2022-11-05 18:32:22 +03:00
|
|
|
('DPM++ 2S a Karras', 'sample_dpmpp_2s_ancestral', ['k_dpmpp_2s_a_ka'], {'scheduler': 'karras'}),
|
|
|
|
('DPM++ 2M Karras', 'sample_dpmpp_2m', ['k_dpmpp_2m_ka'], {'scheduler': 'karras'}),
|
2022-11-22 17:24:50 +03:00
|
|
|
('DPM++ SDE Karras', 'sample_dpmpp_sde', ['k_dpmpp_sde_ka'], {'scheduler': 'karras'}),
|
2022-09-03 17:21:15 +03:00
|
|
|
]
|
|
|
|
|
|
|
|
samplers_data_k_diffusion = [
|
2022-10-06 14:12:52 +03:00
|
|
|
SamplerData(label, lambda model, funcname=funcname: KDiffusionSampler(funcname, model), aliases, options)
|
|
|
|
for label, funcname, aliases, options in samplers_k_diffusion
|
2022-09-03 17:21:15 +03:00
|
|
|
if hasattr(k_diffusion.sampling, funcname)
|
|
|
|
]
|
|
|
|
|
2022-10-06 12:08:48 +03:00
|
|
|
all_samplers = [
|
2022-09-03 17:21:15 +03:00
|
|
|
*samplers_data_k_diffusion,
|
2022-10-06 14:12:52 +03:00
|
|
|
SamplerData('DDIM', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.ddim.DDIMSampler, model), [], {}),
|
|
|
|
SamplerData('PLMS', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.plms.PLMSSampler, model), [], {}),
|
2022-09-03 12:08:45 +03:00
|
|
|
]
|
2022-11-19 12:01:51 +03:00
|
|
|
all_samplers_map = {x.name: x for x in all_samplers}
|
2022-10-06 12:08:48 +03:00
|
|
|
|
|
|
|
samplers = []
|
|
|
|
samplers_for_img2img = []
|
|
|
|
|
|
|
|
|
2022-11-19 12:01:51 +03:00
|
|
|
def create_sampler(name, model):
|
|
|
|
if name is not None:
|
|
|
|
config = all_samplers_map.get(name, None)
|
|
|
|
else:
|
|
|
|
config = all_samplers[0]
|
|
|
|
|
|
|
|
assert config is not None, f'bad sampler name: {name}'
|
|
|
|
|
2022-10-06 14:12:52 +03:00
|
|
|
sampler = config.constructor(model)
|
|
|
|
sampler.config = config
|
2022-11-19 12:01:51 +03:00
|
|
|
|
2022-10-06 14:12:52 +03:00
|
|
|
return sampler
|
|
|
|
|
|
|
|
|
2022-10-06 12:08:48 +03:00
|
|
|
def set_samplers():
|
|
|
|
global samplers, samplers_for_img2img
|
|
|
|
|
|
|
|
hidden = set(opts.hide_samplers)
|
2022-10-11 02:02:44 +03:00
|
|
|
hidden_img2img = set(opts.hide_samplers + ['PLMS'])
|
2022-10-06 12:08:48 +03:00
|
|
|
|
|
|
|
samplers = [x for x in all_samplers if x.name not in hidden]
|
|
|
|
samplers_for_img2img = [x for x in all_samplers if x.name not in hidden_img2img]
|
|
|
|
|
|
|
|
|
|
|
|
set_samplers()
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-09-26 11:56:47 +03:00
|
|
|
sampler_extra_params = {
|
2022-09-28 10:49:07 +03:00
|
|
|
'sample_euler': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
|
|
|
|
'sample_heun': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
|
|
|
|
'sample_dpm_2': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
|
2022-09-26 11:56:47 +03:00
|
|
|
}
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-10-22 20:48:13 +03:00
|
|
|
|
2022-09-19 16:42:56 +03:00
|
|
|
def setup_img2img_steps(p, steps=None):
|
|
|
|
if opts.img2img_fix_steps or steps is not None:
|
|
|
|
steps = int((steps or p.steps) / min(p.denoising_strength, 0.999)) if p.denoising_strength > 0 else 0
|
2022-09-16 13:38:02 +03:00
|
|
|
t_enc = p.steps - 1
|
|
|
|
else:
|
|
|
|
steps = p.steps
|
|
|
|
t_enc = int(min(p.denoising_strength, 0.999) * steps)
|
|
|
|
|
|
|
|
return steps, t_enc
|
|
|
|
|
|
|
|
|
2022-10-22 20:48:13 +03:00
|
|
|
def single_sample_to_image(sample):
|
|
|
|
x_sample = processing.decode_first_stage(shared.sd_model, sample.unsqueeze(0))[0]
|
2022-09-06 23:10:12 +03:00
|
|
|
x_sample = torch.clamp((x_sample + 1.0) / 2.0, min=0.0, max=1.0)
|
|
|
|
x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2)
|
|
|
|
x_sample = x_sample.astype(np.uint8)
|
|
|
|
return Image.fromarray(x_sample)
|
|
|
|
|
2022-10-22 20:48:13 +03:00
|
|
|
|
2022-11-02 12:18:21 +03:00
|
|
|
def sample_to_image(samples, index=0):
|
|
|
|
return single_sample_to_image(samples[index])
|
2022-10-22 20:48:13 +03:00
|
|
|
|
2022-11-02 12:45:03 +03:00
|
|
|
|
2022-10-19 13:38:10 +03:00
|
|
|
def samples_to_image_grid(samples):
|
2022-10-22 20:48:13 +03:00
|
|
|
return images.image_grid([single_sample_to_image(sample) for sample in samples])
|
|
|
|
|
2022-09-06 23:10:12 +03:00
|
|
|
|
|
|
|
def store_latent(decoded):
|
|
|
|
state.current_latent = decoded
|
|
|
|
|
|
|
|
if opts.show_progress_every_n_steps > 0 and shared.state.sampling_step % opts.show_progress_every_n_steps == 0:
|
|
|
|
if not shared.parallel_processing_allowed:
|
|
|
|
shared.state.current_image = sample_to_image(decoded)
|
|
|
|
|
|
|
|
|
2022-10-18 17:23:38 +03:00
|
|
|
class InterruptedException(BaseException):
|
|
|
|
pass
|
2022-09-06 02:09:01 +03:00
|
|
|
|
|
|
|
|
2022-09-03 12:08:45 +03:00
|
|
|
class VanillaStableDiffusionSampler:
|
|
|
|
def __init__(self, constructor, sd_model):
|
|
|
|
self.sampler = constructor(sd_model)
|
2022-11-26 16:10:46 +03:00
|
|
|
self.is_plms = hasattr(self.sampler, 'p_sample_plms')
|
|
|
|
self.orig_p_sample_ddim = self.sampler.p_sample_plms if self.is_plms else self.sampler.p_sample_ddim
|
2022-09-03 12:08:45 +03:00
|
|
|
self.mask = None
|
|
|
|
self.nmask = None
|
|
|
|
self.init_latent = None
|
2022-09-13 21:49:58 +03:00
|
|
|
self.sampler_noises = None
|
2022-09-15 13:10:16 +03:00
|
|
|
self.step = 0
|
2022-10-18 17:23:38 +03:00
|
|
|
self.stop_at = None
|
2022-09-28 18:09:06 +03:00
|
|
|
self.eta = None
|
|
|
|
self.default_eta = 0.0
|
2022-10-06 14:12:52 +03:00
|
|
|
self.config = None
|
2022-10-18 17:23:38 +03:00
|
|
|
self.last_latent = None
|
2022-09-15 13:10:16 +03:00
|
|
|
|
2022-10-20 01:09:43 +03:00
|
|
|
self.conditioning_key = sd_model.model.conditioning_key
|
|
|
|
|
2022-09-13 21:49:58 +03:00
|
|
|
def number_of_needed_noises(self, p):
|
|
|
|
return 0
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-10-18 17:23:38 +03:00
|
|
|
def launch_sampling(self, steps, func):
|
|
|
|
state.sampling_steps = steps
|
|
|
|
state.sampling_step = 0
|
|
|
|
|
|
|
|
try:
|
|
|
|
return func()
|
|
|
|
except InterruptedException:
|
|
|
|
return self.last_latent
|
|
|
|
|
2022-09-15 13:10:16 +03:00
|
|
|
def p_sample_ddim_hook(self, x_dec, cond, ts, unconditional_conditioning, *args, **kwargs):
|
2022-10-18 17:23:38 +03:00
|
|
|
if state.interrupted or state.skipped:
|
|
|
|
raise InterruptedException
|
|
|
|
|
|
|
|
if self.stop_at is not None and self.step > self.stop_at:
|
|
|
|
raise InterruptedException
|
|
|
|
|
2022-10-20 19:45:03 +03:00
|
|
|
# Have to unwrap the inpainting conditioning here to perform pre-processing
|
2022-10-19 23:47:45 +03:00
|
|
|
image_conditioning = None
|
|
|
|
if isinstance(cond, dict):
|
|
|
|
image_conditioning = cond["c_concat"][0]
|
|
|
|
cond = cond["c_crossattn"][0]
|
|
|
|
unconditional_conditioning = unconditional_conditioning["c_crossattn"][0]
|
2022-10-18 17:23:38 +03:00
|
|
|
|
2022-10-05 23:16:27 +03:00
|
|
|
conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
|
2022-09-15 13:10:16 +03:00
|
|
|
unconditional_conditioning = prompt_parser.reconstruct_cond_batch(unconditional_conditioning, self.step)
|
|
|
|
|
2022-10-05 23:16:27 +03:00
|
|
|
assert all([len(conds) == 1 for conds in conds_list]), 'composition via AND is not supported for DDIM/PLMS samplers'
|
|
|
|
cond = tensor
|
|
|
|
|
2022-10-08 15:25:59 +03: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 13:10:16 +03:00
|
|
|
if self.mask is not None:
|
|
|
|
img_orig = self.sampler.model.q_sample(self.init_latent, ts)
|
|
|
|
x_dec = img_orig * self.mask + self.nmask * x_dec
|
|
|
|
|
2022-10-20 19:45:03 +03: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 23:47:45 +03:00
|
|
|
if image_conditioning is not None:
|
|
|
|
cond = {"c_concat": [image_conditioning], "c_crossattn": [cond]}
|
|
|
|
unconditional_conditioning = {"c_concat": [image_conditioning], "c_crossattn": [unconditional_conditioning]}
|
|
|
|
|
2022-09-15 13:10:16 +03:00
|
|
|
res = self.orig_p_sample_ddim(x_dec, cond, ts, unconditional_conditioning=unconditional_conditioning, *args, **kwargs)
|
|
|
|
|
|
|
|
if self.mask is not None:
|
2022-10-18 17:23:38 +03:00
|
|
|
self.last_latent = self.init_latent * self.mask + self.nmask * res[1]
|
2022-09-15 13:10:16 +03:00
|
|
|
else:
|
2022-10-18 17:23:38 +03:00
|
|
|
self.last_latent = res[1]
|
|
|
|
|
|
|
|
store_latent(self.last_latent)
|
2022-09-15 13:10:16 +03:00
|
|
|
|
|
|
|
self.step += 1
|
2022-10-18 17:23:38 +03:00
|
|
|
state.sampling_step = self.step
|
|
|
|
shared.total_tqdm.update()
|
|
|
|
|
2022-09-15 13:10:16 +03:00
|
|
|
return res
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-09-28 18:09:06 +03:00
|
|
|
def initialize(self, p):
|
2022-10-01 00:38:14 +03:00
|
|
|
self.eta = p.eta if p.eta is not None else opts.eta_ddim
|
2022-09-28 18:09:06 +03:00
|
|
|
|
|
|
|
for fieldname in ['p_sample_ddim', 'p_sample_plms']:
|
|
|
|
if hasattr(self.sampler, fieldname):
|
|
|
|
setattr(self.sampler, fieldname, self.p_sample_ddim_hook)
|
|
|
|
|
|
|
|
self.mask = p.mask if hasattr(p, 'mask') else None
|
|
|
|
self.nmask = p.nmask if hasattr(p, 'nmask') else None
|
|
|
|
|
2022-10-29 17:23:19 +03:00
|
|
|
def adjust_steps_if_invalid(self, p, num_steps):
|
2022-10-30 14:04:27 +03:00
|
|
|
if (self.config.name == 'DDIM' and p.ddim_discretize == 'uniform') or (self.config.name == 'PLMS'):
|
2022-10-29 17:23:19 +03:00
|
|
|
valid_step = 999 / (1000 // num_steps)
|
|
|
|
if valid_step == floor(valid_step):
|
|
|
|
return int(valid_step) + 1
|
|
|
|
|
|
|
|
return num_steps
|
|
|
|
|
2022-10-19 23:47:45 +03:00
|
|
|
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
|
2022-09-19 16:42:56 +03:00
|
|
|
steps, t_enc = setup_img2img_steps(p, steps)
|
2022-10-29 17:23:19 +03:00
|
|
|
steps = self.adjust_steps_if_invalid(p, steps)
|
2022-09-28 22:30:52 +03:00
|
|
|
self.initialize(p)
|
|
|
|
|
2022-10-29 17:23:19 +03:00
|
|
|
self.sampler.make_schedule(ddim_num_steps=steps, ddim_eta=self.eta, ddim_discretize=p.ddim_discretize, verbose=False)
|
2022-09-03 12:08:45 +03:00
|
|
|
x1 = self.sampler.stochastic_encode(x, torch.tensor([t_enc] * int(x.shape[0])).to(shared.device), noise=noise)
|
|
|
|
|
2022-09-19 16:42:56 +03:00
|
|
|
self.init_latent = x
|
2022-10-20 23:49:14 +03:00
|
|
|
self.last_latent = x
|
2022-09-16 08:51:21 +03:00
|
|
|
self.step = 0
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-10-20 00:14:24 +03:00
|
|
|
# Wrap the conditioning models with additional image conditioning for inpainting model
|
|
|
|
if image_conditioning is not None:
|
|
|
|
conditioning = {"c_concat": [image_conditioning], "c_crossattn": [conditioning]}
|
|
|
|
unconditional_conditioning = {"c_concat": [image_conditioning], "c_crossattn": [unconditional_conditioning]}
|
|
|
|
|
|
|
|
|
2022-10-21 17:46:32 +03: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 12:08:45 +03:00
|
|
|
|
|
|
|
return samples
|
|
|
|
|
2022-10-19 23:47:45 +03:00
|
|
|
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
|
2022-09-28 18:09:06 +03:00
|
|
|
self.initialize(p)
|
|
|
|
|
2022-09-08 19:20:41 +03:00
|
|
|
self.init_latent = None
|
2022-10-20 23:49:14 +03:00
|
|
|
self.last_latent = x
|
2022-09-16 08:51:21 +03:00
|
|
|
self.step = 0
|
2022-09-08 19:20:41 +03:00
|
|
|
|
2022-10-29 17:23:19 +03:00
|
|
|
steps = self.adjust_steps_if_invalid(p, steps or p.steps)
|
2022-09-19 16:42:56 +03:00
|
|
|
|
2022-10-19 23:47:45 +03:00
|
|
|
# Wrap the conditioning models with additional image conditioning for inpainting model
|
2022-11-26 16:10:46 +03:00
|
|
|
# dummy_for_plms is needed because PLMS code checks the first item in the dict to have the right shape
|
2022-10-19 23:47:45 +03:00
|
|
|
if image_conditioning is not None:
|
2022-11-26 16:10:46 +03:00
|
|
|
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 23:47:45 +03:00
|
|
|
|
2022-10-29 17:23:19 +03: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 20:12:24 +03:00
|
|
|
|
2022-09-03 12:08:45 +03:00
|
|
|
return samples_ddim
|
|
|
|
|
|
|
|
|
|
|
|
class CFGDenoiser(torch.nn.Module):
|
|
|
|
def __init__(self, model):
|
|
|
|
super().__init__()
|
|
|
|
self.inner_model = model
|
|
|
|
self.mask = None
|
|
|
|
self.nmask = None
|
|
|
|
self.init_latent = None
|
2022-09-15 13:10:16 +03:00
|
|
|
self.step = 0
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-10-19 23:47:45 +03:00
|
|
|
def forward(self, x, sigma, uncond, cond, cond_scale, image_cond):
|
2022-10-18 17:23:38 +03:00
|
|
|
if state.interrupted or state.skipped:
|
|
|
|
raise InterruptedException
|
|
|
|
|
2022-10-05 23:16:27 +03:00
|
|
|
conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
|
2022-09-15 13:10:16 +03:00
|
|
|
uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step)
|
|
|
|
|
2022-10-05 23:16:27 +03:00
|
|
|
batch_size = len(conds_list)
|
|
|
|
repeats = [len(conds_list[i]) for i in range(batch_size)]
|
|
|
|
|
|
|
|
x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x])
|
2022-10-19 23:47:45 +03:00
|
|
|
image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_cond])
|
2022-10-05 23:16:27 +03:00
|
|
|
sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma])
|
|
|
|
|
2022-11-02 03:38:17 +03:00
|
|
|
denoiser_params = CFGDenoiserParams(x_in, image_cond_in, sigma_in, state.sampling_step, state.sampling_steps)
|
|
|
|
cfg_denoiser_callback(denoiser_params)
|
|
|
|
x_in = denoiser_params.x
|
|
|
|
image_cond_in = denoiser_params.image_cond
|
|
|
|
sigma_in = denoiser_params.sigma
|
2022-10-31 02:48:33 +03:00
|
|
|
|
2022-10-08 15:25:59 +03:00
|
|
|
if tensor.shape[1] == uncond.shape[1]:
|
|
|
|
cond_in = torch.cat([tensor, uncond])
|
|
|
|
|
|
|
|
if shared.batch_cond_uncond:
|
2022-10-19 23:47:45 +03:00
|
|
|
x_out = self.inner_model(x_in, sigma_in, cond={"c_crossattn": [cond_in], "c_concat": [image_cond_in]})
|
2022-10-08 15:25:59 +03:00
|
|
|
else:
|
|
|
|
x_out = torch.zeros_like(x_in)
|
|
|
|
for batch_offset in range(0, x_out.shape[0], batch_size):
|
|
|
|
a = batch_offset
|
|
|
|
b = a + batch_size
|
2022-10-19 23:47:45 +03:00
|
|
|
x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond={"c_crossattn": [cond_in[a:b]], "c_concat": [image_cond_in[a:b]]})
|
2022-09-03 12:08:45 +03:00
|
|
|
else:
|
2022-10-05 23:16:27 +03:00
|
|
|
x_out = torch.zeros_like(x_in)
|
2022-10-08 15:25:59 +03:00
|
|
|
batch_size = batch_size*2 if shared.batch_cond_uncond else batch_size
|
|
|
|
for batch_offset in range(0, tensor.shape[0], batch_size):
|
2022-10-05 23:16:27 +03:00
|
|
|
a = batch_offset
|
2022-10-08 15:25:59 +03:00
|
|
|
b = min(a + batch_size, tensor.shape[0])
|
2022-10-19 23:47:45 +03:00
|
|
|
x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond={"c_crossattn": [tensor[a:b]], "c_concat": [image_cond_in[a:b]]})
|
2022-10-08 15:25:59 +03:00
|
|
|
|
2022-10-19 23:47:45 +03:00
|
|
|
x_out[-uncond.shape[0]:] = self.inner_model(x_in[-uncond.shape[0]:], sigma_in[-uncond.shape[0]:], cond={"c_crossattn": [uncond], "c_concat": [image_cond_in[-uncond.shape[0]:]]})
|
2022-10-05 23:16:27 +03:00
|
|
|
|
2022-10-08 15:25:59 +03:00
|
|
|
denoised_uncond = x_out[-uncond.shape[0]:]
|
2022-10-05 23:16:27 +03:00
|
|
|
denoised = torch.clone(denoised_uncond)
|
|
|
|
|
|
|
|
for i, conds in enumerate(conds_list):
|
|
|
|
for cond_index, weight in conds:
|
|
|
|
denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale)
|
2022-09-03 12:08:45 +03:00
|
|
|
|
|
|
|
if self.mask is not None:
|
|
|
|
denoised = self.init_latent * self.mask + self.nmask * denoised
|
|
|
|
|
2022-09-15 13:10:16 +03:00
|
|
|
self.step += 1
|
|
|
|
|
2022-09-03 12:08:45 +03:00
|
|
|
return denoised
|
|
|
|
|
|
|
|
|
2022-09-16 09:47:03 +03:00
|
|
|
class TorchHijack:
|
|
|
|
def __init__(self, kdiff_sampler):
|
|
|
|
self.kdiff_sampler = kdiff_sampler
|
|
|
|
|
|
|
|
def __getattr__(self, item):
|
|
|
|
if item == 'randn_like':
|
|
|
|
return self.kdiff_sampler.randn_like
|
|
|
|
|
|
|
|
if hasattr(torch, item):
|
|
|
|
return getattr(torch, item)
|
|
|
|
|
|
|
|
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, item))
|
|
|
|
|
2022-09-13 21:49:58 +03:00
|
|
|
|
2022-09-03 12:08:45 +03:00
|
|
|
class KDiffusionSampler:
|
|
|
|
def __init__(self, funcname, sd_model):
|
2022-11-26 16:10:46 +03:00
|
|
|
denoiser = k_diffusion.external.CompVisVDenoiser if sd_model.parameterization == "v" else k_diffusion.external.CompVisDenoiser
|
|
|
|
|
|
|
|
self.model_wrap = denoiser(sd_model, quantize=shared.opts.enable_quantization)
|
2022-09-03 12:08:45 +03:00
|
|
|
self.funcname = funcname
|
|
|
|
self.func = getattr(k_diffusion.sampling, self.funcname)
|
2022-09-28 10:49:07 +03:00
|
|
|
self.extra_params = sampler_extra_params.get(funcname, [])
|
2022-09-03 12:08:45 +03:00
|
|
|
self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
|
2022-09-13 21:49:58 +03:00
|
|
|
self.sampler_noises = None
|
|
|
|
self.sampler_noise_index = 0
|
2022-09-19 16:42:56 +03:00
|
|
|
self.stop_at = None
|
2022-09-28 18:09:06 +03:00
|
|
|
self.eta = None
|
|
|
|
self.default_eta = 1.0
|
2022-10-06 14:12:52 +03:00
|
|
|
self.config = None
|
2022-10-18 17:23:38 +03:00
|
|
|
self.last_latent = None
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-10-20 01:09:43 +03:00
|
|
|
self.conditioning_key = sd_model.model.conditioning_key
|
|
|
|
|
2022-09-06 19:33:51 +03:00
|
|
|
def callback_state(self, d):
|
2022-10-18 17:23:38 +03:00
|
|
|
step = d['i']
|
|
|
|
latent = d["denoised"]
|
|
|
|
store_latent(latent)
|
|
|
|
self.last_latent = latent
|
|
|
|
|
|
|
|
if self.stop_at is not None and step > self.stop_at:
|
|
|
|
raise InterruptedException
|
|
|
|
|
|
|
|
state.sampling_step = step
|
|
|
|
shared.total_tqdm.update()
|
|
|
|
|
|
|
|
def launch_sampling(self, steps, func):
|
|
|
|
state.sampling_steps = steps
|
|
|
|
state.sampling_step = 0
|
|
|
|
|
|
|
|
try:
|
|
|
|
return func()
|
|
|
|
except InterruptedException:
|
|
|
|
return self.last_latent
|
2022-09-06 19:33:51 +03:00
|
|
|
|
2022-09-13 21:49:58 +03:00
|
|
|
def number_of_needed_noises(self, p):
|
|
|
|
return p.steps
|
|
|
|
|
|
|
|
def randn_like(self, x):
|
|
|
|
noise = self.sampler_noises[self.sampler_noise_index] if self.sampler_noises is not None and self.sampler_noise_index < len(self.sampler_noises) else None
|
|
|
|
|
|
|
|
if noise is not None and x.shape == noise.shape:
|
|
|
|
res = noise
|
|
|
|
else:
|
2022-09-16 09:47:03 +03:00
|
|
|
res = torch.randn_like(x)
|
2022-09-13 21:49:58 +03:00
|
|
|
|
|
|
|
self.sampler_noise_index += 1
|
|
|
|
return res
|
|
|
|
|
2022-09-28 18:09:06 +03:00
|
|
|
def initialize(self, p):
|
2022-09-19 16:42:56 +03:00
|
|
|
self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None
|
|
|
|
self.model_wrap_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None
|
2022-09-16 08:51:21 +03:00
|
|
|
self.model_wrap.step = 0
|
2022-09-18 23:43:37 +03:00
|
|
|
self.sampler_noise_index = 0
|
2022-09-28 18:09:06 +03:00
|
|
|
self.eta = p.eta or opts.eta_ancestral
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-09-16 09:47:03 +03:00
|
|
|
if self.sampler_noises is not None:
|
|
|
|
k_diffusion.sampling.torch = TorchHijack(self)
|
|
|
|
|
2022-09-26 11:56:47 +03:00
|
|
|
extra_params_kwargs = {}
|
2022-09-28 10:49:07 +03:00
|
|
|
for param_name in self.extra_params:
|
|
|
|
if hasattr(p, param_name) and param_name in inspect.signature(self.func).parameters:
|
|
|
|
extra_params_kwargs[param_name] = getattr(p, param_name)
|
2022-09-26 11:56:47 +03:00
|
|
|
|
2022-09-28 18:09:06 +03:00
|
|
|
if 'eta' in inspect.signature(self.func).parameters:
|
|
|
|
extra_params_kwargs['eta'] = self.eta
|
|
|
|
|
|
|
|
return extra_params_kwargs
|
|
|
|
|
2022-10-19 23:47:45 +03:00
|
|
|
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
|
2022-09-28 18:09:06 +03:00
|
|
|
steps, t_enc = setup_img2img_steps(p, steps)
|
|
|
|
|
2022-09-30 03:46:06 +03:00
|
|
|
if p.sampler_noise_scheduler_override:
|
2022-10-06 23:27:01 +03:00
|
|
|
sigmas = p.sampler_noise_scheduler_override(steps)
|
|
|
|
elif self.config is not None and self.config.options.get('scheduler', None) == 'karras':
|
|
|
|
sigmas = k_diffusion.sampling.get_sigmas_karras(n=steps, sigma_min=0.1, sigma_max=10, device=shared.device)
|
2022-09-30 03:46:06 +03:00
|
|
|
else:
|
2022-10-06 23:27:01 +03:00
|
|
|
sigmas = self.model_wrap.get_sigmas(steps)
|
2022-09-28 18:09:06 +03:00
|
|
|
|
|
|
|
sigma_sched = sigmas[steps - t_enc - 1:]
|
2022-10-11 02:02:44 +03:00
|
|
|
xi = x + noise * sigma_sched[0]
|
|
|
|
|
|
|
|
extra_params_kwargs = self.initialize(p)
|
|
|
|
if 'sigma_min' in inspect.signature(self.func).parameters:
|
2022-10-11 02:36:00 +03:00
|
|
|
## last sigma is zero which isn't allowed by DPM Fast & Adaptive so taking value before last
|
2022-10-11 02:02:44 +03:00
|
|
|
extra_params_kwargs['sigma_min'] = sigma_sched[-2]
|
|
|
|
if 'sigma_max' in inspect.signature(self.func).parameters:
|
|
|
|
extra_params_kwargs['sigma_max'] = sigma_sched[0]
|
|
|
|
if 'n' in inspect.signature(self.func).parameters:
|
|
|
|
extra_params_kwargs['n'] = len(sigma_sched) - 1
|
|
|
|
if 'sigma_sched' in inspect.signature(self.func).parameters:
|
|
|
|
extra_params_kwargs['sigma_sched'] = sigma_sched
|
|
|
|
if 'sigmas' in inspect.signature(self.func).parameters:
|
|
|
|
extra_params_kwargs['sigmas'] = sigma_sched
|
2022-09-28 18:09:06 +03:00
|
|
|
|
|
|
|
self.model_wrap_cfg.init_latent = x
|
2022-10-20 23:49:14 +03:00
|
|
|
self.last_latent = x
|
2022-09-28 18:09:06 +03:00
|
|
|
|
2022-10-21 17:46:32 +03:00
|
|
|
samples = self.launch_sampling(t_enc + 1, lambda: self.func(self.model_wrap_cfg, xi, extra_args={
|
2022-10-19 23:47:45 +03:00
|
|
|
'cond': conditioning,
|
|
|
|
'image_cond': image_conditioning,
|
|
|
|
'uncond': unconditional_conditioning,
|
|
|
|
'cond_scale': p.cfg_scale
|
|
|
|
}, disable=False, callback=self.callback_state, **extra_params_kwargs))
|
2022-10-11 02:02:44 +03:00
|
|
|
|
2022-10-18 17:23:38 +03:00
|
|
|
return samples
|
2022-09-03 12:08:45 +03:00
|
|
|
|
2022-10-19 23:47:45 +03:00
|
|
|
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning = None):
|
2022-09-19 16:42:56 +03:00
|
|
|
steps = steps or p.steps
|
|
|
|
|
2022-09-30 03:46:06 +03:00
|
|
|
if p.sampler_noise_scheduler_override:
|
2022-10-06 14:12:52 +03:00
|
|
|
sigmas = p.sampler_noise_scheduler_override(steps)
|
|
|
|
elif self.config is not None and self.config.options.get('scheduler', None) == 'karras':
|
|
|
|
sigmas = k_diffusion.sampling.get_sigmas_karras(n=steps, sigma_min=0.1, sigma_max=10, device=shared.device)
|
2022-09-30 03:46:06 +03:00
|
|
|
else:
|
2022-10-06 14:12:52 +03:00
|
|
|
sigmas = self.model_wrap.get_sigmas(steps)
|
|
|
|
|
2022-09-03 12:08:45 +03:00
|
|
|
x = x * sigmas[0]
|
|
|
|
|
2022-09-28 18:09:06 +03:00
|
|
|
extra_params_kwargs = self.initialize(p)
|
2022-09-29 10:15:38 +03:00
|
|
|
if 'sigma_min' in inspect.signature(self.func).parameters:
|
2022-09-29 13:30:33 +03:00
|
|
|
extra_params_kwargs['sigma_min'] = self.model_wrap.sigmas[0].item()
|
|
|
|
extra_params_kwargs['sigma_max'] = self.model_wrap.sigmas[-1].item()
|
2022-09-29 10:15:38 +03:00
|
|
|
if 'n' in inspect.signature(self.func).parameters:
|
2022-09-29 13:30:33 +03:00
|
|
|
extra_params_kwargs['n'] = steps
|
|
|
|
else:
|
|
|
|
extra_params_kwargs['sigmas'] = sigmas
|
2022-10-18 17:23:38 +03:00
|
|
|
|
2022-10-20 23:49:14 +03:00
|
|
|
self.last_latent = x
|
2022-10-19 23:47:45 +03:00
|
|
|
samples = self.launch_sampling(steps, lambda: self.func(self.model_wrap_cfg, x, extra_args={
|
|
|
|
'cond': conditioning,
|
|
|
|
'image_cond': image_conditioning,
|
|
|
|
'uncond': unconditional_conditioning,
|
|
|
|
'cond_scale': p.cfg_scale
|
|
|
|
}, disable=False, callback=self.callback_state, **extra_params_kwargs))
|
2022-10-18 17:23:38 +03:00
|
|
|
|
2022-09-19 16:42:56 +03:00
|
|
|
return samples
|
2022-09-03 12:08:45 +03:00
|
|
|
|