processing.py 74 KB

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