processing.py 78 KB

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