processing.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  1. import json
  2. import logging
  3. import math
  4. import os
  5. import sys
  6. import hashlib
  7. import torch
  8. import numpy as np
  9. from PIL import Image, ImageOps
  10. import random
  11. import cv2
  12. from skimage import exposure
  13. from typing import Any, Dict, List
  14. import modules.sd_hijack
  15. from modules import devices, prompt_parser, masking, sd_samplers, lowvram, generation_parameters_copypaste, extra_networks, sd_vae_approx, scripts, sd_samplers_common, sd_unet, errors
  16. from modules.sd_hijack import model_hijack
  17. from modules.shared import opts, cmd_opts, state
  18. import modules.shared as shared
  19. import modules.paths as paths
  20. import modules.face_restoration
  21. import modules.images as images
  22. import modules.styles
  23. import modules.sd_models as sd_models
  24. import modules.sd_vae as sd_vae
  25. from ldm.data.util import AddMiDaS
  26. from ldm.models.diffusion.ddpm import LatentDepth2ImageDiffusion
  27. from einops import repeat, rearrange
  28. from blendmodes.blend import blendLayers, BlendType
  29. # some of those options should not be changed at all because they would break the model, so I removed them from options.
  30. opt_C = 4
  31. opt_f = 8
  32. def setup_color_correction(image):
  33. logging.info("Calibrating color correction.")
  34. correction_target = cv2.cvtColor(
  35. np.asarray(image.copy()), cv2.COLOR_RGB2LAB)
  36. return correction_target
  37. def apply_color_correction(correction, original_image):
  38. logging.info("Applying color correction.")
  39. image = Image.fromarray(cv2.cvtColor(exposure.match_histograms(
  40. cv2.cvtColor(
  41. np.asarray(original_image),
  42. cv2.COLOR_RGB2LAB
  43. ),
  44. correction,
  45. channel_axis=2
  46. ), cv2.COLOR_LAB2RGB).astype("uint8"))
  47. image = blendLayers(image, original_image, BlendType.LUMINOSITY)
  48. return image
  49. def apply_overlay(image, paste_loc, index, overlays):
  50. if overlays is None or index >= len(overlays):
  51. return image
  52. overlay = overlays[index]
  53. if paste_loc is not None:
  54. x, y, w, h = paste_loc
  55. base_image = Image.new('RGBA', (overlay.width, overlay.height))
  56. image = images.resize_image(1, image, w, h)
  57. base_image.paste(image, (x, y))
  58. image = base_image
  59. image = image.convert('RGBA')
  60. image.alpha_composite(overlay)
  61. image = image.convert('RGB')
  62. return image
  63. def txt2img_image_conditioning(sd_model, x, width, height):
  64. # Inpainting models
  65. if sd_model.model.conditioning_key in {'hybrid', 'concat'}:
  66. # The "masked-image" in this case will just be all zeros since the entire image is masked.
  67. image_conditioning = torch.zeros(
  68. x.shape[0], 3, height, width, device=x.device)
  69. image_conditioning = sd_model.get_first_stage_encoding(
  70. sd_model.encode_first_stage(image_conditioning))
  71. # Add the fake full 1s mask to the first dimension.
  72. image_conditioning = torch.nn.functional.pad(
  73. image_conditioning, (0, 0, 0, 0, 1, 0), value=1.0)
  74. image_conditioning = image_conditioning.to(x.dtype)
  75. return image_conditioning
  76. elif sd_model.model.conditioning_key == "crossattn-adm": # UnCLIP models
  77. return x.new_zeros(x.shape[0], 2*sd_model.noise_augmentor.time_embed.dim, dtype=x.dtype, device=x.device)
  78. else:
  79. # Dummy zero conditioning if we're not using inpainting or unclip models.
  80. # Still takes up a bit of memory, but no encoder call.
  81. # Pretty sure we can just make this a 1x1 image since its not going to be used besides its batch size.
  82. return x.new_zeros(x.shape[0], 5, 1, 1, dtype=x.dtype, device=x.device)
  83. class StableDiffusionProcessing:
  84. """
  85. The first set of paramaters: sd_models -> do_not_reload_embeddings represent the minimum required to create a StableDiffusionProcessing
  86. """
  87. cached_uc = [None, None]
  88. cached_c = [None, None]
  89. def __init__(self, sd_model=None, outpath_samples=None, outpath_grids=None, prompt: str = "", styles: List[str] = None, seed: int = -1, subseed: int = -1, subseed_strength: float = 0, seed_resize_from_h: int = -1, seed_resize_from_w: int = -1, seed_enable_extras: bool = True, sampler_name: str = None, batch_size: int = 1, n_iter: int = 1, steps: int = 50, cfg_scale: float = 7.0, width: int = 512, height: int = 512, restore_faces: bool = False, tiling: bool = False, do_not_save_samples: bool = False, do_not_save_grid: bool = False, extra_generation_params: Dict[Any, Any] = None, overlay_images: Any = None, negative_prompt: str = None, eta: float = None, do_not_reload_embeddings: bool = False, denoising_strength: float = 0, ddim_discretize: str = None, s_min_uncond: float = 0.0, s_churn: float = 0.0, s_tmax: float = None, s_tmin: float = 0.0, s_noise: float = 1.0, override_settings: Dict[str, Any] = None, override_settings_restore_afterwards: bool = True, sampler_index: int = None, script_args: list = None):
  90. if sampler_index is not None:
  91. print("sampler_index argument for StableDiffusionProcessing does not do anything; use sampler_name", file=sys.stderr)
  92. self.outpath_samples: str = outpath_samples
  93. self.outpath_grids: str = outpath_grids
  94. self.prompt: str = prompt
  95. self.prompt_for_display: str = None
  96. self.negative_prompt: str = (negative_prompt or "")
  97. self.styles: list = styles or []
  98. self.seed: int = seed
  99. self.subseed: int = subseed
  100. self.subseed_strength: float = subseed_strength
  101. self.seed_resize_from_h: int = seed_resize_from_h
  102. self.seed_resize_from_w: int = seed_resize_from_w
  103. self.sampler_name: str = sampler_name
  104. self.batch_size: int = batch_size
  105. self.n_iter: int = n_iter
  106. self.steps: int = steps
  107. self.cfg_scale: float = cfg_scale
  108. self.width: int = width
  109. self.height: int = height
  110. self.restore_faces: bool = restore_faces
  111. self.tiling: bool = tiling
  112. self.do_not_save_samples: bool = do_not_save_samples
  113. self.do_not_save_grid: bool = do_not_save_grid
  114. self.extra_generation_params: dict = extra_generation_params or {}
  115. self.overlay_images = overlay_images
  116. self.eta = eta
  117. self.do_not_reload_embeddings = do_not_reload_embeddings
  118. self.paste_to = None
  119. self.color_corrections = None
  120. self.denoising_strength: float = denoising_strength
  121. self.sampler_noise_scheduler_override = None
  122. self.ddim_discretize = ddim_discretize or opts.ddim_discretize
  123. self.s_min_uncond = s_min_uncond or opts.s_min_uncond
  124. self.s_churn = s_churn or opts.s_churn
  125. self.s_tmin = s_tmin or opts.s_tmin
  126. # not representable as a standard ui option
  127. self.s_tmax = s_tmax or float('inf')
  128. self.s_noise = s_noise or opts.s_noise
  129. self.override_settings = {k: v for k, v in (
  130. override_settings or {}).items() if k not in shared.restricted_opts}
  131. self.override_settings_restore_afterwards = override_settings_restore_afterwards
  132. self.is_using_inpainting_conditioning = False
  133. self.disable_extra_networks = False
  134. self.token_merging_ratio = 0
  135. self.token_merging_ratio_hr = 0
  136. if not seed_enable_extras:
  137. self.subseed = -1
  138. self.subseed_strength = 0
  139. self.seed_resize_from_h = 0
  140. self.seed_resize_from_w = 0
  141. self.scripts = None
  142. self.script_args = script_args
  143. self.all_prompts = None
  144. self.all_negative_prompts = None
  145. self.all_seeds = None
  146. self.all_subseeds = None
  147. self.iteration = 0
  148. self.is_hr_pass = False
  149. self.sampler = None
  150. self.prompts = None
  151. self.negative_prompts = None
  152. self.extra_network_data = None
  153. self.seeds = None
  154. self.subseeds = None
  155. self.step_multiplier = 1
  156. self.cached_uc = StableDiffusionProcessing.cached_uc
  157. self.cached_c = StableDiffusionProcessing.cached_c
  158. self.uc = None
  159. self.c = None
  160. self.user = None
  161. @property
  162. def sd_model(self):
  163. return shared.sd_model
  164. def txt2img_image_conditioning(self, x, width=None, height=None):
  165. self.is_using_inpainting_conditioning = self.sd_model.model.conditioning_key in {
  166. 'hybrid', 'concat'}
  167. return txt2img_image_conditioning(self.sd_model, x, width or self.width, height or self.height)
  168. def depth2img_image_conditioning(self, source_image):
  169. # Use the AddMiDaS helper to Format our source image to suit the MiDaS model
  170. transformer = AddMiDaS(model_type="dpt_hybrid")
  171. transformed = transformer(
  172. {"jpg": rearrange(source_image[0], "c h w -> h w c")})
  173. midas_in = torch.from_numpy(
  174. transformed["midas_in"][None, ...]).to(device=shared.device)
  175. midas_in = repeat(midas_in, "1 ... -> n ...", n=self.batch_size)
  176. conditioning_image = self.sd_model.get_first_stage_encoding(
  177. self.sd_model.encode_first_stage(source_image))
  178. conditioning = torch.nn.functional.interpolate(
  179. self.sd_model.depth_model(midas_in),
  180. size=conditioning_image.shape[2:],
  181. mode="bicubic",
  182. align_corners=False,
  183. )
  184. (depth_min, depth_max) = torch.aminmax(conditioning)
  185. conditioning = 2. * (conditioning - depth_min) / \
  186. (depth_max - depth_min) - 1.
  187. return conditioning
  188. def edit_image_conditioning(self, source_image):
  189. conditioning_image = self.sd_model.encode_first_stage(
  190. source_image).mode()
  191. return conditioning_image
  192. def unclip_image_conditioning(self, source_image):
  193. c_adm = self.sd_model.embedder(source_image)
  194. if self.sd_model.noise_augmentor is not None:
  195. noise_level = 0 # TODO: Allow other noise levels?
  196. c_adm, noise_level_emb = self.sd_model.noise_augmentor(c_adm, noise_level=repeat(
  197. torch.tensor([noise_level]).to(c_adm.device), '1 -> b', b=c_adm.shape[0]))
  198. c_adm = torch.cat((c_adm, noise_level_emb), 1)
  199. return c_adm
  200. def inpainting_image_conditioning(self, source_image, latent_image, image_mask=None):
  201. self.is_using_inpainting_conditioning = True
  202. # Handle the different mask inputs
  203. if image_mask is not None:
  204. if torch.is_tensor(image_mask):
  205. conditioning_mask = image_mask
  206. else:
  207. conditioning_mask = np.array(image_mask.convert("L"))
  208. conditioning_mask = conditioning_mask.astype(
  209. np.float32) / 255.0
  210. conditioning_mask = torch.from_numpy(
  211. conditioning_mask[None, None])
  212. # Inpainting model uses a discretized mask as input, so we round to either 1.0 or 0.0
  213. conditioning_mask = torch.round(conditioning_mask)
  214. else:
  215. conditioning_mask = source_image.new_ones(
  216. 1, 1, *source_image.shape[-2:])
  217. # Create another latent image, this time with a masked version of the original input.
  218. # Smoothly interpolate between the masked and unmasked latent conditioning image using a parameter.
  219. conditioning_mask = conditioning_mask.to(
  220. device=source_image.device, dtype=source_image.dtype)
  221. conditioning_image = torch.lerp(
  222. source_image,
  223. source_image * (1.0 - conditioning_mask),
  224. getattr(self, "inpainting_mask_weight",
  225. shared.opts.inpainting_mask_weight)
  226. )
  227. # Encode the new masked image using first stage of network.
  228. conditioning_image = self.sd_model.get_first_stage_encoding(
  229. self.sd_model.encode_first_stage(conditioning_image))
  230. # Create the concatenated conditioning tensor to be fed to `c_concat`
  231. conditioning_mask = torch.nn.functional.interpolate(
  232. conditioning_mask, size=latent_image.shape[-2:])
  233. conditioning_mask = conditioning_mask.expand(
  234. conditioning_image.shape[0], -1, -1, -1)
  235. image_conditioning = torch.cat(
  236. [conditioning_mask, conditioning_image], dim=1)
  237. image_conditioning = image_conditioning.to(
  238. shared.device).type(self.sd_model.dtype)
  239. return image_conditioning
  240. def img2img_image_conditioning(self, source_image, latent_image, image_mask=None):
  241. source_image = devices.cond_cast_float(source_image)
  242. # HACK: Using introspection as the Depth2Image model doesn't appear to uniquely
  243. # identify itself with a field common to all models. The conditioning_key is also hybrid.
  244. if isinstance(self.sd_model, LatentDepth2ImageDiffusion):
  245. return self.depth2img_image_conditioning(source_image)
  246. if self.sd_model.cond_stage_key == "edit":
  247. return self.edit_image_conditioning(source_image)
  248. if self.sampler.conditioning_key in {'hybrid', 'concat'}:
  249. return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask)
  250. if self.sampler.conditioning_key == "crossattn-adm":
  251. return self.unclip_image_conditioning(source_image)
  252. # Dummy zero conditioning if we're not using inpainting or depth model.
  253. return latent_image.new_zeros(latent_image.shape[0], 5, 1, 1)
  254. def init(self, all_prompts, all_seeds, all_subseeds):
  255. pass
  256. def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts):
  257. raise NotImplementedError()
  258. def close(self):
  259. self.sampler = None
  260. self.c = None
  261. self.uc = None
  262. if not opts.experimental_persistent_cond_cache:
  263. StableDiffusionProcessing.cached_c = [None, None]
  264. StableDiffusionProcessing.cached_uc = [None, None]
  265. def get_token_merging_ratio(self, for_hr=False):
  266. if for_hr:
  267. return self.token_merging_ratio_hr or opts.token_merging_ratio_hr or self.token_merging_ratio or opts.token_merging_ratio
  268. return self.token_merging_ratio or opts.token_merging_ratio
  269. def setup_prompts(self):
  270. if type(self.prompt) == list:
  271. self.all_prompts = self.prompt
  272. else:
  273. self.all_prompts = self.batch_size * self.n_iter * [self.prompt]
  274. if type(self.negative_prompt) == list:
  275. self.all_negative_prompts = self.negative_prompt
  276. else:
  277. self.all_negative_prompts = self.batch_size * \
  278. self.n_iter * [self.negative_prompt]
  279. self.all_prompts = [shared.prompt_styles.apply_styles_to_prompt(
  280. x, self.styles) for x in self.all_prompts]
  281. self.all_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(
  282. x, self.styles) for x in self.all_negative_prompts]
  283. def get_conds_with_caching(self, function, required_prompts, steps, caches, extra_network_data):
  284. """
  285. Returns the result of calling function(shared.sd_model, required_prompts, steps)
  286. using a cache to store the result if the same arguments have been used before.
  287. cache is an array containing two elements. The first element is a tuple
  288. representing the previously used arguments, or None if no arguments
  289. have been used before. The second element is where the previously
  290. computed result is stored.
  291. caches is a list with items described above.
  292. """
  293. cached_params = (
  294. required_prompts,
  295. steps,
  296. opts.CLIP_stop_at_last_layers,
  297. shared.sd_model.sd_checkpoint_info,
  298. extra_network_data,
  299. opts.sdxl_crop_left,
  300. opts.sdxl_crop_top,
  301. self.width,
  302. self.height,
  303. )
  304. for cache in caches:
  305. if cache[0] is not None and cached_params == cache[0]:
  306. return cache[1]
  307. cache = caches[0]
  308. with devices.autocast():
  309. cache[1] = function(shared.sd_model, required_prompts, steps)
  310. cache[0] = cached_params
  311. return cache[1]
  312. def setup_conds(self):
  313. prompts = prompt_parser.SdConditioning(
  314. self.prompts, width=self.width, height=self.height)
  315. negative_prompts = prompt_parser.SdConditioning(
  316. self.negative_prompts, width=self.width, height=self.height, is_negative_prompt=True)
  317. sampler_config = sd_samplers.find_sampler_config(self.sampler_name)
  318. self.step_multiplier = 2 if sampler_config and sampler_config.options.get(
  319. "second_order", False) else 1
  320. self.uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, negative_prompts,
  321. self.steps * self.step_multiplier, [self.cached_uc], self.extra_network_data)
  322. self.c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning,
  323. prompts, self.steps * self.step_multiplier, [self.cached_c], self.extra_network_data)
  324. def parse_extra_network_prompts(self):
  325. self.prompts, self.extra_network_data = extra_networks.parse_prompts(
  326. self.prompts)
  327. class Processed:
  328. def __init__(self, p: StableDiffusionProcessing, images_list, seed=-1, info="", subseed=None, all_prompts=None, all_negative_prompts=None, all_seeds=None, all_subseeds=None, index_of_first_image=0, infotexts=None, comments=""):
  329. self.images = images_list
  330. self.prompt = p.prompt
  331. self.negative_prompt = p.negative_prompt
  332. self.seed = seed
  333. self.subseed = subseed
  334. self.subseed_strength = p.subseed_strength
  335. self.info = info
  336. self.comments = comments
  337. self.width = p.width
  338. self.height = p.height
  339. self.sampler_name = p.sampler_name
  340. self.cfg_scale = p.cfg_scale
  341. self.image_cfg_scale = getattr(p, 'image_cfg_scale', None)
  342. self.steps = p.steps
  343. self.batch_size = p.batch_size
  344. self.restore_faces = p.restore_faces
  345. self.face_restoration_model = opts.face_restoration_model if p.restore_faces else None
  346. self.sd_model_hash = shared.sd_model.sd_model_hash
  347. self.seed_resize_from_w = p.seed_resize_from_w
  348. self.seed_resize_from_h = p.seed_resize_from_h
  349. self.denoising_strength = getattr(p, 'denoising_strength', None)
  350. self.extra_generation_params = p.extra_generation_params
  351. self.index_of_first_image = index_of_first_image
  352. self.styles = p.styles
  353. self.job_timestamp = state.job_timestamp
  354. self.clip_skip = opts.CLIP_stop_at_last_layers
  355. self.token_merging_ratio = p.token_merging_ratio
  356. self.token_merging_ratio_hr = p.token_merging_ratio_hr
  357. self.eta = p.eta
  358. self.ddim_discretize = p.ddim_discretize
  359. self.s_churn = p.s_churn
  360. self.s_tmin = p.s_tmin
  361. self.s_tmax = p.s_tmax
  362. self.s_noise = p.s_noise
  363. self.s_min_uncond = p.s_min_uncond
  364. self.sampler_noise_scheduler_override = p.sampler_noise_scheduler_override
  365. self.prompt = self.prompt if type(
  366. self.prompt) != list else self.prompt[0]
  367. self.negative_prompt = self.negative_prompt if type(
  368. self.negative_prompt) != list else self.negative_prompt[0]
  369. self.seed = int(self.seed if type(self.seed) !=
  370. list else self.seed[0]) if self.seed is not None else -1
  371. self.subseed = int(self.subseed if type(
  372. self.subseed) != list else self.subseed[0]) if self.subseed is not None else -1
  373. self.is_using_inpainting_conditioning = p.is_using_inpainting_conditioning
  374. self.all_prompts = all_prompts or p.all_prompts or [self.prompt]
  375. self.all_negative_prompts = all_negative_prompts or p.all_negative_prompts or [
  376. self.negative_prompt]
  377. self.all_seeds = all_seeds or p.all_seeds or [self.seed]
  378. self.all_subseeds = all_subseeds or p.all_subseeds or [self.subseed]
  379. self.infotexts = infotexts or [info]
  380. def js(self):
  381. obj = {
  382. "prompt": self.all_prompts[0],
  383. "all_prompts": self.all_prompts,
  384. "negative_prompt": self.all_negative_prompts[0],
  385. "all_negative_prompts": self.all_negative_prompts,
  386. "seed": self.seed,
  387. "all_seeds": self.all_seeds,
  388. "subseed": self.subseed,
  389. "all_subseeds": self.all_subseeds,
  390. "subseed_strength": self.subseed_strength,
  391. "width": self.width,
  392. "height": self.height,
  393. "sampler_name": self.sampler_name,
  394. "cfg_scale": self.cfg_scale,
  395. "steps": self.steps,
  396. "batch_size": self.batch_size,
  397. "restore_faces": self.restore_faces,
  398. "face_restoration_model": self.face_restoration_model,
  399. "sd_model_hash": self.sd_model_hash,
  400. "seed_resize_from_w": self.seed_resize_from_w,
  401. "seed_resize_from_h": self.seed_resize_from_h,
  402. "denoising_strength": self.denoising_strength,
  403. "extra_generation_params": self.extra_generation_params,
  404. "index_of_first_image": self.index_of_first_image,
  405. "infotexts": self.infotexts,
  406. "styles": self.styles,
  407. "job_timestamp": self.job_timestamp,
  408. "clip_skip": self.clip_skip,
  409. "is_using_inpainting_conditioning": self.is_using_inpainting_conditioning,
  410. }
  411. return json.dumps(obj)
  412. def infotext(self, p: StableDiffusionProcessing, index):
  413. return create_infotext(p, self.all_prompts, self.all_seeds, self.all_subseeds, comments=[], position_in_batch=index % self.batch_size, iteration=index // self.batch_size)
  414. def get_token_merging_ratio(self, for_hr=False):
  415. return self.token_merging_ratio_hr if for_hr else self.token_merging_ratio
  416. # from https://discuss.pytorch.org/t/help-regarding-slerp-function-for-generative-model-sampling/32475/3
  417. def slerp(val, low, high):
  418. low_norm = low/torch.norm(low, dim=1, keepdim=True)
  419. high_norm = high/torch.norm(high, dim=1, keepdim=True)
  420. dot = (low_norm*high_norm).sum(1)
  421. if dot.mean() > 0.9995:
  422. return low * val + high * (1 - val)
  423. omega = torch.acos(dot)
  424. so = torch.sin(omega)
  425. res = (torch.sin((1.0-val)*omega)/so).unsqueeze(1) * \
  426. low + (torch.sin(val*omega)/so).unsqueeze(1) * high
  427. return res
  428. def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0, p=None):
  429. eta_noise_seed_delta = opts.eta_noise_seed_delta or 0
  430. xs = []
  431. # if we have multiple seeds, this means we are working with batch size>1; this then
  432. # enables the generation of additional tensors with noise that the sampler will use during its processing.
  433. # Using those pre-generated tensors instead of simple torch.randn allows a batch with seeds [100, 101] to
  434. # produce the same images as with two batches [100], [101].
  435. if p is not None and p.sampler is not None and (len(seeds) > 1 and opts.enable_batch_seeds or eta_noise_seed_delta > 0):
  436. sampler_noises = [[]
  437. for _ in range(p.sampler.number_of_needed_noises(p))]
  438. else:
  439. sampler_noises = None
  440. for i, seed in enumerate(seeds):
  441. noise_shape = shape if seed_resize_from_h <= 0 or seed_resize_from_w <= 0 else (
  442. shape[0], seed_resize_from_h//8, seed_resize_from_w//8)
  443. subnoise = None
  444. if subseeds is not None:
  445. subseed = 0 if i >= len(subseeds) else subseeds[i]
  446. subnoise = devices.randn(subseed, noise_shape)
  447. # randn results depend on device; gpu and cpu get different results for same seed;
  448. # the way I see it, it's better to do this on CPU, so that everyone gets same result;
  449. # but the original script had it like this, so I do not dare change it for now because
  450. # it will break everyone's seeds.
  451. noise = devices.randn(seed, noise_shape)
  452. if subnoise is not None:
  453. noise = slerp(subseed_strength, noise, subnoise)
  454. if noise_shape != shape:
  455. x = devices.randn(seed, shape)
  456. dx = (shape[2] - noise_shape[2]) // 2
  457. dy = (shape[1] - noise_shape[1]) // 2
  458. w = noise_shape[2] if dx >= 0 else noise_shape[2] + 2 * dx
  459. h = noise_shape[1] if dy >= 0 else noise_shape[1] + 2 * dy
  460. tx = 0 if dx < 0 else dx
  461. ty = 0 if dy < 0 else dy
  462. dx = max(-dx, 0)
  463. dy = max(-dy, 0)
  464. x[:, ty:ty+h, tx:tx+w] = noise[:, dy:dy+h, dx:dx+w]
  465. noise = x
  466. if sampler_noises is not None:
  467. cnt = p.sampler.number_of_needed_noises(p)
  468. if eta_noise_seed_delta > 0:
  469. torch.manual_seed(seed + eta_noise_seed_delta)
  470. for j in range(cnt):
  471. sampler_noises[j].append(
  472. devices.randn_without_seed(tuple(noise_shape)))
  473. xs.append(noise)
  474. if sampler_noises is not None:
  475. p.sampler.sampler_noises = [torch.stack(n).to(
  476. shared.device) for n in sampler_noises]
  477. x = torch.stack(xs).to(shared.device)
  478. return x
  479. def decode_latent_batch(model, batch, target_device=None, check_for_nans=False):
  480. samples = []
  481. for i in range(batch.shape[0]):
  482. sample = decode_first_stage(model, batch[i:i + 1])[0]
  483. if check_for_nans:
  484. try:
  485. devices.test_for_nans(sample, "vae")
  486. except devices.NansException as e:
  487. if devices.dtype_vae == torch.float32 or not shared.opts.auto_vae_precision:
  488. raise e
  489. errors.print_error_explanation(
  490. "A tensor with all NaNs was produced in VAE.\n"
  491. "Web UI will now convert VAE into 32-bit float and retry.\n"
  492. "To disable this behavior, disable the 'Automaticlly revert VAE to 32-bit floats' setting.\n"
  493. "To always start with 32-bit VAE, use --no-half-vae commandline flag."
  494. )
  495. devices.dtype_vae = torch.float32
  496. model.first_stage_model.to(devices.dtype_vae)
  497. batch = batch.to(devices.dtype_vae)
  498. sample = decode_first_stage(model, batch[i:i + 1])[0]
  499. if target_device is not None:
  500. sample = sample.to(target_device)
  501. samples.append(sample)
  502. return samples
  503. def decode_first_stage(model, x):
  504. x = model.decode_first_stage(x.to(devices.dtype_vae))
  505. return x
  506. def get_fixed_seed(seed):
  507. if seed is None or seed == '' or seed == -1:
  508. return int(random.randrange(4294967294))
  509. return seed
  510. def fix_seed(p):
  511. p.seed = get_fixed_seed(p.seed)
  512. p.subseed = get_fixed_seed(p.subseed)
  513. def program_version():
  514. import launch
  515. res = launch.git_tag()
  516. if res == "<none>":
  517. res = None
  518. return res
  519. def create_infotext(p, all_prompts, all_seeds, all_subseeds, comments=None, iteration=0, position_in_batch=0, use_main_prompt=False, index=None, all_negative_prompts=None):
  520. if index is None:
  521. index = position_in_batch + iteration * p.batch_size
  522. if all_negative_prompts is None:
  523. all_negative_prompts = p.all_negative_prompts
  524. clip_skip = getattr(p, 'clip_skip', opts.CLIP_stop_at_last_layers)
  525. enable_hr = getattr(p, 'enable_hr', False)
  526. token_merging_ratio = p.get_token_merging_ratio()
  527. token_merging_ratio_hr = p.get_token_merging_ratio(for_hr=True)
  528. uses_ensd = opts.eta_noise_seed_delta != 0
  529. if uses_ensd:
  530. uses_ensd = sd_samplers_common.is_sampler_using_eta_noise_seed_delta(p)
  531. generation_params = {
  532. "Steps": p.steps,
  533. "Sampler": p.sampler_name,
  534. "CFG scale": p.cfg_scale,
  535. "Image CFG scale": getattr(p, 'image_cfg_scale', None),
  536. "Seed": p.all_seeds[0] if use_main_prompt else all_seeds[index],
  537. "Face restoration": (opts.face_restoration_model if p.restore_faces else None),
  538. "Size": f"{p.width}x{p.height}",
  539. "Model hash": getattr(p, 'sd_model_hash', None if not opts.add_model_hash_to_info or not shared.sd_model.sd_model_hash else shared.sd_model.sd_model_hash),
  540. "Model": (None if not opts.add_model_name_to_info else shared.sd_model.sd_checkpoint_info.name_for_extra),
  541. "Variation seed": (None if p.subseed_strength == 0 else (p.all_subseeds[0] if use_main_prompt else all_subseeds[index])),
  542. "Variation seed strength": (None if p.subseed_strength == 0 else p.subseed_strength),
  543. "Seed resize from": (None if p.seed_resize_from_w <= 0 or p.seed_resize_from_h <= 0 else f"{p.seed_resize_from_w}x{p.seed_resize_from_h}"),
  544. "Denoising strength": getattr(p, 'denoising_strength', None),
  545. "Conditional mask weight": getattr(p, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) if p.is_using_inpainting_conditioning else None,
  546. "Clip skip": None if clip_skip <= 1 else clip_skip,
  547. "ENSD": opts.eta_noise_seed_delta if uses_ensd else None,
  548. "Token merging ratio": None if token_merging_ratio == 0 else token_merging_ratio,
  549. "Token merging ratio hr": None if not enable_hr or token_merging_ratio_hr == 0 else token_merging_ratio_hr,
  550. "Init image hash": getattr(p, 'init_img_hash', None),
  551. "RNG": opts.randn_source if opts.randn_source != "GPU" else None,
  552. "NGMS": None if p.s_min_uncond == 0 else p.s_min_uncond,
  553. **p.extra_generation_params,
  554. "Version": program_version() if opts.add_version_to_infotext else None,
  555. "User": p.user if opts.add_user_name_to_info else None,
  556. }
  557. generation_params_text = ", ".join(
  558. [k if k == v else f'{k}: {generation_parameters_copypaste.quote(v)}' for k, v in generation_params.items() if v is not None])
  559. prompt_text = p.prompt if use_main_prompt else all_prompts[index]
  560. negative_prompt_text = f"\nNegative prompt: {all_negative_prompts[index]}" if all_negative_prompts[index] else ""
  561. return f"{prompt_text}{negative_prompt_text}\n{generation_params_text}".strip()
  562. def process_images(p: StableDiffusionProcessing) -> Processed:
  563. if p.scripts is not None:
  564. p.scripts.before_process(p)
  565. stored_opts = {k: opts.data[k] for k in p.override_settings.keys()}
  566. try:
  567. # if no checkpoint override or the override checkpoint can't be found, remove override entry and load opts checkpoint
  568. if sd_models.checkpoint_aliases.get(p.override_settings.get('sd_model_checkpoint')) is None:
  569. p.override_settings.pop('sd_model_checkpoint', None)
  570. sd_models.reload_model_weights()
  571. for k, v in p.override_settings.items():
  572. setattr(opts, k, v)
  573. if k == 'sd_model_checkpoint':
  574. sd_models.reload_model_weights()
  575. if k == 'sd_vae':
  576. sd_vae.reload_vae_weights()
  577. sd_models.apply_token_merging(p.sd_model, p.get_token_merging_ratio())
  578. res = process_images_inner(p)
  579. finally:
  580. sd_models.apply_token_merging(p.sd_model, 0)
  581. # restore opts to original state
  582. if p.override_settings_restore_afterwards:
  583. for k, v in stored_opts.items():
  584. setattr(opts, k, v)
  585. if k == 'sd_vae':
  586. sd_vae.reload_vae_weights()
  587. return res
  588. def process_images_inner(p: StableDiffusionProcessing) -> Processed:
  589. """this is the main loop that both txt2img and img2img use; it calls func_init once inside all the scopes and func_sample once per batch"""
  590. if type(p.prompt) == list:
  591. assert (len(p.prompt) > 0)
  592. else:
  593. assert p.prompt is not None
  594. devices.torch_gc()
  595. seed = get_fixed_seed(p.seed)
  596. subseed = get_fixed_seed(p.subseed)
  597. modules.sd_hijack.model_hijack.apply_circular(p.tiling)
  598. modules.sd_hijack.model_hijack.clear_comments()
  599. comments = {}
  600. p.setup_prompts()
  601. if type(seed) == list:
  602. p.all_seeds = seed
  603. else:
  604. p.all_seeds = [int(seed) + (x if p.subseed_strength == 0 else 0)
  605. for x in range(len(p.all_prompts))]
  606. if type(subseed) == list:
  607. p.all_subseeds = subseed
  608. else:
  609. p.all_subseeds = [int(subseed) + x for x in range(len(p.all_prompts))]
  610. if os.path.exists(cmd_opts.embeddings_dir) and not p.do_not_reload_embeddings:
  611. model_hijack.embedding_db.load_textual_inversion_embeddings()
  612. if p.scripts is not None:
  613. p.scripts.process(p)
  614. infotexts = []
  615. output_images = []
  616. with torch.no_grad(), p.sd_model.ema_scope():
  617. with devices.autocast():
  618. p.init(p.all_prompts, p.all_seeds, p.all_subseeds)
  619. # for OSX, loading the model during sampling changes the generated picture, so it is loaded here
  620. if shared.opts.live_previews_enable and opts.show_progress_type == "Approx NN":
  621. sd_vae_approx.model()
  622. sd_unet.apply_unet()
  623. if state.job_count == -1:
  624. state.job_count = p.n_iter
  625. for n in range(p.n_iter):
  626. p.iteration = n
  627. if state.skipped:
  628. state.skipped = False
  629. if state.interrupted:
  630. break
  631. p.prompts = p.all_prompts[n * p.batch_size:(n + 1) * p.batch_size]
  632. p.negative_prompts = p.all_negative_prompts[n *
  633. p.batch_size:(n + 1) * p.batch_size]
  634. p.seeds = p.all_seeds[n * p.batch_size:(n + 1) * p.batch_size]
  635. p.subseeds = p.all_subseeds[n *
  636. p.batch_size:(n + 1) * p.batch_size]
  637. if p.scripts is not None:
  638. p.scripts.before_process_batch(
  639. p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds)
  640. if len(p.prompts) == 0:
  641. break
  642. p.parse_extra_network_prompts()
  643. if not p.disable_extra_networks:
  644. with devices.autocast():
  645. extra_networks.activate(p, p.extra_network_data)
  646. if p.scripts is not None:
  647. p.scripts.process_batch(
  648. p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds)
  649. # params.txt should be saved after scripts.process_batch, since the
  650. # infotext could be modified by that callback
  651. # Example: a wildcard processed by process_batch sets an extra model
  652. # strength, which is saved as "Model Strength: 1.0" in the infotext
  653. if n == 0:
  654. with open(os.path.join(paths.data_path, "params.txt"), "w", encoding="utf8") as file:
  655. processed = Processed(p, [], p.seed, "")
  656. file.write(processed.infotext(p, 0))
  657. p.setup_conds()
  658. for comment in model_hijack.comments:
  659. comments[comment] = 1
  660. p.extra_generation_params.update(
  661. model_hijack.extra_generation_params)
  662. if p.n_iter > 1:
  663. shared.state.job = f"Batch {n+1} out of {p.n_iter}"
  664. with devices.without_autocast() if devices.unet_needs_upcast else devices.autocast():
  665. samples_ddim = p.sample(conditioning=p.c, unconditional_conditioning=p.uc, seeds=p.seeds,
  666. subseeds=p.subseeds, subseed_strength=p.subseed_strength, prompts=p.prompts)
  667. x_samples_ddim = decode_latent_batch(
  668. p.sd_model, samples_ddim, target_device=devices.cpu, check_for_nans=True)
  669. x_samples_ddim = torch.stack(x_samples_ddim).float()
  670. x_samples_ddim = torch.clamp(
  671. (x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
  672. del samples_ddim
  673. if lowvram.is_enabled(shared.sd_model):
  674. lowvram.send_everything_to_cpu()
  675. devices.torch_gc()
  676. if p.scripts is not None:
  677. p.scripts.postprocess_batch(p, x_samples_ddim, batch_number=n)
  678. p.prompts = p.all_prompts[n *
  679. p.batch_size:(n + 1) * p.batch_size]
  680. p.negative_prompts = p.all_negative_prompts[n *
  681. p.batch_size:(n + 1) * p.batch_size]
  682. batch_params = scripts.PostprocessBatchListArgs(
  683. list(x_samples_ddim))
  684. p.scripts.postprocess_batch_list(
  685. p, batch_params, batch_number=n)
  686. x_samples_ddim = batch_params.images
  687. def infotext(index=0, use_main_prompt=False):
  688. return create_infotext(p, p.prompts, p.seeds, p.subseeds, use_main_prompt=use_main_prompt, index=index, all_negative_prompts=p.negative_prompts)
  689. for i, x_sample in enumerate(x_samples_ddim):
  690. p.batch_index = i
  691. x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2)
  692. x_sample = x_sample.astype(np.uint8)
  693. if p.restore_faces:
  694. if opts.save and not p.do_not_save_samples and opts.save_images_before_face_restoration:
  695. images.save_image(Image.fromarray(x_sample), p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(
  696. i), p=p, suffix="-before-face-restoration")
  697. devices.torch_gc()
  698. x_sample = modules.face_restoration.restore_faces(x_sample)
  699. devices.torch_gc()
  700. image = Image.fromarray(x_sample)
  701. if p.scripts is not None:
  702. pp = scripts.PostprocessImageArgs(image)
  703. p.scripts.postprocess_image(p, pp)
  704. image = pp.image
  705. if p.color_corrections is not None and i < len(p.color_corrections):
  706. if opts.save and not p.do_not_save_samples and opts.save_images_before_color_correction:
  707. image_without_cc = apply_overlay(
  708. image, p.paste_to, i, p.overlay_images)
  709. images.save_image(image_without_cc, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(
  710. i), p=p, suffix="-before-color-correction")
  711. image = apply_color_correction(
  712. p.color_corrections[i], image)
  713. image = apply_overlay(image, p.paste_to, i, p.overlay_images)
  714. if opts.samples_save and not p.do_not_save_samples:
  715. images.save_image(
  716. image, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p)
  717. text = infotext(i)
  718. infotexts.append(text)
  719. if opts.enable_pnginfo:
  720. image.info["parameters"] = text
  721. output_images.append(image)
  722. if hasattr(p, 'mask_for_overlay') and p.mask_for_overlay and any([opts.save_mask, opts.save_mask_composite, opts.return_mask, opts.return_mask_composite]):
  723. image_mask = p.mask_for_overlay.convert('RGB')
  724. image_mask_composite = Image.composite(image.convert('RGBA').convert('RGBa'), Image.new(
  725. 'RGBa', image.size), images.resize_image(2, p.mask_for_overlay, image.width, image.height).convert('L')).convert('RGBA')
  726. if opts.save_mask:
  727. images.save_image(image_mask, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(
  728. i), p=p, suffix="-mask")
  729. if opts.save_mask_composite:
  730. images.save_image(image_mask_composite, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(
  731. i), p=p, suffix="-mask-composite")
  732. if opts.return_mask:
  733. output_images.append(image_mask)
  734. if opts.return_mask_composite:
  735. output_images.append(image_mask_composite)
  736. del x_samples_ddim
  737. devices.torch_gc()
  738. state.nextjob()
  739. p.color_corrections = None
  740. index_of_first_image = 0
  741. unwanted_grid_because_of_img_count = len(
  742. output_images) < 2 and opts.grid_only_if_multiple
  743. if (opts.return_grid or opts.grid_save) and not p.do_not_save_grid and not unwanted_grid_because_of_img_count:
  744. grid = images.image_grid(output_images, p.batch_size)
  745. if opts.return_grid:
  746. text = infotext(use_main_prompt=True)
  747. infotexts.insert(0, text)
  748. if opts.enable_pnginfo:
  749. grid.info["parameters"] = text
  750. output_images.insert(0, grid)
  751. index_of_first_image = 1
  752. if opts.grid_save:
  753. images.save_image(grid, p.outpath_grids, "grid", p.all_seeds[0], p.all_prompts[0], opts.grid_format, info=infotext(
  754. use_main_prompt=True), short_filename=not opts.grid_extended_filename, p=p, grid=True)
  755. if not p.disable_extra_networks and p.extra_network_data:
  756. extra_networks.deactivate(p, p.extra_network_data)
  757. devices.torch_gc()
  758. res = Processed(
  759. p,
  760. images_list=output_images,
  761. seed=p.all_seeds[0],
  762. info=infotexts[0],
  763. comments="".join(f"{comment}\n" for comment in comments),
  764. subseed=p.all_subseeds[0],
  765. index_of_first_image=index_of_first_image,
  766. infotexts=infotexts,
  767. )
  768. if p.scripts is not None:
  769. p.scripts.postprocess(p, res)
  770. return res
  771. def old_hires_fix_first_pass_dimensions(width, height):
  772. """old algorithm for auto-calculating first pass size"""
  773. desired_pixel_count = 512 * 512
  774. actual_pixel_count = width * height
  775. scale = math.sqrt(desired_pixel_count / actual_pixel_count)
  776. width = math.ceil(scale * width / 64) * 64
  777. height = math.ceil(scale * height / 64) * 64
  778. return width, height
  779. class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
  780. sampler = None
  781. cached_hr_uc = [None, None]
  782. cached_hr_c = [None, None]
  783. def __init__(self, enable_hr: bool = False, denoising_strength: float = 0.75, firstphase_width: int = 0, firstphase_height: int = 0, hr_scale: float = 2.0, hr_upscaler: str = None, hr_second_pass_steps: int = 0, hr_resize_x: int = 0, hr_resize_y: int = 0, hr_sampler_name: str = None, hr_prompt: str = '', hr_negative_prompt: str = '', task_id: str = None, **kwargs):
  784. super().__init__(**kwargs)
  785. self.enable_hr = enable_hr
  786. self.denoising_strength = denoising_strength
  787. self.hr_scale = hr_scale
  788. self.hr_upscaler = hr_upscaler
  789. self.hr_second_pass_steps = hr_second_pass_steps
  790. self.hr_resize_x = hr_resize_x
  791. self.hr_resize_y = hr_resize_y
  792. self.hr_upscale_to_x = hr_resize_x
  793. self.hr_upscale_to_y = hr_resize_y
  794. self.hr_sampler_name = hr_sampler_name
  795. self.hr_prompt = hr_prompt
  796. self.hr_negative_prompt = hr_negative_prompt
  797. self.all_hr_prompts = None
  798. self.all_hr_negative_prompts = None
  799. if firstphase_width != 0 or firstphase_height != 0:
  800. self.hr_upscale_to_x = self.width
  801. self.hr_upscale_to_y = self.height
  802. self.width = firstphase_width
  803. self.height = firstphase_height
  804. self.truncate_x = 0
  805. self.truncate_y = 0
  806. self.applied_old_hires_behavior_to = None
  807. self.hr_prompts = None
  808. self.hr_negative_prompts = None
  809. self.hr_extra_network_data = None
  810. self.cached_hr_uc = StableDiffusionProcessingTxt2Img.cached_hr_uc
  811. self.cached_hr_c = StableDiffusionProcessingTxt2Img.cached_hr_c
  812. self.hr_c = None
  813. self.hr_uc = None
  814. def init(self, all_prompts, all_seeds, all_subseeds):
  815. if self.enable_hr:
  816. if self.hr_sampler_name is not None and self.hr_sampler_name != self.sampler_name:
  817. self.extra_generation_params["Hires sampler"] = self.hr_sampler_name
  818. if tuple(self.hr_prompt) != tuple(self.prompt):
  819. self.extra_generation_params["Hires prompt"] = self.hr_prompt
  820. if tuple(self.hr_negative_prompt) != tuple(self.negative_prompt):
  821. self.extra_generation_params["Hires negative prompt"] = self.hr_negative_prompt
  822. if opts.use_old_hires_fix_width_height and self.applied_old_hires_behavior_to != (self.width, self.height):
  823. self.hr_resize_x = self.width
  824. self.hr_resize_y = self.height
  825. self.hr_upscale_to_x = self.width
  826. self.hr_upscale_to_y = self.height
  827. self.width, self.height = old_hires_fix_first_pass_dimensions(
  828. self.width, self.height)
  829. self.applied_old_hires_behavior_to = (self.width, self.height)
  830. if self.hr_resize_x == 0 and self.hr_resize_y == 0:
  831. self.extra_generation_params["Hires upscale"] = self.hr_scale
  832. self.hr_upscale_to_x = int(self.width * self.hr_scale)
  833. self.hr_upscale_to_y = int(self.height * self.hr_scale)
  834. else:
  835. self.extra_generation_params["Hires resize"] = f"{self.hr_resize_x}x{self.hr_resize_y}"
  836. if self.hr_resize_y == 0:
  837. self.hr_upscale_to_x = self.hr_resize_x
  838. self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width
  839. elif self.hr_resize_x == 0:
  840. self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height
  841. self.hr_upscale_to_y = self.hr_resize_y
  842. else:
  843. target_w = self.hr_resize_x
  844. target_h = self.hr_resize_y
  845. src_ratio = self.width / self.height
  846. dst_ratio = self.hr_resize_x / self.hr_resize_y
  847. if src_ratio < dst_ratio:
  848. self.hr_upscale_to_x = self.hr_resize_x
  849. self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width
  850. else:
  851. self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height
  852. self.hr_upscale_to_y = self.hr_resize_y
  853. self.truncate_x = (
  854. self.hr_upscale_to_x - target_w) // opt_f
  855. self.truncate_y = (
  856. self.hr_upscale_to_y - target_h) // opt_f
  857. # special case: the user has chosen to do nothing
  858. if self.hr_upscale_to_x == self.width and self.hr_upscale_to_y == self.height:
  859. self.enable_hr = False
  860. self.denoising_strength = None
  861. self.extra_generation_params.pop("Hires upscale", None)
  862. self.extra_generation_params.pop("Hires resize", None)
  863. return
  864. if not state.processing_has_refined_job_count:
  865. if state.job_count == -1:
  866. state.job_count = self.n_iter
  867. shared.total_tqdm.updateTotal(
  868. (self.steps + (self.hr_second_pass_steps or self.steps)) * state.job_count)
  869. state.job_count = state.job_count * 2
  870. state.processing_has_refined_job_count = True
  871. if self.hr_second_pass_steps:
  872. self.extra_generation_params["Hires steps"] = self.hr_second_pass_steps
  873. if self.hr_upscaler is not None:
  874. self.extra_generation_params["Hires upscaler"] = self.hr_upscaler
  875. def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts):
  876. self.sampler = sd_samplers.create_sampler(
  877. self.sampler_name, self.sd_model)
  878. latent_scale_mode = shared.latent_upscale_modes.get(
  879. self.hr_upscaler, None) if self.hr_upscaler is not None else shared.latent_upscale_modes.get(shared.latent_upscale_default_mode, "nearest")
  880. if self.enable_hr and latent_scale_mode is None:
  881. if not any(x.name == self.hr_upscaler for x in shared.sd_upscalers):
  882. raise Exception(
  883. f"could not find upscaler named {self.hr_upscaler}")
  884. x = create_random_tensors([opt_C, self.height // opt_f, self.width // opt_f], seeds=seeds, subseeds=subseeds,
  885. subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w, p=self)
  886. samples = self.sampler.sample(self, x, conditioning, unconditional_conditioning,
  887. image_conditioning=self.txt2img_image_conditioning(x))
  888. if not self.enable_hr:
  889. return samples
  890. self.is_hr_pass = True
  891. target_width = self.hr_upscale_to_x
  892. target_height = self.hr_upscale_to_y
  893. def save_intermediate(image, index):
  894. """saves image before applying hires fix, if enabled in options; takes as an argument either an image or batch with latent space images"""
  895. if not opts.save or self.do_not_save_samples or not opts.save_images_before_highres_fix:
  896. return
  897. if not isinstance(image, Image.Image):
  898. image = sd_samplers.sample_to_image(
  899. image, index, approximation=0)
  900. info = create_infotext(self, self.all_prompts, self.all_seeds, self.all_subseeds, [
  901. ], iteration=self.iteration, position_in_batch=index)
  902. images.save_image(image, self.outpath_samples, "",
  903. seeds[index], prompts[index], opts.samples_format, info=info, p=self, suffix="-before-highres-fix")
  904. if latent_scale_mode is not None:
  905. for i in range(samples.shape[0]):
  906. save_intermediate(samples, i)
  907. samples = torch.nn.functional.interpolate(samples, size=(
  908. target_height // opt_f, target_width // opt_f), mode=latent_scale_mode["mode"], antialias=latent_scale_mode["antialias"])
  909. # Avoid making the inpainting conditioning unless necessary as
  910. # this does need some extra compute to decode / encode the image again.
  911. if getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) < 1.0:
  912. image_conditioning = self.img2img_image_conditioning(
  913. decode_first_stage(self.sd_model, samples), samples)
  914. else:
  915. image_conditioning = self.txt2img_image_conditioning(samples)
  916. else:
  917. decoded_samples = decode_first_stage(self.sd_model, samples)
  918. lowres_samples = torch.clamp(
  919. (decoded_samples + 1.0) / 2.0, min=0.0, max=1.0)
  920. batch_images = []
  921. for i, x_sample in enumerate(lowres_samples):
  922. x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2)
  923. x_sample = x_sample.astype(np.uint8)
  924. image = Image.fromarray(x_sample)
  925. save_intermediate(image, i)
  926. image = images.resize_image(
  927. 0, image, target_width, target_height, upscaler_name=self.hr_upscaler)
  928. image = np.array(image).astype(np.float32) / 255.0
  929. image = np.moveaxis(image, 2, 0)
  930. batch_images.append(image)
  931. decoded_samples = torch.from_numpy(np.array(batch_images))
  932. decoded_samples = decoded_samples.to(shared.device)
  933. decoded_samples = 2. * decoded_samples - 1.
  934. samples = self.sd_model.get_first_stage_encoding(
  935. self.sd_model.encode_first_stage(decoded_samples))
  936. image_conditioning = self.img2img_image_conditioning(
  937. decoded_samples, samples)
  938. shared.state.nextjob()
  939. img2img_sampler_name = self.hr_sampler_name or self.sampler_name
  940. # PLMS/UniPC do not support img2img so we just silently switch to DDIM
  941. if self.sampler_name in ['PLMS', 'UniPC']:
  942. img2img_sampler_name = 'DDIM'
  943. self.sampler = sd_samplers.create_sampler(
  944. img2img_sampler_name, self.sd_model)
  945. samples = samples[:, :, self.truncate_y//2:samples.shape[2]-(
  946. self.truncate_y+1)//2, self.truncate_x//2:samples.shape[3]-(self.truncate_x+1)//2]
  947. noise = create_random_tensors(
  948. samples.shape[1:], seeds=seeds, subseeds=subseeds, subseed_strength=subseed_strength, p=self)
  949. # GC now before running the next img2img to prevent running out of memory
  950. x = None
  951. devices.torch_gc()
  952. if not self.disable_extra_networks:
  953. with devices.autocast():
  954. extra_networks.activate(self, self.hr_extra_network_data)
  955. with devices.autocast():
  956. self.calculate_hr_conds()
  957. sd_models.apply_token_merging(
  958. self.sd_model, self.get_token_merging_ratio(for_hr=True))
  959. if self.scripts is not None:
  960. self.scripts.before_hr(self)
  961. samples = self.sampler.sample_img2img(self, samples, noise, self.hr_c, self.hr_uc,
  962. steps=self.hr_second_pass_steps or self.steps, image_conditioning=image_conditioning)
  963. sd_models.apply_token_merging(
  964. self.sd_model, self.get_token_merging_ratio())
  965. self.is_hr_pass = False
  966. return samples
  967. def close(self):
  968. super().close()
  969. self.hr_c = None
  970. self.hr_uc = None
  971. if not opts.experimental_persistent_cond_cache:
  972. StableDiffusionProcessingTxt2Img.cached_hr_uc = [None, None]
  973. StableDiffusionProcessingTxt2Img.cached_hr_c = [None, None]
  974. def setup_prompts(self):
  975. super().setup_prompts()
  976. if not self.enable_hr:
  977. return
  978. if self.hr_prompt == '':
  979. self.hr_prompt = self.prompt
  980. if self.hr_negative_prompt == '':
  981. self.hr_negative_prompt = self.negative_prompt
  982. if type(self.hr_prompt) == list:
  983. self.all_hr_prompts = self.hr_prompt
  984. else:
  985. self.all_hr_prompts = self.batch_size * \
  986. self.n_iter * [self.hr_prompt]
  987. if type(self.hr_negative_prompt) == list:
  988. self.all_hr_negative_prompts = self.hr_negative_prompt
  989. else:
  990. self.all_hr_negative_prompts = self.batch_size * \
  991. self.n_iter * [self.hr_negative_prompt]
  992. self.all_hr_prompts = [shared.prompt_styles.apply_styles_to_prompt(
  993. x, self.styles) for x in self.all_hr_prompts]
  994. self.all_hr_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(
  995. x, self.styles) for x in self.all_hr_negative_prompts]
  996. def calculate_hr_conds(self):
  997. if self.hr_c is not None:
  998. return
  999. self.hr_uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, self.hr_negative_prompts,
  1000. self.steps * self.step_multiplier, [self.cached_hr_uc, self.cached_uc], self.hr_extra_network_data)
  1001. self.hr_c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, self.hr_prompts,
  1002. self.steps * self.step_multiplier, [self.cached_hr_c, self.cached_c], self.hr_extra_network_data)
  1003. def setup_conds(self):
  1004. super().setup_conds()
  1005. self.hr_uc = None
  1006. self.hr_c = None
  1007. if self.enable_hr:
  1008. if shared.opts.hires_fix_use_firstpass_conds:
  1009. self.calculate_hr_conds()
  1010. # if in lowvram mode, we need to calculate conds right away, before the cond NN is unloaded
  1011. elif lowvram.is_enabled(shared.sd_model):
  1012. with devices.autocast():
  1013. extra_networks.activate(self, self.hr_extra_network_data)
  1014. self.calculate_hr_conds()
  1015. with devices.autocast():
  1016. extra_networks.activate(self, self.extra_network_data)
  1017. def parse_extra_network_prompts(self):
  1018. res = super().parse_extra_network_prompts()
  1019. if self.enable_hr:
  1020. self.hr_prompts = self.all_hr_prompts[self.iteration *
  1021. self.batch_size:(self.iteration + 1) * self.batch_size]
  1022. self.hr_negative_prompts = self.all_hr_negative_prompts[self.iteration * self.batch_size:(
  1023. self.iteration + 1) * self.batch_size]
  1024. self.hr_prompts, self.hr_extra_network_data = extra_networks.parse_prompts(
  1025. self.hr_prompts)
  1026. return res
  1027. class StableDiffusionProcessingImg2Img(StableDiffusionProcessing):
  1028. sampler = None
  1029. def __init__(self, init_images: list = None, resize_mode: int = 0, denoising_strength: float = 0.75, image_cfg_scale: float = None, mask: Any = None, mask_blur: int = None, mask_blur_x: int = 4, mask_blur_y: int = 4, inpainting_fill: int = 0, inpaint_full_res: bool = True, inpaint_full_res_padding: int = 0, inpainting_mask_invert: int = 0, initial_noise_multiplier: float = None, task_id: str = None, **kwargs):
  1030. super().__init__(**kwargs)
  1031. self.init_images = init_images
  1032. self.resize_mode: int = resize_mode
  1033. self.denoising_strength: float = denoising_strength
  1034. self.image_cfg_scale: float = image_cfg_scale if shared.sd_model.cond_stage_key == "edit" else None
  1035. self.init_latent = None
  1036. self.image_mask = mask
  1037. self.latent_mask = None
  1038. self.mask_for_overlay = None
  1039. if mask_blur is not None:
  1040. mask_blur_x = mask_blur
  1041. mask_blur_y = mask_blur
  1042. self.mask_blur_x = mask_blur_x
  1043. self.mask_blur_y = mask_blur_y
  1044. self.inpainting_fill = inpainting_fill
  1045. self.inpaint_full_res = inpaint_full_res
  1046. self.inpaint_full_res_padding = inpaint_full_res_padding
  1047. self.inpainting_mask_invert = inpainting_mask_invert
  1048. self.initial_noise_multiplier = opts.initial_noise_multiplier if initial_noise_multiplier is None else initial_noise_multiplier
  1049. self.mask = None
  1050. self.nmask = None
  1051. self.image_conditioning = None
  1052. def init(self, all_prompts, all_seeds, all_subseeds):
  1053. self.sampler = sd_samplers.create_sampler(
  1054. self.sampler_name, self.sd_model)
  1055. crop_region = None
  1056. image_mask = self.image_mask
  1057. if image_mask is not None:
  1058. image_mask = image_mask.convert('L')
  1059. if self.inpainting_mask_invert:
  1060. image_mask = ImageOps.invert(image_mask)
  1061. if self.mask_blur_x > 0:
  1062. np_mask = np.array(image_mask)
  1063. kernel_size = 2 * int(4 * self.mask_blur_x + 0.5) + 1
  1064. np_mask = cv2.GaussianBlur(
  1065. np_mask, (kernel_size, 1), self.mask_blur_x)
  1066. image_mask = Image.fromarray(np_mask)
  1067. if self.mask_blur_y > 0:
  1068. np_mask = np.array(image_mask)
  1069. kernel_size = 2 * int(4 * self.mask_blur_y + 0.5) + 1
  1070. np_mask = cv2.GaussianBlur(
  1071. np_mask, (1, kernel_size), self.mask_blur_y)
  1072. image_mask = Image.fromarray(np_mask)
  1073. if self.inpaint_full_res:
  1074. self.mask_for_overlay = image_mask
  1075. mask = image_mask.convert('L')
  1076. crop_region = masking.get_crop_region(
  1077. np.array(mask), self.inpaint_full_res_padding)
  1078. crop_region = masking.expand_crop_region(
  1079. crop_region, self.width, self.height, mask.width, mask.height)
  1080. x1, y1, x2, y2 = crop_region
  1081. mask = mask.crop(crop_region)
  1082. image_mask = images.resize_image(
  1083. 2, mask, self.width, self.height)
  1084. self.paste_to = (x1, y1, x2-x1, y2-y1)
  1085. else:
  1086. image_mask = images.resize_image(
  1087. self.resize_mode, image_mask, self.width, self.height)
  1088. np_mask = np.array(image_mask)
  1089. np_mask = np.clip((np_mask.astype(np.float32))
  1090. * 2, 0, 255).astype(np.uint8)
  1091. self.mask_for_overlay = Image.fromarray(np_mask)
  1092. self.overlay_images = []
  1093. latent_mask = self.latent_mask if self.latent_mask is not None else image_mask
  1094. add_color_corrections = opts.img2img_color_correction and self.color_corrections is None
  1095. if add_color_corrections:
  1096. self.color_corrections = []
  1097. imgs = []
  1098. for img in self.init_images:
  1099. # Save init image
  1100. if opts.save_init_img:
  1101. self.init_img_hash = hashlib.md5(img.tobytes()).hexdigest()
  1102. images.save_image(img, path=opts.outdir_init_images, basename=None,
  1103. forced_filename=self.init_img_hash, save_to_dirs=False)
  1104. image = images.flatten(img, opts.img2img_background_color)
  1105. if crop_region is None and self.resize_mode != 3:
  1106. image = images.resize_image(
  1107. self.resize_mode, image, self.width, self.height)
  1108. if image_mask is not None:
  1109. image_masked = Image.new('RGBa', (image.width, image.height))
  1110. image_masked.paste(image.convert("RGBA").convert(
  1111. "RGBa"), mask=ImageOps.invert(self.mask_for_overlay.convert('L')))
  1112. self.overlay_images.append(image_masked.convert('RGBA'))
  1113. # crop_region is not None if we are doing inpaint full res
  1114. if crop_region is not None:
  1115. image = image.crop(crop_region)
  1116. image = images.resize_image(2, image, self.width, self.height)
  1117. if image_mask is not None:
  1118. if self.inpainting_fill != 1:
  1119. image = masking.fill(image, latent_mask)
  1120. if add_color_corrections:
  1121. self.color_corrections.append(setup_color_correction(image))
  1122. image = np.array(image).astype(np.float32) / 255.0
  1123. image = np.moveaxis(image, 2, 0)
  1124. imgs.append(image)
  1125. if len(imgs) == 1:
  1126. batch_images = np.expand_dims(
  1127. imgs[0], axis=0).repeat(self.batch_size, axis=0)
  1128. if self.overlay_images is not None:
  1129. self.overlay_images = self.overlay_images * self.batch_size
  1130. if self.color_corrections is not None and len(self.color_corrections) == 1:
  1131. self.color_corrections = self.color_corrections * self.batch_size
  1132. elif len(imgs) <= self.batch_size:
  1133. self.batch_size = len(imgs)
  1134. batch_images = np.array(imgs)
  1135. else:
  1136. raise RuntimeError(
  1137. f"bad number of images passed: {len(imgs)}; expecting {self.batch_size} or less")
  1138. image = torch.from_numpy(batch_images)
  1139. image = 2. * image - 1.
  1140. image = image.to(shared.device, dtype=devices.dtype_vae)
  1141. self.init_latent = self.sd_model.get_first_stage_encoding(
  1142. self.sd_model.encode_first_stage(image))
  1143. if self.resize_mode == 3:
  1144. self.init_latent = torch.nn.functional.interpolate(self.init_latent, size=(
  1145. self.height // opt_f, self.width // opt_f), mode="bilinear")
  1146. if image_mask is not None:
  1147. init_mask = latent_mask
  1148. latmask = init_mask.convert('RGB').resize(
  1149. (self.init_latent.shape[3], self.init_latent.shape[2]))
  1150. latmask = np.moveaxis(
  1151. np.array(latmask, dtype=np.float32), 2, 0) / 255
  1152. latmask = latmask[0]
  1153. latmask = np.around(latmask)
  1154. latmask = np.tile(latmask[None], (4, 1, 1))
  1155. self.mask = torch.asarray(
  1156. 1.0 - latmask).to(shared.device).type(self.sd_model.dtype)
  1157. self.nmask = torch.asarray(latmask).to(
  1158. shared.device).type(self.sd_model.dtype)
  1159. # this needs to be fixed to be done in sample() using actual seeds for batches
  1160. if self.inpainting_fill == 2:
  1161. self.init_latent = self.init_latent * self.mask + create_random_tensors(
  1162. self.init_latent.shape[1:], all_seeds[0:self.init_latent.shape[0]]) * self.nmask
  1163. elif self.inpainting_fill == 3:
  1164. self.init_latent = self.init_latent * self.mask
  1165. self.image_conditioning = self.img2img_image_conditioning(
  1166. image, self.init_latent, image_mask)
  1167. def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts):
  1168. x = create_random_tensors([opt_C, self.height // opt_f, self.width // opt_f], seeds=seeds, subseeds=subseeds,
  1169. subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w, p=self)
  1170. if self.initial_noise_multiplier != 1.0:
  1171. self.extra_generation_params["Noise multiplier"] = self.initial_noise_multiplier
  1172. x *= self.initial_noise_multiplier
  1173. samples = self.sampler.sample_img2img(
  1174. self, self.init_latent, x, conditioning, unconditional_conditioning, image_conditioning=self.image_conditioning)
  1175. if self.mask is not None:
  1176. samples = samples * self.nmask + self.init_latent * self.mask
  1177. del x
  1178. devices.torch_gc()
  1179. return samples
  1180. def get_token_merging_ratio(self, for_hr=False):
  1181. return self.token_merging_ratio or ("token_merging_ratio" in self.override_settings and opts.token_merging_ratio) or opts.token_merging_ratio_img2img or opts.token_merging_ratio