processing.py 73 KB

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