sd_samplers_compvis.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import math
  2. import ldm.models.diffusion.ddim
  3. import ldm.models.diffusion.plms
  4. import numpy as np
  5. import torch
  6. from modules.shared import state
  7. from modules import sd_samplers_common, prompt_parser, shared
  8. import modules.models.diffusion.uni_pc
  9. samplers_data_compvis = [
  10. sd_samplers_common.SamplerData('DDIM', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.ddim.DDIMSampler, model), [], {"default_eta_is_0": True, "uses_ensd": True, "no_sdxl": True}),
  11. sd_samplers_common.SamplerData('PLMS', lambda model: VanillaStableDiffusionSampler(ldm.models.diffusion.plms.PLMSSampler, model), [], {"no_sdxl": True}),
  12. sd_samplers_common.SamplerData('UniPC', lambda model: VanillaStableDiffusionSampler(modules.models.diffusion.uni_pc.UniPCSampler, model), [], {"no_sdxl": True}),
  13. ]
  14. class VanillaStableDiffusionSampler:
  15. def __init__(self, constructor, sd_model):
  16. self.sampler = constructor(sd_model)
  17. self.is_ddim = hasattr(self.sampler, 'p_sample_ddim')
  18. self.is_plms = hasattr(self.sampler, 'p_sample_plms')
  19. self.is_unipc = isinstance(self.sampler, modules.models.diffusion.uni_pc.UniPCSampler)
  20. self.orig_p_sample_ddim = None
  21. if self.is_plms:
  22. self.orig_p_sample_ddim = self.sampler.p_sample_plms
  23. elif self.is_ddim:
  24. self.orig_p_sample_ddim = self.sampler.p_sample_ddim
  25. self.mask = None
  26. self.nmask = None
  27. self.init_latent = None
  28. self.sampler_noises = None
  29. self.step = 0
  30. self.stop_at = None
  31. self.eta = None
  32. self.config = None
  33. self.last_latent = None
  34. self.conditioning_key = sd_model.model.conditioning_key
  35. def number_of_needed_noises(self, p):
  36. return 0
  37. def launch_sampling(self, steps, func):
  38. state.sampling_steps = steps
  39. state.sampling_step = 0
  40. try:
  41. return func()
  42. except sd_samplers_common.InterruptedException:
  43. return self.last_latent
  44. def p_sample_ddim_hook(self, x_dec, cond, ts, unconditional_conditioning, *args, **kwargs):
  45. x_dec, ts, cond, unconditional_conditioning = self.before_sample(x_dec, ts, cond, unconditional_conditioning)
  46. res = self.orig_p_sample_ddim(x_dec, cond, ts, *args, unconditional_conditioning=unconditional_conditioning, **kwargs)
  47. x_dec, ts, cond, unconditional_conditioning, res = self.after_sample(x_dec, ts, cond, unconditional_conditioning, res)
  48. return res
  49. def before_sample(self, x, ts, cond, unconditional_conditioning):
  50. if state.interrupted or state.skipped:
  51. raise sd_samplers_common.InterruptedException
  52. if self.stop_at is not None and self.step > self.stop_at:
  53. raise sd_samplers_common.InterruptedException
  54. # Have to unwrap the inpainting conditioning here to perform pre-processing
  55. image_conditioning = None
  56. uc_image_conditioning = None
  57. if isinstance(cond, dict):
  58. if self.conditioning_key == "crossattn-adm":
  59. image_conditioning = cond["c_adm"]
  60. uc_image_conditioning = unconditional_conditioning["c_adm"]
  61. else:
  62. image_conditioning = cond["c_concat"][0]
  63. cond = cond["c_crossattn"][0]
  64. unconditional_conditioning = unconditional_conditioning["c_crossattn"][0]
  65. conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
  66. unconditional_conditioning = prompt_parser.reconstruct_cond_batch(unconditional_conditioning, self.step)
  67. assert all(len(conds) == 1 for conds in conds_list), 'composition via AND is not supported for DDIM/PLMS samplers'
  68. cond = tensor
  69. # for DDIM, shapes must match, we can't just process cond and uncond independently;
  70. # filling unconditional_conditioning with repeats of the last vector to match length is
  71. # not 100% correct but should work well enough
  72. if unconditional_conditioning.shape[1] < cond.shape[1]:
  73. last_vector = unconditional_conditioning[:, -1:]
  74. last_vector_repeated = last_vector.repeat([1, cond.shape[1] - unconditional_conditioning.shape[1], 1])
  75. unconditional_conditioning = torch.hstack([unconditional_conditioning, last_vector_repeated])
  76. elif unconditional_conditioning.shape[1] > cond.shape[1]:
  77. unconditional_conditioning = unconditional_conditioning[:, :cond.shape[1]]
  78. if self.mask is not None:
  79. img_orig = self.sampler.model.q_sample(self.init_latent, ts)
  80. x = img_orig * self.mask + self.nmask * x
  81. # Wrap the image conditioning back up since the DDIM code can accept the dict directly.
  82. # Note that they need to be lists because it just concatenates them later.
  83. if image_conditioning is not None:
  84. if self.conditioning_key == "crossattn-adm":
  85. cond = {"c_adm": image_conditioning, "c_crossattn": [cond]}
  86. unconditional_conditioning = {"c_adm": uc_image_conditioning, "c_crossattn": [unconditional_conditioning]}
  87. else:
  88. cond = {"c_concat": [image_conditioning], "c_crossattn": [cond]}
  89. unconditional_conditioning = {"c_concat": [image_conditioning], "c_crossattn": [unconditional_conditioning]}
  90. return x, ts, cond, unconditional_conditioning
  91. def update_step(self, last_latent):
  92. if self.mask is not None:
  93. self.last_latent = self.init_latent * self.mask + self.nmask * last_latent
  94. else:
  95. self.last_latent = last_latent
  96. sd_samplers_common.store_latent(self.last_latent)
  97. self.step += 1
  98. state.sampling_step = self.step
  99. shared.total_tqdm.update()
  100. def after_sample(self, x, ts, cond, uncond, res):
  101. if not self.is_unipc:
  102. self.update_step(res[1])
  103. return x, ts, cond, uncond, res
  104. def unipc_after_update(self, x, model_x):
  105. self.update_step(x)
  106. def initialize(self, p):
  107. if self.is_ddim:
  108. self.eta = p.eta if p.eta is not None else shared.opts.eta_ddim
  109. else:
  110. self.eta = 0.0
  111. if self.eta != 0.0:
  112. p.extra_generation_params["Eta DDIM"] = self.eta
  113. if self.is_unipc:
  114. keys = [
  115. ('UniPC variant', 'uni_pc_variant'),
  116. ('UniPC skip type', 'uni_pc_skip_type'),
  117. ('UniPC order', 'uni_pc_order'),
  118. ('UniPC lower order final', 'uni_pc_lower_order_final'),
  119. ]
  120. for name, key in keys:
  121. v = getattr(shared.opts, key)
  122. if v != shared.opts.get_default(key):
  123. p.extra_generation_params[name] = v
  124. for fieldname in ['p_sample_ddim', 'p_sample_plms']:
  125. if hasattr(self.sampler, fieldname):
  126. setattr(self.sampler, fieldname, self.p_sample_ddim_hook)
  127. if self.is_unipc:
  128. 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))
  129. self.mask = p.mask if hasattr(p, 'mask') else None
  130. self.nmask = p.nmask if hasattr(p, 'nmask') else None
  131. def adjust_steps_if_invalid(self, p, num_steps):
  132. if ((self.config.name == 'DDIM') and p.ddim_discretize == 'uniform') or (self.config.name == 'PLMS') or (self.config.name == 'UniPC'):
  133. if self.config.name == 'UniPC' and num_steps < shared.opts.uni_pc_order:
  134. num_steps = shared.opts.uni_pc_order
  135. valid_step = 999 / (1000 // num_steps)
  136. if valid_step == math.floor(valid_step):
  137. return int(valid_step) + 1
  138. return num_steps
  139. def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
  140. steps, t_enc = sd_samplers_common.setup_img2img_steps(p, steps)
  141. steps = self.adjust_steps_if_invalid(p, steps)
  142. self.initialize(p)
  143. self.sampler.make_schedule(ddim_num_steps=steps, ddim_eta=self.eta, ddim_discretize=p.ddim_discretize, verbose=False)
  144. x1 = self.sampler.stochastic_encode(x, torch.tensor([t_enc] * int(x.shape[0])).to(shared.device), noise=noise)
  145. self.init_latent = x
  146. self.last_latent = x
  147. self.step = 0
  148. # Wrap the conditioning models with additional image conditioning for inpainting model
  149. if image_conditioning is not None:
  150. if self.conditioning_key == "crossattn-adm":
  151. conditioning = {"c_adm": image_conditioning, "c_crossattn": [conditioning]}
  152. unconditional_conditioning = {"c_adm": torch.zeros_like(image_conditioning), "c_crossattn": [unconditional_conditioning]}
  153. else:
  154. conditioning = {"c_concat": [image_conditioning], "c_crossattn": [conditioning]}
  155. unconditional_conditioning = {"c_concat": [image_conditioning], "c_crossattn": [unconditional_conditioning]}
  156. 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))
  157. return samples
  158. def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None):
  159. self.initialize(p)
  160. self.init_latent = None
  161. self.last_latent = x
  162. self.step = 0
  163. steps = self.adjust_steps_if_invalid(p, steps or p.steps)
  164. # Wrap the conditioning models with additional image conditioning for inpainting model
  165. # dummy_for_plms is needed because PLMS code checks the first item in the dict to have the right shape
  166. if image_conditioning is not None:
  167. if self.conditioning_key == "crossattn-adm":
  168. conditioning = {"dummy_for_plms": np.zeros((conditioning.shape[0],)), "c_crossattn": [conditioning], "c_adm": image_conditioning}
  169. unconditional_conditioning = {"c_crossattn": [unconditional_conditioning], "c_adm": torch.zeros_like(image_conditioning)}
  170. else:
  171. conditioning = {"dummy_for_plms": np.zeros((conditioning.shape[0],)), "c_crossattn": [conditioning], "c_concat": [image_conditioning]}
  172. unconditional_conditioning = {"c_crossattn": [unconditional_conditioning], "c_concat": [image_conditioning]}
  173. 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])
  174. return samples_ddim