sd_samplers_kdiffusion.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import torch
  2. import inspect
  3. import k_diffusion.sampling
  4. from modules import sd_samplers_common, sd_samplers_extra, sd_samplers_cfg_denoiser, sd_schedulers, devices
  5. from modules.sd_samplers_cfg_denoiser import CFGDenoiser # noqa: F401
  6. from modules.script_callbacks import ExtraNoiseParams, extra_noise_callback
  7. from modules.shared import opts
  8. import modules.shared as shared
  9. samplers_k_diffusion = [
  10. ('DPM++ 2M', 'sample_dpmpp_2m', ['k_dpmpp_2m'], {'scheduler': 'karras'}),
  11. ('DPM++ SDE', 'sample_dpmpp_sde', ['k_dpmpp_sde'], {'scheduler': 'karras', "second_order": True, "brownian_noise": True}),
  12. ('DPM++ 2M SDE', 'sample_dpmpp_2m_sde', ['k_dpmpp_2m_sde'], {'scheduler': 'exponential', "brownian_noise": True}),
  13. ('DPM++ 2M SDE Heun', 'sample_dpmpp_2m_sde', ['k_dpmpp_2m_sde_heun'], {'scheduler': 'exponential', "brownian_noise": True, "solver_type": "heun"}),
  14. ('DPM++ 2S a', 'sample_dpmpp_2s_ancestral', ['k_dpmpp_2s_a'], {'scheduler': 'karras', "uses_ensd": True, "second_order": True}),
  15. ('DPM++ 3M SDE', 'sample_dpmpp_3m_sde', ['k_dpmpp_3m_sde'], {'scheduler': 'exponential', 'discard_next_to_last_sigma': True, "brownian_noise": True}),
  16. ('Euler a', 'sample_euler_ancestral', ['k_euler_a', 'k_euler_ancestral'], {"uses_ensd": True}),
  17. ('Euler', 'sample_euler', ['k_euler'], {}),
  18. ('LMS', 'sample_lms', ['k_lms'], {}),
  19. ('Heun', 'sample_heun', ['k_heun'], {"second_order": True}),
  20. ('DPM2', 'sample_dpm_2', ['k_dpm_2'], {'scheduler': 'karras', 'discard_next_to_last_sigma': True, "second_order": True}),
  21. ('DPM2 a', 'sample_dpm_2_ancestral', ['k_dpm_2_a'], {'scheduler': 'karras', 'discard_next_to_last_sigma': True, "uses_ensd": True, "second_order": 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. ('Restart', sd_samplers_extra.restart_sampler, ['restart'], {'scheduler': 'karras', "second_order": True}),
  25. ]
  26. samplers_data_k_diffusion = [
  27. sd_samplers_common.SamplerData(label, lambda model, funcname=funcname: KDiffusionSampler(funcname, model), aliases, options)
  28. for label, funcname, aliases, options in samplers_k_diffusion
  29. if callable(funcname) or hasattr(k_diffusion.sampling, funcname)
  30. ]
  31. sampler_extra_params = {
  32. 'sample_euler': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
  33. 'sample_heun': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
  34. 'sample_dpm_2': ['s_churn', 's_tmin', 's_tmax', 's_noise'],
  35. 'sample_dpm_fast': ['s_noise'],
  36. 'sample_dpm_2_ancestral': ['s_noise'],
  37. 'sample_dpmpp_2s_ancestral': ['s_noise'],
  38. 'sample_dpmpp_sde': ['s_noise'],
  39. 'sample_dpmpp_2m_sde': ['s_noise'],
  40. 'sample_dpmpp_3m_sde': ['s_noise'],
  41. }
  42. k_diffusion_samplers_map = {x.name: x for x in samplers_data_k_diffusion}
  43. k_diffusion_scheduler = {x.name: x.function for x in sd_schedulers.schedulers}
  44. class CFGDenoiserKDiffusion(sd_samplers_cfg_denoiser.CFGDenoiser):
  45. @property
  46. def inner_model(self):
  47. if self.model_wrap is None:
  48. denoiser_constructor = getattr(shared.sd_model, 'create_denoiser', None)
  49. if denoiser_constructor is not None:
  50. self.model_wrap = denoiser_constructor()
  51. else:
  52. denoiser = k_diffusion.external.CompVisVDenoiser if shared.sd_model.parameterization == "v" else k_diffusion.external.CompVisDenoiser
  53. self.model_wrap = denoiser(shared.sd_model, quantize=shared.opts.enable_quantization)
  54. return self.model_wrap
  55. class KDiffusionSampler(sd_samplers_common.Sampler):
  56. def __init__(self, funcname, sd_model, options=None):
  57. super().__init__(funcname)
  58. self.extra_params = sampler_extra_params.get(funcname, [])
  59. self.options = options or {}
  60. self.func = funcname if callable(funcname) else getattr(k_diffusion.sampling, self.funcname)
  61. self.model_wrap_cfg = CFGDenoiserKDiffusion(self)
  62. self.model_wrap = self.model_wrap_cfg.inner_model
  63. def get_sigmas(self, p, steps):
  64. discard_next_to_last_sigma = self.config is not None and self.config.options.get('discard_next_to_last_sigma', False)
  65. if opts.always_discard_next_to_last_sigma and not discard_next_to_last_sigma:
  66. discard_next_to_last_sigma = True
  67. p.extra_generation_params["Discard penultimate sigma"] = True
  68. steps += 1 if discard_next_to_last_sigma else 0
  69. scheduler_name = (p.hr_scheduler if p.is_hr_pass else p.scheduler) or 'Automatic'
  70. if scheduler_name == 'Automatic':
  71. scheduler_name = self.config.options.get('scheduler', None)
  72. scheduler = sd_schedulers.schedulers_map.get(scheduler_name)
  73. m_sigma_min, m_sigma_max = self.model_wrap.sigmas[0].item(), self.model_wrap.sigmas[-1].item()
  74. sigma_min, sigma_max = (0.1, 10) if opts.use_old_karras_scheduler_sigmas else (m_sigma_min, m_sigma_max)
  75. if p.sampler_noise_scheduler_override:
  76. sigmas = p.sampler_noise_scheduler_override(steps)
  77. elif scheduler is None or scheduler.function is None:
  78. sigmas = self.model_wrap.get_sigmas(steps)
  79. else:
  80. sigmas_kwargs = {'sigma_min': sigma_min, 'sigma_max': sigma_max}
  81. if scheduler.label != 'Automatic' and not p.is_hr_pass:
  82. p.extra_generation_params["Schedule type"] = scheduler.label
  83. elif scheduler.label != p.extra_generation_params.get("Schedule type"):
  84. p.extra_generation_params["Hires schedule type"] = scheduler.label
  85. if opts.sigma_min != 0 and opts.sigma_min != m_sigma_min:
  86. sigmas_kwargs['sigma_min'] = opts.sigma_min
  87. p.extra_generation_params["Schedule min sigma"] = opts.sigma_min
  88. if opts.sigma_max != 0 and opts.sigma_max != m_sigma_max:
  89. sigmas_kwargs['sigma_max'] = opts.sigma_max
  90. p.extra_generation_params["Schedule max sigma"] = opts.sigma_max
  91. if scheduler.default_rho != -1 and opts.rho != 0 and opts.rho != scheduler.default_rho:
  92. sigmas_kwargs['rho'] = opts.rho
  93. p.extra_generation_params["Schedule rho"] = opts.rho
  94. if scheduler.need_inner_model:
  95. sigmas_kwargs['inner_model'] = self.model_wrap
  96. if scheduler.label == 'Beta':
  97. p.extra_generation_params["Beta schedule alpha"] = opts.beta_dist_alpha
  98. p.extra_generation_params["Beta schedule beta"] = opts.beta_dist_beta
  99. sigmas = scheduler.function(n=steps, **sigmas_kwargs, device=devices.cpu)
  100. if discard_next_to_last_sigma:
  101. sigmas = torch.cat([sigmas[:-2], sigmas[-1:]])
  102. return sigmas.cpu()
  103. def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
  104. steps, t_enc = sd_samplers_common.setup_img2img_steps(p, steps)
  105. sigmas = self.get_sigmas(p, steps)
  106. sigma_sched = sigmas[steps - t_enc - 1:]
  107. if hasattr(shared.sd_model, 'add_noise_to_latent'):
  108. xi = shared.sd_model.add_noise_to_latent(x, noise, sigma_sched[0])
  109. else:
  110. xi = x + noise * sigma_sched[0]
  111. if opts.img2img_extra_noise > 0:
  112. p.extra_generation_params["Extra noise"] = opts.img2img_extra_noise
  113. extra_noise_params = ExtraNoiseParams(noise, x, xi)
  114. extra_noise_callback(extra_noise_params)
  115. noise = extra_noise_params.noise
  116. xi += noise * opts.img2img_extra_noise
  117. extra_params_kwargs = self.initialize(p)
  118. parameters = inspect.signature(self.func).parameters
  119. if 'sigma_min' in parameters:
  120. ## last sigma is zero which isn't allowed by DPM Fast & Adaptive so taking value before last
  121. extra_params_kwargs['sigma_min'] = sigma_sched[-2]
  122. if 'sigma_max' in parameters:
  123. extra_params_kwargs['sigma_max'] = sigma_sched[0]
  124. if 'n' in parameters:
  125. extra_params_kwargs['n'] = len(sigma_sched) - 1
  126. if 'sigma_sched' in parameters:
  127. extra_params_kwargs['sigma_sched'] = sigma_sched
  128. if 'sigmas' in parameters:
  129. extra_params_kwargs['sigmas'] = sigma_sched
  130. if self.config.options.get('brownian_noise', False):
  131. noise_sampler = self.create_noise_sampler(x, sigmas, p)
  132. extra_params_kwargs['noise_sampler'] = noise_sampler
  133. if self.config.options.get('solver_type', None) == 'heun':
  134. extra_params_kwargs['solver_type'] = 'heun'
  135. self.model_wrap_cfg.init_latent = x
  136. self.last_latent = x
  137. self.sampler_extra_args = {
  138. 'cond': conditioning,
  139. 'image_cond': image_conditioning,
  140. 'uncond': unconditional_conditioning,
  141. 'cond_scale': p.cfg_scale,
  142. 's_min_uncond': self.s_min_uncond
  143. }
  144. samples = self.launch_sampling(t_enc + 1, lambda: self.func(self.model_wrap_cfg, xi, extra_args=self.sampler_extra_args, disable=False, callback=self.callback_state, **extra_params_kwargs))
  145. self.add_infotext(p)
  146. return samples
  147. def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
  148. steps = steps or p.steps
  149. sigmas = self.get_sigmas(p, steps)
  150. if opts.sgm_noise_multiplier:
  151. p.extra_generation_params["SGM noise multiplier"] = True
  152. x = x * torch.sqrt(1.0 + sigmas[0] ** 2.0)
  153. else:
  154. x = x * sigmas[0]
  155. extra_params_kwargs = self.initialize(p)
  156. parameters = inspect.signature(self.func).parameters
  157. if 'n' in parameters:
  158. extra_params_kwargs['n'] = steps
  159. if 'sigma_min' in parameters:
  160. extra_params_kwargs['sigma_min'] = self.model_wrap.sigmas[0].item()
  161. extra_params_kwargs['sigma_max'] = self.model_wrap.sigmas[-1].item()
  162. if 'sigmas' in parameters:
  163. extra_params_kwargs['sigmas'] = sigmas
  164. if self.config.options.get('brownian_noise', False):
  165. noise_sampler = self.create_noise_sampler(x, sigmas, p)
  166. extra_params_kwargs['noise_sampler'] = noise_sampler
  167. if self.config.options.get('solver_type', None) == 'heun':
  168. extra_params_kwargs['solver_type'] = 'heun'
  169. self.last_latent = x
  170. self.sampler_extra_args = {
  171. 'cond': conditioning,
  172. 'image_cond': image_conditioning,
  173. 'uncond': unconditional_conditioning,
  174. 'cond_scale': p.cfg_scale,
  175. 's_min_uncond': self.s_min_uncond
  176. }
  177. samples = self.launch_sampling(steps, lambda: self.func(self.model_wrap_cfg, x, extra_args=self.sampler_extra_args, disable=False, callback=self.callback_state, **extra_params_kwargs))
  178. self.add_infotext(p)
  179. return samples