diffusers/community-pipelines-mirror
Community Pipeline Examples For more information about community pipelines, please have a look at this issue. Community pipeline examples consist pipelines that have been added by the community. Please have a look at the following tables to get an overview of all community examples. Click on the Code Example to get a copy-and-paste ready code example that you can try out. If a community pipeline doesn't work as expected, please open an issue and ping the author on it. Please… See the full description on the dataset page: https://huggingface.co/datasets/diffusers/community-pipelines-mirror.
922k
1# Copyright 2024 The HuggingFace Team. All rights reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14 15import inspect16from typing import Any, Callable, Dict, List, Optional, Union17 18import intel_extension_for_pytorch as ipex19import torch20from packaging import version21from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer22 23from diffusers.configuration_utils import FrozenDict24from diffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin25from diffusers.models import AutoencoderKL, UNet2DConditionModel26from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin27from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput28from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker29from diffusers.schedulers import KarrasDiffusionSchedulers30from diffusers.utils import (31 deprecate,32 logging,33 replace_example_docstring,34)35from diffusers.utils.torch_utils import randn_tensor36 37 38logger = logging.get_logger(__name__) # pylint: disable=invalid-name39 40EXAMPLE_DOC_STRING = """41 Examples:42 ```py43 >>> import torch44 >>> from diffusers import StableDiffusionPipeline45 46 >>> pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", custom_pipeline="stable_diffusion_ipex")47 48 >>> # For Float3249 >>> pipe.prepare_for_ipex(prompt, dtype=torch.float32, height=512, width=512) #value of image height/width should be consistent with the pipeline inference50 >>> # For BFloat1651 >>> pipe.prepare_for_ipex(prompt, dtype=torch.bfloat16, height=512, width=512) #value of image height/width should be consistent with the pipeline inference52 53 >>> prompt = "a photo of an astronaut riding a horse on mars"54 >>> # For Float3255 >>> image = pipe(prompt, num_inference_steps=num_inference_steps, height=512, width=512).images[0] #value of image height/width should be consistent with 'prepare_for_ipex()'56 >>> # For BFloat1657 >>> with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16):58 >>> image = pipe(prompt, num_inference_steps=num_inference_steps, height=512, width=512).images[0] #value of image height/width should be consistent with 'prepare_for_ipex()'59 ```60"""61 62 63class StableDiffusionIPEXPipeline(64 DiffusionPipeline, StableDiffusionMixin, TextualInversionLoaderMixin, LoraLoaderMixin65):66 r"""67 Pipeline for text-to-image generation using Stable Diffusion on IPEX.68 69 This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the70 library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)71 72 Args:73 vae ([`AutoencoderKL`]):74 Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.75 text_encoder ([`CLIPTextModel`]):76 Frozen text-encoder. Stable Diffusion uses the text portion of77 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically78 the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.79 tokenizer (`CLIPTokenizer`):80 Tokenizer of class81 [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).82 unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.83 scheduler ([`SchedulerMixin`]):84 A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of85 [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].86 safety_checker ([`StableDiffusionSafetyChecker`]):87 Classification module that estimates whether generated images could be considered offensive or harmful.88 Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.89 feature_extractor ([`CLIPFeatureExtractor`]):90 Model that extracts features from generated images to be used as inputs for the `safety_checker`.91 """92 93 _optional_components = ["safety_checker", "feature_extractor"]94 95 def __init__(96 self,97 vae: AutoencoderKL,98 text_encoder: CLIPTextModel,99 tokenizer: CLIPTokenizer,100 unet: UNet2DConditionModel,101 scheduler: KarrasDiffusionSchedulers,102 safety_checker: StableDiffusionSafetyChecker,103 feature_extractor: CLIPFeatureExtractor,104 requires_safety_checker: bool = True,105 ):106 super().__init__()107 108 if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:109 deprecation_message = (110 f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"111 f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "112 "to update the config accordingly as leaving `steps_offset` might led to incorrect results"113 " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"114 " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"115 " file"116 )117 deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)118 new_config = dict(scheduler.config)119 new_config["steps_offset"] = 1120 scheduler._internal_dict = FrozenDict(new_config)121 122 if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:123 deprecation_message = (124 f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."125 " `clip_sample` should be set to False in the configuration file. Please make sure to update the"126 " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"127 " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"128 " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"129 )130 deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)131 new_config = dict(scheduler.config)132 new_config["clip_sample"] = False133 scheduler._internal_dict = FrozenDict(new_config)134 135 if safety_checker is None and requires_safety_checker:136 logger.warning(137 f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"138 " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"139 " results in services or applications open to the public. Both the diffusers team and Hugging Face"140 " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"141 " it only for use-cases that involve analyzing network behavior or auditing its results. For more"142 " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."143 )144 145 if safety_checker is not None and feature_extractor is None:146 raise ValueError(147 "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"148 " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."149 )150 151 is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(152 version.parse(unet.config._diffusers_version).base_version153 ) < version.parse("0.9.0.dev0")154 is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64155 if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:156 deprecation_message = (157 "The configuration file of the unet has set the default `sample_size` to smaller than"158 " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"159 " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"160 " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"161 " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"162 " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"163 " in the config might lead to incorrect results in future versions. If you have downloaded this"164 " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"165 " the `unet/config.json` file"166 )167 deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)168 new_config = dict(unet.config)169 new_config["sample_size"] = 64170 unet._internal_dict = FrozenDict(new_config)171 172 self.register_modules(173 vae=vae,174 text_encoder=text_encoder,175 tokenizer=tokenizer,176 unet=unet,177 scheduler=scheduler,178 safety_checker=safety_checker,179 feature_extractor=feature_extractor,180 )181 self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)182 self.register_to_config(requires_safety_checker=requires_safety_checker)183 184 def get_input_example(self, prompt, height=None, width=None, guidance_scale=7.5, num_images_per_prompt=1):185 prompt_embeds = None186 negative_prompt_embeds = None187 negative_prompt = None188 callback_steps = 1189 generator = None190 latents = None191 192 # 0. Default height and width to unet193 height = height or self.unet.config.sample_size * self.vae_scale_factor194 width = width or self.unet.config.sample_size * self.vae_scale_factor195 196 # 1. Check inputs. Raise error if not correct197 self.check_inputs(198 prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds199 )200 201 # 2. Define call parameters202 if prompt is not None and isinstance(prompt, str):203 batch_size = 1204 elif prompt is not None and isinstance(prompt, list):205 batch_size = len(prompt)206 207 device = "cpu"208 # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)209 # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`210 # corresponds to doing no classifier free guidance.211 do_classifier_free_guidance = guidance_scale > 1.0212 213 # 3. Encode input prompt214 prompt_embeds = self._encode_prompt(215 prompt,216 device,217 num_images_per_prompt,218 do_classifier_free_guidance,219 negative_prompt,220 prompt_embeds=prompt_embeds,221 negative_prompt_embeds=negative_prompt_embeds,222 )223 224 # 5. Prepare latent variables225 latents = self.prepare_latents(226 batch_size * num_images_per_prompt,227 self.unet.config.in_channels,228 height,229 width,230 prompt_embeds.dtype,231 device,232 generator,233 latents,234 )235 dummy = torch.ones(1, dtype=torch.int32)236 latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents237 latent_model_input = self.scheduler.scale_model_input(latent_model_input, dummy)238 239 unet_input_example = (latent_model_input, dummy, prompt_embeds)240 vae_decoder_input_example = latents241 242 return unet_input_example, vae_decoder_input_example243 244 def prepare_for_ipex(self, promt, dtype=torch.float32, height=None, width=None, guidance_scale=7.5):245 self.unet = self.unet.to(memory_format=torch.channels_last)246 self.vae.decoder = self.vae.decoder.to(memory_format=torch.channels_last)247 self.text_encoder = self.text_encoder.to(memory_format=torch.channels_last)248 if self.safety_checker is not None:249 self.safety_checker = self.safety_checker.to(memory_format=torch.channels_last)250 251 unet_input_example, vae_decoder_input_example = self.get_input_example(promt, height, width, guidance_scale)252 253 # optimize with ipex254 if dtype == torch.bfloat16:255 self.unet = ipex.optimize(self.unet.eval(), dtype=torch.bfloat16, inplace=True)256 self.vae.decoder = ipex.optimize(self.vae.decoder.eval(), dtype=torch.bfloat16, inplace=True)257 self.text_encoder = ipex.optimize(self.text_encoder.eval(), dtype=torch.bfloat16, inplace=True)258 if self.safety_checker is not None:259 self.safety_checker = ipex.optimize(self.safety_checker.eval(), dtype=torch.bfloat16, inplace=True)260 elif dtype == torch.float32:261 self.unet = ipex.optimize(262 self.unet.eval(),263 dtype=torch.float32,264 inplace=True,265 weights_prepack=True,266 auto_kernel_selection=False,267 )268 self.vae.decoder = ipex.optimize(269 self.vae.decoder.eval(),270 dtype=torch.float32,271 inplace=True,272 weights_prepack=True,273 auto_kernel_selection=False,274 )275 self.text_encoder = ipex.optimize(276 self.text_encoder.eval(),277 dtype=torch.float32,278 inplace=True,279 weights_prepack=True,280 auto_kernel_selection=False,281 )282 if self.safety_checker is not None:283 self.safety_checker = ipex.optimize(284 self.safety_checker.eval(),285 dtype=torch.float32,286 inplace=True,287 weights_prepack=True,288 auto_kernel_selection=False,289 )290 else:291 raise ValueError(" The value of 'dtype' should be 'torch.bfloat16' or 'torch.float32' !")292 293 # trace unet model to get better performance on IPEX294 with torch.cpu.amp.autocast(enabled=dtype == torch.bfloat16), torch.no_grad():295 unet_trace_model = torch.jit.trace(self.unet, unet_input_example, check_trace=False, strict=False)296 unet_trace_model = torch.jit.freeze(unet_trace_model)297 self.unet.forward = unet_trace_model.forward298 299 # trace vae.decoder model to get better performance on IPEX300 with torch.cpu.amp.autocast(enabled=dtype == torch.bfloat16), torch.no_grad():301 ave_decoder_trace_model = torch.jit.trace(302 self.vae.decoder, vae_decoder_input_example, check_trace=False, strict=False303 )304 ave_decoder_trace_model = torch.jit.freeze(ave_decoder_trace_model)305 self.vae.decoder.forward = ave_decoder_trace_model.forward306 307 def _encode_prompt(308 self,309 prompt,310 device,311 num_images_per_prompt,312 do_classifier_free_guidance,313 negative_prompt=None,314 prompt_embeds: Optional[torch.Tensor] = None,315 negative_prompt_embeds: Optional[torch.Tensor] = None,316 ):317 r"""318 Encodes the prompt into text encoder hidden states.319 320 Args:321 prompt (`str` or `List[str]`, *optional*):322 prompt to be encoded323 device: (`torch.device`):324 torch device325 num_images_per_prompt (`int`):326 number of images that should be generated per prompt327 do_classifier_free_guidance (`bool`):328 whether to use classifier free guidance or not329 negative_prompt (`str` or `List[str]`, *optional*):330 The prompt or prompts not to guide the image generation. If not defined, one has to pass331 `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.332 Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).333 prompt_embeds (`torch.Tensor`, *optional*):334 Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not335 provided, text embeddings will be generated from `prompt` input argument.336 negative_prompt_embeds (`torch.Tensor`, *optional*):337 Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt338 weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input339 argument.340 """341 if prompt is not None and isinstance(prompt, str):342 batch_size = 1343 elif prompt is not None and isinstance(prompt, list):344 batch_size = len(prompt)345 else:346 batch_size = prompt_embeds.shape[0]347 348 if prompt_embeds is None:349 # textual inversion: process multi-vector tokens if necessary350 if isinstance(self, TextualInversionLoaderMixin):351 prompt = self.maybe_convert_prompt(prompt, self.tokenizer)352 353 text_inputs = self.tokenizer(354 prompt,355 padding="max_length",356 max_length=self.tokenizer.model_max_length,357 truncation=True,358 return_tensors="pt",359 )360 text_input_ids = text_inputs.input_ids361 untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids362 363 if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(364 text_input_ids, untruncated_ids365 ):366 removed_text = self.tokenizer.batch_decode(367 untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]368 )369 logger.warning(370 "The following part of your input was truncated because CLIP can only handle sequences up to"371 f" {self.tokenizer.model_max_length} tokens: {removed_text}"372 )373 374 if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:375 attention_mask = text_inputs.attention_mask.to(device)376 else:377 attention_mask = None378 379 prompt_embeds = self.text_encoder(380 text_input_ids.to(device),381 attention_mask=attention_mask,382 )383 prompt_embeds = prompt_embeds[0]384 385 prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)386 387 bs_embed, seq_len, _ = prompt_embeds.shape388 # duplicate text embeddings for each generation per prompt, using mps friendly method389 prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)390 prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)391 392 # get unconditional embeddings for classifier free guidance393 if do_classifier_free_guidance and negative_prompt_embeds is None:394 uncond_tokens: List[str]395 if negative_prompt is None:396 uncond_tokens = [""] * batch_size397 elif type(prompt) is not type(negative_prompt):398 raise TypeError(399 f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="400 f" {type(prompt)}."401 )402 elif isinstance(negative_prompt, str):403 uncond_tokens = [negative_prompt]404 elif batch_size != len(negative_prompt):405 raise ValueError(406 f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"407 f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"408 " the batch size of `prompt`."409 )410 else:411 uncond_tokens = negative_prompt412 413 # textual inversion: process multi-vector tokens if necessary414 if isinstance(self, TextualInversionLoaderMixin):415 uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)416 417 max_length = prompt_embeds.shape[1]418 uncond_input = self.tokenizer(419 uncond_tokens,420 padding="max_length",421 max_length=max_length,422 truncation=True,423 return_tensors="pt",424 )425 426 if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:427 attention_mask = uncond_input.attention_mask.to(device)428 else:429 attention_mask = None430 431 negative_prompt_embeds = self.text_encoder(432 uncond_input.input_ids.to(device),433 attention_mask=attention_mask,434 )435 negative_prompt_embeds = negative_prompt_embeds[0]436 437 if do_classifier_free_guidance:438 # duplicate unconditional embeddings for each generation per prompt, using mps friendly method439 seq_len = negative_prompt_embeds.shape[1]440 441 negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)442 443 negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)444 negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)445 446 # For classifier free guidance, we need to do two forward passes.447 # Here we concatenate the unconditional and text embeddings into a single batch448 # to avoid doing two forward passes449 prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])450 451 return prompt_embeds452 453 def run_safety_checker(self, image, device, dtype):454 if self.safety_checker is not None:455 safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)456 image, has_nsfw_concept = self.safety_checker(457 images=image, clip_input=safety_checker_input.pixel_values.to(dtype)458 )459 else:460 has_nsfw_concept = None461 return image, has_nsfw_concept462 463 def decode_latents(self, latents):464 latents = 1 / self.vae.config.scaling_factor * latents465 image = self.vae.decode(latents).sample466 image = (image / 2 + 0.5).clamp(0, 1)467 # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16468 image = image.cpu().permute(0, 2, 3, 1).float().numpy()469 return image470 471 def prepare_extra_step_kwargs(self, generator, eta):472 # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature473 # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.474 # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502475 # and should be between [0, 1]476 477 accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())478 extra_step_kwargs = {}479 if accepts_eta:480 extra_step_kwargs["eta"] = eta481 482 # check if the scheduler accepts generator483 accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())484 if accepts_generator:485 extra_step_kwargs["generator"] = generator486 return extra_step_kwargs487 488 def check_inputs(489 self,490 prompt,491 height,492 width,493 callback_steps,494 negative_prompt=None,495 prompt_embeds=None,496 negative_prompt_embeds=None,497 ):498 if height % 8 != 0 or width % 8 != 0:499 raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")500 501 if (callback_steps is None) or (502 callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)503 ):504 raise ValueError(505 f"`callback_steps` has to be a positive integer but is {callback_steps} of type"506 f" {type(callback_steps)}."507 )508 509 if prompt is not None and prompt_embeds is not None:510 raise ValueError(511 f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"512 " only forward one of the two."513 )514 elif prompt is None and prompt_embeds is None:515 raise ValueError(516 "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."517 )518 elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):519 raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")520 521 if negative_prompt is not None and negative_prompt_embeds is not None:522 raise ValueError(523 f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"524 f" {negative_prompt_embeds}. Please make sure to only forward one of the two."525 )526 527 if prompt_embeds is not None and negative_prompt_embeds is not None:528 if prompt_embeds.shape != negative_prompt_embeds.shape:529 raise ValueError(530 "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"531 f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"532 f" {negative_prompt_embeds.shape}."533 )534 535 def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):536 shape = (537 batch_size,538 num_channels_latents,539 int(height) // self.vae_scale_factor,540 int(width) // self.vae_scale_factor,541 )542 if isinstance(generator, list) and len(generator) != batch_size:543 raise ValueError(544 f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"545 f" size of {batch_size}. Make sure the batch size matches the length of the generators."546 )547 548 if latents is None:549 latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)550 else:551 latents = latents.to(device)552 553 # scale the initial noise by the standard deviation required by the scheduler554 latents = latents * self.scheduler.init_noise_sigma555 return latents556 557 @torch.no_grad()558 @replace_example_docstring(EXAMPLE_DOC_STRING)559 def __call__(560 self,561 prompt: Union[str, List[str]] = None,562 height: Optional[int] = None,563 width: Optional[int] = None,564 num_inference_steps: int = 50,565 guidance_scale: float = 7.5,566 negative_prompt: Optional[Union[str, List[str]]] = None,567 num_images_per_prompt: Optional[int] = 1,568 eta: float = 0.0,569 generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,570 latents: Optional[torch.Tensor] = None,571 prompt_embeds: Optional[torch.Tensor] = None,572 negative_prompt_embeds: Optional[torch.Tensor] = None,573 output_type: Optional[str] = "pil",574 return_dict: bool = True,575 callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,576 callback_steps: int = 1,577 cross_attention_kwargs: Optional[Dict[str, Any]] = None,578 ):579 r"""580 Function invoked when calling the pipeline for generation.581 582 Args:583 prompt (`str` or `List[str]`, *optional*):584 The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.585 instead.586 height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):587 The height in pixels of the generated image.588 width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):589 The width in pixels of the generated image.590 num_inference_steps (`int`, *optional*, defaults to 50):591 The number of denoising steps. More denoising steps usually lead to a higher quality image at the592 expense of slower inference.593 guidance_scale (`float`, *optional*, defaults to 7.5):594 Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).595 `guidance_scale` is defined as `w` of equation 2. of [Imagen596 Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >597 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,598 usually at the expense of lower image quality.599 negative_prompt (`str` or `List[str]`, *optional*):600 The prompt or prompts not to guide the image generation. If not defined, one has to pass601 `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.602 Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).603 num_images_per_prompt (`int`, *optional*, defaults to 1):604 The number of images to generate per prompt.605 eta (`float`, *optional*, defaults to 0.0):606 Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to607 [`schedulers.DDIMScheduler`], will be ignored for others.608 generator (`torch.Generator` or `List[torch.Generator]`, *optional*):609 One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)610 to make generation deterministic.611 latents (`torch.Tensor`, *optional*):612 Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image613 generation. Can be used to tweak the same generation with different prompts. If not provided, a latents614 tensor will ge generated by sampling using the supplied random `generator`.615 prompt_embeds (`torch.Tensor`, *optional*):616 Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not617 provided, text embeddings will be generated from `prompt` input argument.618 negative_prompt_embeds (`torch.Tensor`, *optional*):619 Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt620 weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input621 argument.622 output_type (`str`, *optional*, defaults to `"pil"`):623 The output format of the generate image. Choose between624 [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.625 return_dict (`bool`, *optional*, defaults to `True`):626 Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a627 plain tuple.628 callback (`Callable`, *optional*):629 A function that will be called every `callback_steps` steps during inference. The function will be630 called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.631 callback_steps (`int`, *optional*, defaults to 1):632 The frequency at which the `callback` function will be called. If not specified, the callback will be633 called at every step.634 cross_attention_kwargs (`dict`, *optional*):635 A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under636 `self.processor` in637 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).638 639 Examples:640 641 Returns:642 [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:643 [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.644 When returning a tuple, the first element is a list with the generated images, and the second element is a645 list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"646 (nsfw) content, according to the `safety_checker`.647 """648 # 0. Default height and width to unet649 height = height or self.unet.config.sample_size * self.vae_scale_factor650 width = width or self.unet.config.sample_size * self.vae_scale_factor651 652 # 1. Check inputs. Raise error if not correct653 self.check_inputs(654 prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds655 )656 657 # 2. Define call parameters658 if prompt is not None and isinstance(prompt, str):659 batch_size = 1660 elif prompt is not None and isinstance(prompt, list):661 batch_size = len(prompt)662 else:663 batch_size = prompt_embeds.shape[0]664 665 device = self._execution_device666 # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)667 # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`668 # corresponds to doing no classifier free guidance.669 do_classifier_free_guidance = guidance_scale > 1.0670 671 # 3. Encode input prompt672 prompt_embeds = self._encode_prompt(673 prompt,674 device,675 num_images_per_prompt,676 do_classifier_free_guidance,677 negative_prompt,678 prompt_embeds=prompt_embeds,679 negative_prompt_embeds=negative_prompt_embeds,680 )681 682 # 4. Prepare timesteps683 self.scheduler.set_timesteps(num_inference_steps, device=device)684 timesteps = self.scheduler.timesteps685 686 # 5. Prepare latent variables687 num_channels_latents = self.unet.config.in_channels688 latents = self.prepare_latents(689 batch_size * num_images_per_prompt,690 num_channels_latents,691 height,692 width,693 prompt_embeds.dtype,694 device,695 generator,696 latents,697 )698 699 # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline700 extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)701 702 # 7. Denoising loop703 num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order704 with self.progress_bar(total=num_inference_steps) as progress_bar:705 for i, t in enumerate(timesteps):706 # expand the latents if we are doing classifier free guidance707 latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents708 latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)709 710 # predict the noise residual711 noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=prompt_embeds)["sample"]712 713 # perform guidance714 if do_classifier_free_guidance:715 noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)716 noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)717 718 # compute the previous noisy sample x_t -> x_t-1719 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample720 721 # call the callback, if provided722 if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):723 progress_bar.update()724 if callback is not None and i % callback_steps == 0:725 step_idx = i // getattr(self.scheduler, "order", 1)726 callback(step_idx, t, latents)727 728 if output_type == "latent":729 image = latents730 has_nsfw_concept = None731 elif output_type == "pil":732 # 8. Post-processing733 image = self.decode_latents(latents)734 735 # 9. Run safety checker736 image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)737 738 # 10. Convert to PIL739 image = self.numpy_to_pil(image)740 else:741 # 8. Post-processing742 image = self.decode_latents(latents)743 744 # 9. Run safety checker745 image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)746 747 # Offload last model to CPU748 if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:749 self.final_offload_hook.offload()750 751 if not return_dict:752 return (image, has_nsfw_concept)753 754 return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)755 