sd_samplers_kdiffusion.py 22 KB

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