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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import deque
|
| 2 |
+
import torch
|
| 3 |
+
import inspect
|
| 4 |
+
import k_diffusion.sampling
|
| 5 |
+
from modules import prompt_parser, devices, sd_samplers_common
|
| 6 |
+
|
| 7 |
+
from modules.shared import opts, state
|
| 8 |
+
import modules.shared as shared
|
| 9 |
+
from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback
|
| 10 |
+
from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback
|
| 11 |
+
from modules.script_callbacks import AfterCFGCallbackParams, cfg_after_cfg_callback
|
| 12 |
+
|
| 13 |
+
samplers_k_diffusion = [
|
| 14 |
+
('Euler a', 'sample_euler_ancestral', ['k_euler_a', 'k_euler_ancestral'], {"uses_ensd": True}),
|
| 15 |
+
('Euler', 'sample_euler', ['k_euler'], {}),
|
| 16 |
+
('LMS', 'sample_lms', ['k_lms'], {}),
|
| 17 |
+
('Heun', 'sample_heun', ['k_heun'], {"second_order": True}),
|
| 18 |
+
('DPM2', 'sample_dpm_2', ['k_dpm_2'], {'discard_next_to_last_sigma': True}),
|
| 19 |
+
('DPM2 a', 'sample_dpm_2_ancestral', ['k_dpm_2_a'], {'discard_next_to_last_sigma': True, "uses_ensd": True}),
|
| 20 |
+
('DPM++ 2S a', 'sample_dpmpp_2s_ancestral', ['k_dpmpp_2s_a'], {"uses_ensd": True, "second_order": True}),
|
| 21 |
+
('DPM++ 2M', 'sample_dpmpp_2m', ['k_dpmpp_2m'], {}),
|
| 22 |
+
('DPM++ SDE', 'sample_dpmpp_sde', ['k_dpmpp_sde'], {"second_order": True, "brownian_noise": True}),
|
| 23 |
+
('DPM++ 2M SDE', 'sample_dpmpp_2m_sde', ['k_dpmpp_2m_sde_ka'], {"brownian_noise": True, 'discard_next_to_last_sigma': True}),
|
| 24 |
+
('DPM fast', 'sample_dpm_fast', ['k_dpm_fast'], {"uses_ensd": True}),
|
| 25 |
+
('DPM adaptive', 'sample_dpm_adaptive', ['k_dpm_ad'], {"uses_ensd": True}),
|
| 26 |
+
('LMS Karras', 'sample_lms', ['k_lms_ka'], {'scheduler': 'karras'}),
|
| 27 |
+
('DPM2 Karras', 'sample_dpm_2', ['k_dpm_2_ka'], {'scheduler': 'karras', 'discard_next_to_last_sigma': True, "uses_ensd": True, "second_order": True}),
|
| 28 |
+
('DPM2 a Karras', 'sample_dpm_2_ancestral', ['k_dpm_2_a_ka'], {'scheduler': 'karras', 'discard_next_to_last_sigma': True, "uses_ensd": True, "second_order": True}),
|
| 29 |
+
('DPM++ 2S a Karras', 'sample_dpmpp_2s_ancestral', ['k_dpmpp_2s_a_ka'], {'scheduler': 'karras', "uses_ensd": True, "second_order": True}),
|
| 30 |
+
('DPM++ 2M Karras', 'sample_dpmpp_2m', ['k_dpmpp_2m_ka'], {'scheduler': 'karras'}),
|
| 31 |
+
('DPM++ SDE Karras', 'sample_dpmpp_sde', ['k_dpmpp_sde_ka'], {'scheduler': 'karras', "second_order": True, "brownian_noise": True}),
|
| 32 |
+
('DPM++ 2M SDE Karras', 'sample_dpmpp_2m_sde', ['k_dpmpp_2m_sde_ka'], {'scheduler': 'karras', "brownian_noise": True, 'discard_next_to_last_sigma': True}),
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
samplers_data_k_diffusion = [
|
| 36 |
+
sd_samplers_common.SamplerData(label, lambda model, funcname=funcname: KDiffusionSampler(funcname, model), aliases, options)
|
| 37 |
+
for label, funcname, aliases, options in samplers_k_diffusion
|
| 38 |
+
if hasattr(k_diffusion.sampling, funcname)
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
from tqdm.auto import trange
|
| 42 |
+
|
| 43 |
+
@torch.no_grad()
|
| 44 |
+
def sample_dpmpp_2m_alt(model, x, sigmas, extra_args=None, callback=None, disable=None):
|
| 45 |
+
"""DPM-Solver++(2M)."""
|
| 46 |
+
extra_args = {} if extra_args is None else extra_args
|
| 47 |
+
s_in = x.new_ones([x.shape[0]])
|
| 48 |
+
sigma_fn = lambda t: t.neg().exp()
|
| 49 |
+
t_fn = lambda sigma: sigma.log().neg()
|
| 50 |
+
old_denoised = None
|
| 51 |
+
|
| 52 |
+
for i in trange(len(sigmas) - 1, disable=disable):
|
| 53 |
+
denoised = model(x, sigmas[i] * s_in, **extra_args)
|
| 54 |
+
if callback is not None:
|
| 55 |
+
callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
|
| 56 |
+
t, t_next = t_fn(sigmas[i]), t_fn(sigmas[i + 1])
|
| 57 |
+
h = t_next - t
|
| 58 |
+
if old_denoised is None or sigmas[i + 1] == 0:
|
| 59 |
+
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised
|
| 60 |
+
else:
|
| 61 |
+
h_last = t - t_fn(sigmas[i - 1])
|
| 62 |
+
r = h_last / h
|
| 63 |
+
denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised
|
| 64 |
+
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_d
|
| 65 |
+
sigma_progress = i / len(sigmas)
|
| 66 |
+
adjustment_factor = 1 + (0.15 * (sigma_progress * sigma_progress))
|
| 67 |
+
old_denoised = denoised * adjustment_factor
|
| 68 |
+
return x
|
| 69 |
+
|
| 70 |
+
k_diffusion.sampling.sample_dpmpp_2m_alt = sample_dpmpp_2m_alt
|
| 71 |
+
|
| 72 |
+
samplers_data_k_diffusion.insert(9, sd_samplers_common.SamplerData('DPM++ 2M alt', lambda model: KDiffusionSampler('sample_dpmpp_2m_alt', model), ['k_dpmpp_2m_alt'], {}))
|
| 73 |
+
samplers_data_k_diffusion.insert(10, sd_samplers_common.SamplerData('DPM++ 2M alt Karras', lambda model: KDiffusionSampler('sample_dpmpp_2m_alt', model), ['k_dpmpp_2m_alt_ka'], {'scheduler': 'karras'}))
|
| 74 |
+
|
| 75 |
+
sampler_extra_params = {
|
| 76 |
+
'sample_euler': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
|
| 77 |
+
'sample_heun': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
|
| 78 |
+
'sample_dpm_2': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class CFGDenoiser(torch.nn.Module):
|
| 83 |
+
"""
|
| 84 |
+
Classifier free guidance denoiser. A wrapper for stable diffusion model (specifically for unet)
|
| 85 |
+
that can take a noisy picture and produce a noise-free picture using two guidances (prompts)
|
| 86 |
+
instead of one. Originally, the second prompt is just an empty string, but we use non-empty
|
| 87 |
+
negative prompt.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
def __init__(self, model):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.inner_model = model
|
| 93 |
+
self.mask = None
|
| 94 |
+
self.nmask = None
|
| 95 |
+
self.init_latent = None
|
| 96 |
+
self.step = 0
|
| 97 |
+
self.image_cfg_scale = None
|
| 98 |
+
|
| 99 |
+
def combine_denoised(self, x_out, conds_list, uncond, cond_scale):
|
| 100 |
+
denoised_uncond = x_out[-uncond.shape[0]:]
|
| 101 |
+
denoised = torch.clone(denoised_uncond)
|
| 102 |
+
|
| 103 |
+
for i, conds in enumerate(conds_list):
|
| 104 |
+
for cond_index, weight in conds:
|
| 105 |
+
denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale)
|
| 106 |
+
|
| 107 |
+
return denoised
|
| 108 |
+
|
| 109 |
+
def combine_denoised_for_edit_model(self, x_out, cond_scale):
|
| 110 |
+
out_cond, out_img_cond, out_uncond = x_out.chunk(3)
|
| 111 |
+
denoised = out_uncond + cond_scale * (out_cond - out_img_cond) + self.image_cfg_scale * (out_img_cond - out_uncond)
|
| 112 |
+
|
| 113 |
+
return denoised
|
| 114 |
+
|
| 115 |
+
def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond):
|
| 116 |
+
if state.interrupted or state.skipped:
|
| 117 |
+
raise sd_samplers_common.InterruptedException
|
| 118 |
+
|
| 119 |
+
# at self.image_cfg_scale == 1.0 produced results for edit model are the same as with normal sampling,
|
| 120 |
+
# so is_edit_model is set to False to support AND composition.
|
| 121 |
+
is_edit_model = shared.sd_model.cond_stage_key == "edit" and self.image_cfg_scale is not None and self.image_cfg_scale != 1.0
|
| 122 |
+
|
| 123 |
+
conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
|
| 124 |
+
uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step)
|
| 125 |
+
|
| 126 |
+
assert not is_edit_model or all(len(conds) == 1 for conds in conds_list), "AND is not supported for InstructPix2Pix checkpoint (unless using Image CFG scale = 1.0)"
|
| 127 |
+
|
| 128 |
+
batch_size = len(conds_list)
|
| 129 |
+
repeats = [len(conds_list[i]) for i in range(batch_size)]
|
| 130 |
+
|
| 131 |
+
if shared.sd_model.model.conditioning_key == "crossattn-adm":
|
| 132 |
+
image_uncond = torch.zeros_like(image_cond)
|
| 133 |
+
make_condition_dict = lambda c_crossattn, c_adm: {"c_crossattn": c_crossattn, "c_adm": c_adm}
|
| 134 |
+
else:
|
| 135 |
+
image_uncond = image_cond
|
| 136 |
+
make_condition_dict = lambda c_crossattn, c_concat: {"c_crossattn": c_crossattn, "c_concat": [c_concat]}
|
| 137 |
+
|
| 138 |
+
if not is_edit_model:
|
| 139 |
+
x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x])
|
| 140 |
+
sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma])
|
| 141 |
+
image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond])
|
| 142 |
+
else:
|
| 143 |
+
x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x] + [x])
|
| 144 |
+
sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma] + [sigma])
|
| 145 |
+
image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond] + [torch.zeros_like(self.init_latent)])
|
| 146 |
+
|
| 147 |
+
denoiser_params = CFGDenoiserParams(x_in, image_cond_in, sigma_in, state.sampling_step, state.sampling_steps, tensor, uncond)
|
| 148 |
+
cfg_denoiser_callback(denoiser_params)
|
| 149 |
+
x_in = denoiser_params.x
|
| 150 |
+
image_cond_in = denoiser_params.image_cond
|
| 151 |
+
sigma_in = denoiser_params.sigma
|
| 152 |
+
tensor = denoiser_params.text_cond
|
| 153 |
+
uncond = denoiser_params.text_uncond
|
| 154 |
+
skip_uncond = False
|
| 155 |
+
|
| 156 |
+
# alternating uncond allows for higher thresholds without the quality loss normally expected from raising it
|
| 157 |
+
if self.step % 2 and s_min_uncond > 0 and sigma[0] < s_min_uncond and not is_edit_model:
|
| 158 |
+
skip_uncond = True
|
| 159 |
+
x_in = x_in[:-batch_size]
|
| 160 |
+
sigma_in = sigma_in[:-batch_size]
|
| 161 |
+
|
| 162 |
+
if tensor.shape[1] == uncond.shape[1] or skip_uncond:
|
| 163 |
+
if is_edit_model:
|
| 164 |
+
cond_in = torch.cat([tensor, uncond, uncond])
|
| 165 |
+
elif skip_uncond:
|
| 166 |
+
cond_in = tensor
|
| 167 |
+
else:
|
| 168 |
+
cond_in = torch.cat([tensor, uncond])
|
| 169 |
+
|
| 170 |
+
if shared.batch_cond_uncond:
|
| 171 |
+
x_out = self.inner_model(x_in, sigma_in, cond=make_condition_dict([cond_in], image_cond_in))
|
| 172 |
+
else:
|
| 173 |
+
x_out = torch.zeros_like(x_in)
|
| 174 |
+
for batch_offset in range(0, x_out.shape[0], batch_size):
|
| 175 |
+
a = batch_offset
|
| 176 |
+
b = a + batch_size
|
| 177 |
+
x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict([cond_in[a:b]], image_cond_in[a:b]))
|
| 178 |
+
else:
|
| 179 |
+
x_out = torch.zeros_like(x_in)
|
| 180 |
+
batch_size = batch_size*2 if shared.batch_cond_uncond else batch_size
|
| 181 |
+
for batch_offset in range(0, tensor.shape[0], batch_size):
|
| 182 |
+
a = batch_offset
|
| 183 |
+
b = min(a + batch_size, tensor.shape[0])
|
| 184 |
+
|
| 185 |
+
if not is_edit_model:
|
| 186 |
+
c_crossattn = [tensor[a:b]]
|
| 187 |
+
else:
|
| 188 |
+
c_crossattn = torch.cat([tensor[a:b]], uncond)
|
| 189 |
+
|
| 190 |
+
x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(c_crossattn, image_cond_in[a:b]))
|
| 191 |
+
|
| 192 |
+
if not skip_uncond:
|
| 193 |
+
x_out[-uncond.shape[0]:] = self.inner_model(x_in[-uncond.shape[0]:], sigma_in[-uncond.shape[0]:], cond=make_condition_dict([uncond], image_cond_in[-uncond.shape[0]:]))
|
| 194 |
+
|
| 195 |
+
denoised_image_indexes = [x[0][0] for x in conds_list]
|
| 196 |
+
if skip_uncond:
|
| 197 |
+
fake_uncond = torch.cat([x_out[i:i+1] for i in denoised_image_indexes])
|
| 198 |
+
x_out = torch.cat([x_out, fake_uncond]) # we skipped uncond denoising, so we put cond-denoised image to where the uncond-denoised image should be
|
| 199 |
+
|
| 200 |
+
denoised_params = CFGDenoisedParams(x_out, state.sampling_step, state.sampling_steps, self.inner_model)
|
| 201 |
+
cfg_denoised_callback(denoised_params)
|
| 202 |
+
|
| 203 |
+
devices.test_for_nans(x_out, "unet")
|
| 204 |
+
|
| 205 |
+
if opts.live_preview_content == "Prompt":
|
| 206 |
+
sd_samplers_common.store_latent(torch.cat([x_out[i:i+1] for i in denoised_image_indexes]))
|
| 207 |
+
elif opts.live_preview_content == "Negative prompt":
|
| 208 |
+
sd_samplers_common.store_latent(x_out[-uncond.shape[0]:])
|
| 209 |
+
|
| 210 |
+
if is_edit_model:
|
| 211 |
+
denoised = self.combine_denoised_for_edit_model(x_out, cond_scale)
|
| 212 |
+
elif skip_uncond:
|
| 213 |
+
denoised = self.combine_denoised(x_out, conds_list, uncond, 1.0)
|
| 214 |
+
else:
|
| 215 |
+
denoised = self.combine_denoised(x_out, conds_list, uncond, cond_scale)
|
| 216 |
+
|
| 217 |
+
if self.mask is not None:
|
| 218 |
+
denoised = self.init_latent * self.mask + self.nmask * denoised
|
| 219 |
+
|
| 220 |
+
after_cfg_callback_params = AfterCFGCallbackParams(denoised, state.sampling_step, state.sampling_steps)
|
| 221 |
+
cfg_after_cfg_callback(after_cfg_callback_params)
|
| 222 |
+
denoised = after_cfg_callback_params.x
|
| 223 |
+
|
| 224 |
+
self.step += 1
|
| 225 |
+
return denoised
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class TorchHijack:
|
| 229 |
+
def __init__(self, sampler_noises):
|
| 230 |
+
# Using a deque to efficiently receive the sampler_noises in the same order as the previous index-based
|
| 231 |
+
# implementation.
|
| 232 |
+
self.sampler_noises = deque(sampler_noises)
|
| 233 |
+
|
| 234 |
+
def __getattr__(self, item):
|
| 235 |
+
if item == 'randn_like':
|
| 236 |
+
return self.randn_like
|
| 237 |
+
|
| 238 |
+
if hasattr(torch, item):
|
| 239 |
+
return getattr(torch, item)
|
| 240 |
+
|
| 241 |
+
raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'")
|
| 242 |
+
|
| 243 |
+
def randn_like(self, x):
|
| 244 |
+
if self.sampler_noises:
|
| 245 |
+
noise = self.sampler_noises.popleft()
|
| 246 |
+
if noise.shape == x.shape:
|
| 247 |
+
return noise
|
| 248 |
+
|
| 249 |
+
if opts.randn_source == "CPU" or x.device.type == 'mps':
|
| 250 |
+
return torch.randn_like(x, device=devices.cpu).to(x.device)
|
| 251 |
+
else:
|
| 252 |
+
return torch.randn_like(x)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class KDiffusionSampler:
|
| 256 |
+
def __init__(self, funcname, sd_model):
|
| 257 |
+
denoiser = k_diffusion.external.CompVisVDenoiser if sd_model.parameterization == "v" else k_diffusion.external.CompVisDenoiser
|
| 258 |
+
|
| 259 |
+
self.model_wrap = denoiser(sd_model, quantize=shared.opts.enable_quantization)
|
| 260 |
+
self.funcname = funcname
|
| 261 |
+
self.func = getattr(k_diffusion.sampling, self.funcname)
|
| 262 |
+
self.extra_params = sampler_extra_params.get(funcname, [])
|
| 263 |
+
self.model_wrap_cfg = CFGDenoiser(self.model_wrap)
|
| 264 |
+
self.sampler_noises = None
|
| 265 |
+
self.stop_at = None
|
| 266 |
+
self.eta = None
|
| 267 |
+
self.config = None # set by the function calling the constructor
|
| 268 |
+
self.last_latent = None
|
| 269 |
+
self.s_min_uncond = None
|
| 270 |
+
|
| 271 |
+
self.conditioning_key = sd_model.model.conditioning_key
|
| 272 |
+
|
| 273 |
+
def callback_state(self, d):
|
| 274 |
+
step = d['i']
|
| 275 |
+
latent = d["denoised"]
|
| 276 |
+
if opts.live_preview_content == "Combined":
|
| 277 |
+
sd_samplers_common.store_latent(latent)
|
| 278 |
+
self.last_latent = latent
|
| 279 |
+
|
| 280 |
+
if self.stop_at is not None and step > self.stop_at:
|
| 281 |
+
raise sd_samplers_common.InterruptedException
|
| 282 |
+
|
| 283 |
+
state.sampling_step = step
|
| 284 |
+
shared.total_tqdm.update()
|
| 285 |
+
|
| 286 |
+
def launch_sampling(self, steps, func):
|
| 287 |
+
state.sampling_steps = steps
|
| 288 |
+
state.sampling_step = 0
|
| 289 |
+
|
| 290 |
+
try:
|
| 291 |
+
return func()
|
| 292 |
+
except sd_samplers_common.InterruptedException:
|
| 293 |
+
return self.last_latent
|
| 294 |
+
|
| 295 |
+
def number_of_needed_noises(self, p):
|
| 296 |
+
return p.steps
|
| 297 |
+
|
| 298 |
+
def initialize(self, p):
|
| 299 |
+
self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None
|
| 300 |
+
self.model_wrap_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None
|
| 301 |
+
self.model_wrap_cfg.step = 0
|
| 302 |
+
self.model_wrap_cfg.image_cfg_scale = getattr(p, 'image_cfg_scale', None)
|
| 303 |
+
self.eta = p.eta if p.eta is not None else opts.eta_ancestral
|
| 304 |
+
self.s_min_uncond = getattr(p, 's_min_uncond', 0.0)
|
| 305 |
+
|
| 306 |
+
k_diffusion.sampling.torch = TorchHijack(self.sampler_noises if self.sampler_noises is not None else [])
|
| 307 |
+
|
| 308 |
+
extra_params_kwargs = {}
|
| 309 |
+
for param_name in self.extra_params:
|
| 310 |
+
if hasattr(p, param_name) and param_name in inspect.signature(self.func).parameters:
|
| 311 |
+
extra_params_kwargs[param_name] = getattr(p, param_name)
|
| 312 |
+
|
| 313 |
+
if 'eta' in inspect.signature(self.func).parameters:
|
| 314 |
+
if self.eta != 1.0:
|
| 315 |
+
p.extra_generation_params["Eta"] = self.eta
|
| 316 |
+
|
| 317 |
+
extra_params_kwargs['eta'] = self.eta
|
| 318 |
+
|
| 319 |
+
return extra_params_kwargs
|
| 320 |
+
|
| 321 |
+
def get_sigmas(self, p, steps):
|
| 322 |
+
discard_next_to_last_sigma = self.config is not None and self.config.options.get('discard_next_to_last_sigma', False)
|
| 323 |
+
if opts.always_discard_next_to_last_sigma and not discard_next_to_last_sigma:
|
| 324 |
+
discard_next_to_last_sigma = True
|
| 325 |
+
p.extra_generation_params["Discard penultimate sigma"] = True
|
| 326 |
+
|
| 327 |
+
steps += 1 if discard_next_to_last_sigma else 0
|
| 328 |
+
|
| 329 |
+
if p.sampler_noise_scheduler_override:
|
| 330 |
+
sigmas = p.sampler_noise_scheduler_override(steps)
|
| 331 |
+
elif self.config is not None and self.config.options.get('scheduler', None) == 'karras':
|
| 332 |
+
sigma_min, sigma_max = (0.1, 10) if opts.use_old_karras_scheduler_sigmas else (self.model_wrap.sigmas[0].item(), self.model_wrap.sigmas[-1].item())
|
| 333 |
+
|
| 334 |
+
sigmas = k_diffusion.sampling.get_sigmas_karras(n=steps, sigma_min=sigma_min, sigma_max=sigma_max, device=shared.device)
|
| 335 |
+
else:
|
| 336 |
+
sigmas = self.model_wrap.get_sigmas(steps)
|
| 337 |
+
|
| 338 |
+
if discard_next_to_last_sigma:
|
| 339 |
+
sigmas = torch.cat([sigmas[:-2], sigmas[-1:]])
|
| 340 |
+
|
| 341 |
+
return sigmas
|
| 342 |
+
|
| 343 |
+
def create_noise_sampler(self, x, sigmas, p):
|
| 344 |
+
"""For DPM++ SDE: manually create noise sampler to enable deterministic results across different batch sizes"""
|
| 345 |
+
if shared.opts.no_dpmpp_sde_batch_determinism:
|
| 346 |
+
return None
|
| 347 |
+
|
| 348 |
+
from k_diffusion.sampling import BrownianTreeNoiseSampler
|
| 349 |
+
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
| 350 |
+
current_iter_seeds = p.all_seeds[p.iteration * p.batch_size:(p.iteration + 1) * p.batch_size]
|
| 351 |
+
return BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=current_iter_seeds)
|
| 352 |
+
|
| 353 |
+
def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
|
| 354 |
+
steps, t_enc = sd_samplers_common.setup_img2img_steps(p, steps)
|
| 355 |
+
|
| 356 |
+
sigmas = self.get_sigmas(p, steps)
|
| 357 |
+
|
| 358 |
+
sigma_sched = sigmas[steps - t_enc - 1:]
|
| 359 |
+
xi = x + noise * sigma_sched[0]
|
| 360 |
+
|
| 361 |
+
extra_params_kwargs = self.initialize(p)
|
| 362 |
+
parameters = inspect.signature(self.func).parameters
|
| 363 |
+
|
| 364 |
+
if 'sigma_min' in parameters:
|
| 365 |
+
## last sigma is zero which isn't allowed by DPM Fast & Adaptive so taking value before last
|
| 366 |
+
extra_params_kwargs['sigma_min'] = sigma_sched[-2]
|
| 367 |
+
if 'sigma_max' in parameters:
|
| 368 |
+
extra_params_kwargs['sigma_max'] = sigma_sched[0]
|
| 369 |
+
if 'n' in parameters:
|
| 370 |
+
extra_params_kwargs['n'] = len(sigma_sched) - 1
|
| 371 |
+
if 'sigma_sched' in parameters:
|
| 372 |
+
extra_params_kwargs['sigma_sched'] = sigma_sched
|
| 373 |
+
if 'sigmas' in parameters:
|
| 374 |
+
extra_params_kwargs['sigmas'] = sigma_sched
|
| 375 |
+
|
| 376 |
+
if self.config.options.get('brownian_noise', False):
|
| 377 |
+
noise_sampler = self.create_noise_sampler(x, sigmas, p)
|
| 378 |
+
extra_params_kwargs['noise_sampler'] = noise_sampler
|
| 379 |
+
|
| 380 |
+
self.model_wrap_cfg.init_latent = x
|
| 381 |
+
self.last_latent = x
|
| 382 |
+
extra_args = {
|
| 383 |
+
'cond': conditioning,
|
| 384 |
+
'image_cond': image_conditioning,
|
| 385 |
+
'uncond': unconditional_conditioning,
|
| 386 |
+
'cond_scale': p.cfg_scale,
|
| 387 |
+
's_min_uncond': self.s_min_uncond
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
samples = self.launch_sampling(t_enc + 1, lambda: self.func(self.model_wrap_cfg, xi, extra_args=extra_args, disable=False, callback=self.callback_state, **extra_params_kwargs))
|
| 391 |
+
|
| 392 |
+
return samples
|
| 393 |
+
|
| 394 |
+
def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
|
| 395 |
+
steps = steps or p.steps
|
| 396 |
+
|
| 397 |
+
sigmas = self.get_sigmas(p, steps)
|
| 398 |
+
|
| 399 |
+
x = x * sigmas[0]
|
| 400 |
+
|
| 401 |
+
extra_params_kwargs = self.initialize(p)
|
| 402 |
+
parameters = inspect.signature(self.func).parameters
|
| 403 |
+
|
| 404 |
+
if 'sigma_min' in parameters:
|
| 405 |
+
extra_params_kwargs['sigma_min'] = self.model_wrap.sigmas[0].item()
|
| 406 |
+
extra_params_kwargs['sigma_max'] = self.model_wrap.sigmas[-1].item()
|
| 407 |
+
if 'n' in parameters:
|
| 408 |
+
extra_params_kwargs['n'] = steps
|
| 409 |
+
else:
|
| 410 |
+
extra_params_kwargs['sigmas'] = sigmas
|
| 411 |
+
|
| 412 |
+
if self.config.options.get('brownian_noise', False):
|
| 413 |
+
noise_sampler = self.create_noise_sampler(x, sigmas, p)
|
| 414 |
+
extra_params_kwargs['noise_sampler'] = noise_sampler
|
| 415 |
+
|
| 416 |
+
self.last_latent = x
|
| 417 |
+
samples = self.launch_sampling(steps, lambda: self.func(self.model_wrap_cfg, x, extra_args={
|
| 418 |
+
'cond': conditioning,
|
| 419 |
+
'image_cond': image_conditioning,
|
| 420 |
+
'uncond': unconditional_conditioning,
|
| 421 |
+
'cond_scale': p.cfg_scale,
|
| 422 |
+
's_min_uncond': self.s_min_uncond
|
| 423 |
+
}, disable=False, callback=self.callback_state, **extra_params_kwargs))
|
| 424 |
+
|
| 425 |
+
return samples
|
| 426 |
+
|