sd_samplers_cfg_denoiser.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import torch
  2. from modules import prompt_parser, devices, sd_samplers_common
  3. from modules.shared import opts, state
  4. import modules.shared as shared
  5. from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback
  6. from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback
  7. from modules.script_callbacks import AfterCFGCallbackParams, cfg_after_cfg_callback
  8. def catenate_conds(conds):
  9. if not isinstance(conds[0], dict):
  10. return torch.cat(conds)
  11. return {key: torch.cat([x[key] for x in conds]) for key in conds[0].keys()}
  12. def subscript_cond(cond, a, b):
  13. if not isinstance(cond, dict):
  14. return cond[a:b]
  15. return {key: vec[a:b] for key, vec in cond.items()}
  16. def pad_cond(tensor, repeats, empty):
  17. if not isinstance(tensor, dict):
  18. return torch.cat([tensor, empty.repeat((tensor.shape[0], repeats, 1))], axis=1)
  19. tensor['crossattn'] = pad_cond(tensor['crossattn'], repeats, empty)
  20. return tensor
  21. class CFGDenoiser(torch.nn.Module):
  22. """
  23. Classifier free guidance denoiser. A wrapper for stable diffusion model (specifically for unet)
  24. that can take a noisy picture and produce a noise-free picture using two guidances (prompts)
  25. instead of one. Originally, the second prompt is just an empty string, but we use non-empty
  26. negative prompt.
  27. """
  28. def __init__(self, sampler):
  29. super().__init__()
  30. self.model_wrap = None
  31. self.mask = None
  32. self.nmask = None
  33. self.init_latent = None
  34. self.steps = None
  35. """number of steps as specified by user in UI"""
  36. self.total_steps = None
  37. """expected number of calls to denoiser calculated from self.steps and specifics of the selected sampler"""
  38. self.step = 0
  39. self.image_cfg_scale = None
  40. self.padded_cond_uncond = False
  41. self.sampler = sampler
  42. self.model_wrap = None
  43. self.p = None
  44. self.mask_before_denoising = False
  45. @property
  46. def inner_model(self):
  47. raise NotImplementedError()
  48. def combine_denoised(self, x_out, conds_list, uncond, cond_scale):
  49. denoised_uncond = x_out[-uncond.shape[0]:]
  50. denoised = torch.clone(denoised_uncond)
  51. for i, conds in enumerate(conds_list):
  52. for cond_index, weight in conds:
  53. denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale)
  54. return denoised
  55. def combine_denoised_for_edit_model(self, x_out, cond_scale):
  56. out_cond, out_img_cond, out_uncond = x_out.chunk(3)
  57. denoised = out_uncond + cond_scale * (out_cond - out_img_cond) + self.image_cfg_scale * (out_img_cond - out_uncond)
  58. return denoised
  59. def get_pred_x0(self, x_in, x_out, sigma):
  60. return x_out
  61. def update_inner_model(self):
  62. self.model_wrap = None
  63. c, uc = self.p.get_conds()
  64. self.sampler.sampler_extra_args['cond'] = c
  65. self.sampler.sampler_extra_args['uncond'] = uc
  66. def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond):
  67. if state.interrupted or state.skipped:
  68. raise sd_samplers_common.InterruptedException
  69. if sd_samplers_common.apply_refiner(self):
  70. cond = self.sampler.sampler_extra_args['cond']
  71. uncond = self.sampler.sampler_extra_args['uncond']
  72. # at self.image_cfg_scale == 1.0 produced results for edit model are the same as with normal sampling,
  73. # so is_edit_model is set to False to support AND composition.
  74. 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
  75. conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step)
  76. uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step)
  77. 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)"
  78. if self.mask_before_denoising and self.mask is not None:
  79. x = self.init_latent * self.mask + self.nmask * x
  80. batch_size = len(conds_list)
  81. repeats = [len(conds_list[i]) for i in range(batch_size)]
  82. if shared.sd_model.model.conditioning_key == "crossattn-adm":
  83. image_uncond = torch.zeros_like(image_cond)
  84. make_condition_dict = lambda c_crossattn, c_adm: {"c_crossattn": [c_crossattn], "c_adm": c_adm}
  85. else:
  86. image_uncond = image_cond
  87. if isinstance(uncond, dict):
  88. make_condition_dict = lambda c_crossattn, c_concat: {**c_crossattn, "c_concat": [c_concat]}
  89. else:
  90. make_condition_dict = lambda c_crossattn, c_concat: {"c_crossattn": [c_crossattn], "c_concat": [c_concat]}
  91. if not is_edit_model:
  92. x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x])
  93. sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma])
  94. image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond])
  95. else:
  96. x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x] + [x])
  97. sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma] + [sigma])
  98. 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)])
  99. denoiser_params = CFGDenoiserParams(x_in, image_cond_in, sigma_in, state.sampling_step, state.sampling_steps, tensor, uncond)
  100. cfg_denoiser_callback(denoiser_params)
  101. x_in = denoiser_params.x
  102. image_cond_in = denoiser_params.image_cond
  103. sigma_in = denoiser_params.sigma
  104. tensor = denoiser_params.text_cond
  105. uncond = denoiser_params.text_uncond
  106. skip_uncond = False
  107. # alternating uncond allows for higher thresholds without the quality loss normally expected from raising it
  108. if self.step % 2 and s_min_uncond > 0 and sigma[0] < s_min_uncond and not is_edit_model:
  109. skip_uncond = True
  110. x_in = x_in[:-batch_size]
  111. sigma_in = sigma_in[:-batch_size]
  112. self.padded_cond_uncond = False
  113. if shared.opts.pad_cond_uncond and tensor.shape[1] != uncond.shape[1]:
  114. empty = shared.sd_model.cond_stage_model_empty_prompt
  115. num_repeats = (tensor.shape[1] - uncond.shape[1]) // empty.shape[1]
  116. if num_repeats < 0:
  117. tensor = pad_cond(tensor, -num_repeats, empty)
  118. self.padded_cond_uncond = True
  119. elif num_repeats > 0:
  120. uncond = pad_cond(uncond, num_repeats, empty)
  121. self.padded_cond_uncond = True
  122. if tensor.shape[1] == uncond.shape[1] or skip_uncond:
  123. if is_edit_model:
  124. cond_in = catenate_conds([tensor, uncond, uncond])
  125. elif skip_uncond:
  126. cond_in = tensor
  127. else:
  128. cond_in = catenate_conds([tensor, uncond])
  129. if shared.opts.batch_cond_uncond:
  130. x_out = self.inner_model(x_in, sigma_in, cond=make_condition_dict(cond_in, image_cond_in))
  131. else:
  132. x_out = torch.zeros_like(x_in)
  133. for batch_offset in range(0, x_out.shape[0], batch_size):
  134. a = batch_offset
  135. b = a + batch_size
  136. 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]))
  137. else:
  138. x_out = torch.zeros_like(x_in)
  139. batch_size = batch_size*2 if shared.opts.batch_cond_uncond else batch_size
  140. for batch_offset in range(0, tensor.shape[0], batch_size):
  141. a = batch_offset
  142. b = min(a + batch_size, tensor.shape[0])
  143. if not is_edit_model:
  144. c_crossattn = subscript_cond(tensor, a, b)
  145. else:
  146. c_crossattn = torch.cat([tensor[a:b]], uncond)
  147. 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]))
  148. if not skip_uncond:
  149. 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]:]))
  150. denoised_image_indexes = [x[0][0] for x in conds_list]
  151. if skip_uncond:
  152. fake_uncond = torch.cat([x_out[i:i+1] for i in denoised_image_indexes])
  153. 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
  154. denoised_params = CFGDenoisedParams(x_out, state.sampling_step, state.sampling_steps, self.inner_model)
  155. cfg_denoised_callback(denoised_params)
  156. devices.test_for_nans(x_out, "unet")
  157. if is_edit_model:
  158. denoised = self.combine_denoised_for_edit_model(x_out, cond_scale)
  159. elif skip_uncond:
  160. denoised = self.combine_denoised(x_out, conds_list, uncond, 1.0)
  161. else:
  162. denoised = self.combine_denoised(x_out, conds_list, uncond, cond_scale)
  163. if not self.mask_before_denoising and self.mask is not None:
  164. denoised = self.init_latent * self.mask + self.nmask * denoised
  165. self.sampler.last_latent = self.get_pred_x0(torch.cat([x_in[i:i + 1] for i in denoised_image_indexes]), torch.cat([x_out[i:i + 1] for i in denoised_image_indexes]), sigma)
  166. if opts.live_preview_content == "Prompt":
  167. preview = self.sampler.last_latent
  168. elif opts.live_preview_content == "Negative prompt":
  169. preview = self.get_pred_x0(x_in[-uncond.shape[0]:], x_out[-uncond.shape[0]:], sigma)
  170. else:
  171. preview = self.get_pred_x0(torch.cat([x_in[i:i+1] for i in denoised_image_indexes]), torch.cat([denoised[i:i+1] for i in denoised_image_indexes]), sigma)
  172. sd_samplers_common.store_latent(preview)
  173. after_cfg_callback_params = AfterCFGCallbackParams(denoised, state.sampling_step, state.sampling_steps)
  174. cfg_after_cfg_callback(after_cfg_callback_params)
  175. denoised = after_cfg_callback_params.x
  176. self.step += 1
  177. return denoised