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 2025 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 Callable, List, Optional, Union17 18import torch19from packaging import version20from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer21 22from diffusers import DiffusionPipeline23from diffusers.configuration_utils import FrozenDict24from diffusers.models import AutoencoderKL, UNet2DConditionModel25from diffusers.pipelines.pipeline_utils import StableDiffusionMixin26from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput27from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker28from diffusers.schedulers import (29 DDIMScheduler,30 DPMSolverMultistepScheduler,31 EulerAncestralDiscreteScheduler,32 EulerDiscreteScheduler,33 LMSDiscreteScheduler,34 PNDMScheduler,35)36from diffusers.utils import deprecate, logging37 38 39logger = logging.get_logger(__name__) # pylint: disable=invalid-name40 41 42class ComposableStableDiffusionPipeline(DiffusionPipeline, StableDiffusionMixin):43 r"""44 Pipeline for text-to-image generation using Stable Diffusion.45 46 This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the47 library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)48 49 Args:50 vae ([`AutoencoderKL`]):51 Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.52 text_encoder ([`CLIPTextModel`]):53 Frozen text-encoder. Stable Diffusion uses the text portion of54 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically55 the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.56 tokenizer (`CLIPTokenizer`):57 Tokenizer of class58 [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).59 unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.60 scheduler ([`SchedulerMixin`]):61 A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of62 [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].63 safety_checker ([`StableDiffusionSafetyChecker`]):64 Classification module that estimates whether generated images could be considered offensive or harmful.65 Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.66 feature_extractor ([`CLIPImageProcessor`]):67 Model that extracts features from generated images to be used as inputs for the `safety_checker`.68 """69 70 _optional_components = ["safety_checker", "feature_extractor"]71 72 def __init__(73 self,74 vae: AutoencoderKL,75 text_encoder: CLIPTextModel,76 tokenizer: CLIPTokenizer,77 unet: UNet2DConditionModel,78 scheduler: Union[79 DDIMScheduler,80 PNDMScheduler,81 LMSDiscreteScheduler,82 EulerDiscreteScheduler,83 EulerAncestralDiscreteScheduler,84 DPMSolverMultistepScheduler,85 ],86 safety_checker: StableDiffusionSafetyChecker,87 feature_extractor: CLIPImageProcessor,88 requires_safety_checker: bool = True,89 ):90 super().__init__()91 92 if scheduler is not None and getattr(scheduler.config, "steps_offset", 1) != 1:93 deprecation_message = (94 f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"95 f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "96 "to update the config accordingly as leaving `steps_offset` might led to incorrect results"97 " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"98 " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"99 " file"100 )101 deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)102 new_config = dict(scheduler.config)103 new_config["steps_offset"] = 1104 scheduler._internal_dict = FrozenDict(new_config)105 106 if scheduler is not None and getattr(scheduler.config, "clip_sample", False) is True:107 deprecation_message = (108 f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."109 " `clip_sample` should be set to False in the configuration file. Please make sure to update the"110 " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"111 " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"112 " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"113 )114 deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)115 new_config = dict(scheduler.config)116 new_config["clip_sample"] = False117 scheduler._internal_dict = FrozenDict(new_config)118 119 if safety_checker is None and requires_safety_checker:120 logger.warning(121 f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"122 " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"123 " results in services or applications open to the public. Both the diffusers team and Hugging Face"124 " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"125 " it only for use-cases that involve analyzing network behavior or auditing its results. For more"126 " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."127 )128 129 if safety_checker is not None and feature_extractor is None:130 raise ValueError(131 "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"132 " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."133 )134 135 is_unet_version_less_0_9_0 = (136 unet is not None137 and hasattr(unet.config, "_diffusers_version")138 and version.parse(version.parse(unet.config._diffusers_version).base_version) < version.parse("0.9.0.dev0")139 )140 is_unet_sample_size_less_64 = (141 unet is not None and hasattr(unet.config, "sample_size") and unet.config.sample_size < 64142 )143 if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:144 deprecation_message = (145 "The configuration file of the unet has set the default `sample_size` to smaller than"146 " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"147 " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"148 " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"149 " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"150 " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"151 " in the config might lead to incorrect results in future versions. If you have downloaded this"152 " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"153 " the `unet/config.json` file"154 )155 deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)156 new_config = dict(unet.config)157 new_config["sample_size"] = 64158 unet._internal_dict = FrozenDict(new_config)159 160 self.register_modules(161 vae=vae,162 text_encoder=text_encoder,163 tokenizer=tokenizer,164 unet=unet,165 scheduler=scheduler,166 safety_checker=safety_checker,167 feature_extractor=feature_extractor,168 )169 self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8170 self.register_to_config(requires_safety_checker=requires_safety_checker)171 172 def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):173 r"""174 Encodes the prompt into text encoder hidden states.175 176 Args:177 prompt (`str` or `list(int)`):178 prompt to be encoded179 device: (`torch.device`):180 torch device181 num_images_per_prompt (`int`):182 number of images that should be generated per prompt183 do_classifier_free_guidance (`bool`):184 whether to use classifier free guidance or not185 negative_prompt (`str` or `List[str]`):186 The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored187 if `guidance_scale` is less than `1`).188 """189 batch_size = len(prompt) if isinstance(prompt, list) else 1190 191 text_inputs = self.tokenizer(192 prompt,193 padding="max_length",194 max_length=self.tokenizer.model_max_length,195 truncation=True,196 return_tensors="pt",197 )198 text_input_ids = text_inputs.input_ids199 untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids200 201 if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):202 removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])203 logger.warning(204 "The following part of your input was truncated because CLIP can only handle sequences up to"205 f" {self.tokenizer.model_max_length} tokens: {removed_text}"206 )207 208 if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:209 attention_mask = text_inputs.attention_mask.to(device)210 else:211 attention_mask = None212 213 text_embeddings = self.text_encoder(214 text_input_ids.to(device),215 attention_mask=attention_mask,216 )217 text_embeddings = text_embeddings[0]218 219 # duplicate text embeddings for each generation per prompt, using mps friendly method220 bs_embed, seq_len, _ = text_embeddings.shape221 text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)222 text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)223 224 # get unconditional embeddings for classifier free guidance225 if do_classifier_free_guidance:226 uncond_tokens: List[str]227 if negative_prompt is None:228 uncond_tokens = [""] * batch_size229 elif type(prompt) is not type(negative_prompt):230 raise TypeError(231 f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="232 f" {type(prompt)}."233 )234 elif isinstance(negative_prompt, str):235 uncond_tokens = [negative_prompt]236 elif batch_size != len(negative_prompt):237 raise ValueError(238 f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"239 f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"240 " the batch size of `prompt`."241 )242 else:243 uncond_tokens = negative_prompt244 245 max_length = text_input_ids.shape[-1]246 uncond_input = self.tokenizer(247 uncond_tokens,248 padding="max_length",249 max_length=max_length,250 truncation=True,251 return_tensors="pt",252 )253 254 if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:255 attention_mask = uncond_input.attention_mask.to(device)256 else:257 attention_mask = None258 259 uncond_embeddings = self.text_encoder(260 uncond_input.input_ids.to(device),261 attention_mask=attention_mask,262 )263 uncond_embeddings = uncond_embeddings[0]264 265 # duplicate unconditional embeddings for each generation per prompt, using mps friendly method266 seq_len = uncond_embeddings.shape[1]267 uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)268 uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)269 270 # For classifier free guidance, we need to do two forward passes.271 # Here we concatenate the unconditional and text embeddings into a single batch272 # to avoid doing two forward passes273 text_embeddings = torch.cat([uncond_embeddings, text_embeddings])274 275 return text_embeddings276 277 def run_safety_checker(self, image, device, dtype):278 if self.safety_checker is not None:279 safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)280 image, has_nsfw_concept = self.safety_checker(281 images=image, clip_input=safety_checker_input.pixel_values.to(dtype)282 )283 else:284 has_nsfw_concept = None285 return image, has_nsfw_concept286 287 def decode_latents(self, latents):288 latents = 1 / 0.18215 * latents289 image = self.vae.decode(latents).sample290 image = (image / 2 + 0.5).clamp(0, 1)291 # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16292 image = image.cpu().permute(0, 2, 3, 1).float().numpy()293 return image294 295 def prepare_extra_step_kwargs(self, generator, eta):296 # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature297 # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.298 # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502299 # and should be between [0, 1]300 301 accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())302 extra_step_kwargs = {}303 if accepts_eta:304 extra_step_kwargs["eta"] = eta305 306 # check if the scheduler accepts generator307 accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())308 if accepts_generator:309 extra_step_kwargs["generator"] = generator310 return extra_step_kwargs311 312 def check_inputs(self, prompt, height, width, callback_steps):313 if not isinstance(prompt, str) and not isinstance(prompt, list):314 raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")315 316 if height % 8 != 0 or width % 8 != 0:317 raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")318 319 if (callback_steps is None) or (320 callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)321 ):322 raise ValueError(323 f"`callback_steps` has to be a positive integer but is {callback_steps} of type"324 f" {type(callback_steps)}."325 )326 327 def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):328 shape = (329 batch_size,330 num_channels_latents,331 int(height) // self.vae_scale_factor,332 int(width) // self.vae_scale_factor,333 )334 if latents is None:335 if device.type == "mps":336 # randn does not work reproducibly on mps337 latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)338 else:339 latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)340 else:341 if latents.shape != shape:342 raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")343 latents = latents.to(device)344 345 # scale the initial noise by the standard deviation required by the scheduler346 latents = latents * self.scheduler.init_noise_sigma347 return latents348 349 @torch.no_grad()350 def __call__(351 self,352 prompt: Union[str, List[str]],353 height: Optional[int] = None,354 width: Optional[int] = None,355 num_inference_steps: int = 50,356 guidance_scale: float = 7.5,357 negative_prompt: Optional[Union[str, List[str]]] = None,358 num_images_per_prompt: Optional[int] = 1,359 eta: float = 0.0,360 generator: Optional[torch.Generator] = None,361 latents: Optional[torch.Tensor] = None,362 output_type: Optional[str] = "pil",363 return_dict: bool = True,364 callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,365 callback_steps: int = 1,366 weights: Optional[str] = "",367 ):368 r"""369 Function invoked when calling the pipeline for generation.370 371 Args:372 prompt (`str` or `List[str]`):373 The prompt or prompts to guide the image generation.374 height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):375 The height in pixels of the generated image.376 width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):377 The width in pixels of the generated image.378 num_inference_steps (`int`, *optional*, defaults to 50):379 The number of denoising steps. More denoising steps usually lead to a higher quality image at the380 expense of slower inference.381 guidance_scale (`float`, *optional*, defaults to 5.0):382 Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598).383 `guidance_scale` is defined as `w` of equation 2. of [Imagen384 Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting `guidance_scale >385 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,386 usually at the expense of lower image quality.387 negative_prompt (`str` or `List[str]`, *optional*):388 The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored389 if `guidance_scale` is less than `1`).390 num_images_per_prompt (`int`, *optional*, defaults to 1):391 The number of images to generate per prompt.392 eta (`float`, *optional*, defaults to 0.0):393 Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only applies to394 [`schedulers.DDIMScheduler`], will be ignored for others.395 generator (`torch.Generator`, *optional*):396 A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation397 deterministic.398 latents (`torch.Tensor`, *optional*):399 Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image400 generation. Can be used to tweak the same generation with different prompts. If not provided, a latents401 tensor will ge generated by sampling using the supplied random `generator`.402 output_type (`str`, *optional*, defaults to `"pil"`):403 The output format of the generate image. Choose between404 [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.405 return_dict (`bool`, *optional*, defaults to `True`):406 Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a407 plain tuple.408 callback (`Callable`, *optional*):409 A function that will be called every `callback_steps` steps during inference. The function will be410 called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.411 callback_steps (`int`, *optional*, defaults to 1):412 The frequency at which the `callback` function will be called. If not specified, the callback will be413 called at every step.414 415 Returns:416 [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:417 [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.418 When returning a tuple, the first element is a list with the generated images, and the second element is a419 list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"420 (nsfw) content, according to the `safety_checker`.421 """422 # 0. Default height and width to unet423 height = height or self.unet.config.sample_size * self.vae_scale_factor424 width = width or self.unet.config.sample_size * self.vae_scale_factor425 426 # 1. Check inputs. Raise error if not correct427 self.check_inputs(prompt, height, width, callback_steps)428 429 # 2. Define call parameters430 batch_size = 1 if isinstance(prompt, str) else len(prompt)431 device = self._execution_device432 # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)433 # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`434 # corresponds to doing no classifier free guidance.435 do_classifier_free_guidance = guidance_scale > 1.0436 437 if "|" in prompt:438 prompt = [x.strip() for x in prompt.split("|")]439 print(f"composing {prompt}...")440 441 if not weights:442 # specify weights for prompts (excluding the unconditional score)443 print("using equal positive weights (conjunction) for all prompts...")444 weights = torch.tensor([guidance_scale] * len(prompt), device=self.device).reshape(-1, 1, 1, 1)445 else:446 # set prompt weight for each447 num_prompts = len(prompt) if isinstance(prompt, list) else 1448 weights = [float(w.strip()) for w in weights.split("|")]449 # guidance scale as the default450 if len(weights) < num_prompts:451 weights.append(guidance_scale)452 else:453 weights = weights[:num_prompts]454 assert len(weights) == len(prompt), "weights specified are not equal to the number of prompts"455 weights = torch.tensor(weights, device=self.device).reshape(-1, 1, 1, 1)456 else:457 weights = guidance_scale458 459 # 3. Encode input prompt460 text_embeddings = self._encode_prompt(461 prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt462 )463 464 # 4. Prepare timesteps465 self.scheduler.set_timesteps(num_inference_steps, device=device)466 timesteps = self.scheduler.timesteps467 468 # 5. Prepare latent variables469 num_channels_latents = self.unet.config.in_channels470 latents = self.prepare_latents(471 batch_size * num_images_per_prompt,472 num_channels_latents,473 height,474 width,475 text_embeddings.dtype,476 device,477 generator,478 latents,479 )480 481 # composable diffusion482 if isinstance(prompt, list) and batch_size == 1:483 # remove extra unconditional embedding484 # N = one unconditional embed + conditional embeds485 text_embeddings = text_embeddings[len(prompt) - 1 :]486 487 # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline488 extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)489 490 # 7. Denoising loop491 num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order492 with self.progress_bar(total=num_inference_steps) as progress_bar:493 for i, t in enumerate(timesteps):494 # expand the latents if we are doing classifier free guidance495 latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents496 latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)497 498 # predict the noise residual499 noise_pred = []500 for j in range(text_embeddings.shape[0]):501 noise_pred.append(502 self.unet(latent_model_input[:1], t, encoder_hidden_states=text_embeddings[j : j + 1]).sample503 )504 noise_pred = torch.cat(noise_pred, dim=0)505 506 # perform guidance507 if do_classifier_free_guidance:508 noise_pred_uncond, noise_pred_text = noise_pred[:1], noise_pred[1:]509 noise_pred = noise_pred_uncond + (weights * (noise_pred_text - noise_pred_uncond)).sum(510 dim=0, keepdims=True511 )512 513 # compute the previous noisy sample x_t -> x_t-1514 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample515 516 # call the callback, if provided517 if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):518 progress_bar.update()519 if callback is not None and i % callback_steps == 0:520 step_idx = i // getattr(self.scheduler, "order", 1)521 callback(step_idx, t, latents)522 523 # 8. Post-processing524 image = self.decode_latents(latents)525 526 # 9. Run safety checker527 image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)528 529 # 10. Convert to PIL530 if output_type == "pil":531 image = self.numpy_to_pil(image)532 533 if not return_dict:534 return (image, has_nsfw_concept)535 536 return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)537 