Path: blob/main/examples/community/wildcard_stable_diffusion.py
1448 views
import inspect1import os2import random3import re4from dataclasses import dataclass5from typing import Callable, Dict, List, Optional, Union67import torch8from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer910from diffusers import DiffusionPipeline11from diffusers.configuration_utils import FrozenDict12from diffusers.models import AutoencoderKL, UNet2DConditionModel13from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput14from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker15from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler16from diffusers.utils import deprecate, logging171819logger = logging.get_logger(__name__) # pylint: disable=invalid-name2021global_re_wildcard = re.compile(r"__([^_]*)__")222324def get_filename(path: str):25# this doesn't work on Windows26return os.path.basename(path).split(".txt")[0]272829def read_wildcard_values(path: str):30with open(path, encoding="utf8") as f:31return f.read().splitlines()323334def grab_wildcard_values(wildcard_option_dict: Dict[str, List[str]] = {}, wildcard_files: List[str] = []):35for wildcard_file in wildcard_files:36filename = get_filename(wildcard_file)37read_values = read_wildcard_values(wildcard_file)38if filename not in wildcard_option_dict:39wildcard_option_dict[filename] = []40wildcard_option_dict[filename].extend(read_values)41return wildcard_option_dict424344def replace_prompt_with_wildcards(45prompt: str, wildcard_option_dict: Dict[str, List[str]] = {}, wildcard_files: List[str] = []46):47new_prompt = prompt4849# get wildcard options50wildcard_option_dict = grab_wildcard_values(wildcard_option_dict, wildcard_files)5152for m in global_re_wildcard.finditer(new_prompt):53wildcard_value = m.group()54replace_value = random.choice(wildcard_option_dict[wildcard_value.strip("__")])55new_prompt = new_prompt.replace(wildcard_value, replace_value, 1)5657return new_prompt585960@dataclass61class WildcardStableDiffusionOutput(StableDiffusionPipelineOutput):62prompts: List[str]636465class WildcardStableDiffusionPipeline(DiffusionPipeline):66r"""67Example Usage:68pipe = WildcardStableDiffusionPipeline.from_pretrained(69"CompVis/stable-diffusion-v1-4",7071torch_dtype=torch.float16,72)73prompt = "__animal__ sitting on a __object__ wearing a __clothing__"74out = pipe(75prompt,76wildcard_option_dict={77"clothing":["hat", "shirt", "scarf", "beret"]78},79wildcard_files=["object.txt", "animal.txt"],80num_prompt_samples=181)828384Pipeline for text-to-image generation with wild cards using Stable Diffusion.8586This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the87library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)8889Args:90vae ([`AutoencoderKL`]):91Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.92text_encoder ([`CLIPTextModel`]):93Frozen text-encoder. Stable Diffusion uses the text portion of94[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically95the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.96tokenizer (`CLIPTokenizer`):97Tokenizer of class98[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).99unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.100scheduler ([`SchedulerMixin`]):101A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of102[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].103safety_checker ([`StableDiffusionSafetyChecker`]):104Classification module that estimates whether generated images could be considered offensive or harmful.105Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.106feature_extractor ([`CLIPImageProcessor`]):107Model that extracts features from generated images to be used as inputs for the `safety_checker`.108"""109110def __init__(111self,112vae: AutoencoderKL,113text_encoder: CLIPTextModel,114tokenizer: CLIPTokenizer,115unet: UNet2DConditionModel,116scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],117safety_checker: StableDiffusionSafetyChecker,118feature_extractor: CLIPImageProcessor,119):120super().__init__()121122if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:123deprecation_message = (124f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"125f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "126"to update the config accordingly as leaving `steps_offset` might led to incorrect results"127" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"128" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"129" file"130)131deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)132new_config = dict(scheduler.config)133new_config["steps_offset"] = 1134scheduler._internal_dict = FrozenDict(new_config)135136if safety_checker is None:137logger.warning(138f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"139" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"140" results in services or applications open to the public. Both the diffusers team and Hugging Face"141" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"142" it only for use-cases that involve analyzing network behavior or auditing its results. For more"143" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."144)145146self.register_modules(147vae=vae,148text_encoder=text_encoder,149tokenizer=tokenizer,150unet=unet,151scheduler=scheduler,152safety_checker=safety_checker,153feature_extractor=feature_extractor,154)155156@torch.no_grad()157def __call__(158self,159prompt: Union[str, List[str]],160height: int = 512,161width: int = 512,162num_inference_steps: int = 50,163guidance_scale: float = 7.5,164negative_prompt: Optional[Union[str, List[str]]] = None,165num_images_per_prompt: Optional[int] = 1,166eta: float = 0.0,167generator: Optional[torch.Generator] = None,168latents: Optional[torch.FloatTensor] = None,169output_type: Optional[str] = "pil",170return_dict: bool = True,171callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,172callback_steps: int = 1,173wildcard_option_dict: Dict[str, List[str]] = {},174wildcard_files: List[str] = [],175num_prompt_samples: Optional[int] = 1,176**kwargs,177):178r"""179Function invoked when calling the pipeline for generation.180181Args:182prompt (`str` or `List[str]`):183The prompt or prompts to guide the image generation.184height (`int`, *optional*, defaults to 512):185The height in pixels of the generated image.186width (`int`, *optional*, defaults to 512):187The width in pixels of the generated image.188num_inference_steps (`int`, *optional*, defaults to 50):189The number of denoising steps. More denoising steps usually lead to a higher quality image at the190expense of slower inference.191guidance_scale (`float`, *optional*, defaults to 7.5):192Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).193`guidance_scale` is defined as `w` of equation 2. of [Imagen194Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >1951`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,196usually at the expense of lower image quality.197negative_prompt (`str` or `List[str]`, *optional*):198The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored199if `guidance_scale` is less than `1`).200num_images_per_prompt (`int`, *optional*, defaults to 1):201The number of images to generate per prompt.202eta (`float`, *optional*, defaults to 0.0):203Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to204[`schedulers.DDIMScheduler`], will be ignored for others.205generator (`torch.Generator`, *optional*):206A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation207deterministic.208latents (`torch.FloatTensor`, *optional*):209Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image210generation. Can be used to tweak the same generation with different prompts. If not provided, a latents211tensor will ge generated by sampling using the supplied random `generator`.212output_type (`str`, *optional*, defaults to `"pil"`):213The output format of the generate image. Choose between214[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.215return_dict (`bool`, *optional*, defaults to `True`):216Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a217plain tuple.218callback (`Callable`, *optional*):219A function that will be called every `callback_steps` steps during inference. The function will be220called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.221callback_steps (`int`, *optional*, defaults to 1):222The frequency at which the `callback` function will be called. If not specified, the callback will be223called at every step.224wildcard_option_dict (Dict[str, List[str]]):225dict with key as `wildcard` and values as a list of possible replacements. For example if a prompt, "A __animal__ sitting on a chair". A wildcard_option_dict can provide possible values for "animal" like this: {"animal":["dog", "cat", "fox"]}226wildcard_files: (List[str])227List of filenames of txt files for wildcard replacements. For example if a prompt, "A __animal__ sitting on a chair". A file can be provided ["animal.txt"]228num_prompt_samples: int229Number of times to sample wildcards for each prompt provided230231Returns:232[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:233[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.234When returning a tuple, the first element is a list with the generated images, and the second element is a235list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"236(nsfw) content, according to the `safety_checker`.237"""238239if isinstance(prompt, str):240prompt = [241replace_prompt_with_wildcards(prompt, wildcard_option_dict, wildcard_files)242for i in range(num_prompt_samples)243]244batch_size = len(prompt)245elif isinstance(prompt, list):246prompt_list = []247for p in prompt:248for i in range(num_prompt_samples):249prompt_list.append(replace_prompt_with_wildcards(p, wildcard_option_dict, wildcard_files))250prompt = prompt_list251batch_size = len(prompt)252else:253raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")254255if height % 8 != 0 or width % 8 != 0:256raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")257258if (callback_steps is None) or (259callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)260):261raise ValueError(262f"`callback_steps` has to be a positive integer but is {callback_steps} of type"263f" {type(callback_steps)}."264)265266# get prompt text embeddings267text_inputs = self.tokenizer(268prompt,269padding="max_length",270max_length=self.tokenizer.model_max_length,271return_tensors="pt",272)273text_input_ids = text_inputs.input_ids274275if text_input_ids.shape[-1] > self.tokenizer.model_max_length:276removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])277logger.warning(278"The following part of your input was truncated because CLIP can only handle sequences up to"279f" {self.tokenizer.model_max_length} tokens: {removed_text}"280)281text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]282text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]283284# duplicate text embeddings for each generation per prompt, using mps friendly method285bs_embed, seq_len, _ = text_embeddings.shape286text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)287text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)288289# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)290# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`291# corresponds to doing no classifier free guidance.292do_classifier_free_guidance = guidance_scale > 1.0293# get unconditional embeddings for classifier free guidance294if do_classifier_free_guidance:295uncond_tokens: List[str]296if negative_prompt is None:297uncond_tokens = [""] * batch_size298elif type(prompt) is not type(negative_prompt):299raise TypeError(300f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="301f" {type(prompt)}."302)303elif isinstance(negative_prompt, str):304uncond_tokens = [negative_prompt]305elif batch_size != len(negative_prompt):306raise ValueError(307f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"308f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"309" the batch size of `prompt`."310)311else:312uncond_tokens = negative_prompt313314max_length = text_input_ids.shape[-1]315uncond_input = self.tokenizer(316uncond_tokens,317padding="max_length",318max_length=max_length,319truncation=True,320return_tensors="pt",321)322uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]323324# duplicate unconditional embeddings for each generation per prompt, using mps friendly method325seq_len = uncond_embeddings.shape[1]326uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)327uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)328329# For classifier free guidance, we need to do two forward passes.330# Here we concatenate the unconditional and text embeddings into a single batch331# to avoid doing two forward passes332text_embeddings = torch.cat([uncond_embeddings, text_embeddings])333334# get the initial random noise unless the user supplied it335336# Unlike in other pipelines, latents need to be generated in the target device337# for 1-to-1 results reproducibility with the CompVis implementation.338# However this currently doesn't work in `mps`.339latents_shape = (batch_size * num_images_per_prompt, self.unet.in_channels, height // 8, width // 8)340latents_dtype = text_embeddings.dtype341if latents is None:342if self.device.type == "mps":343# randn does not exist on mps344latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(345self.device346)347else:348latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)349else:350if latents.shape != latents_shape:351raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")352latents = latents.to(self.device)353354# set timesteps355self.scheduler.set_timesteps(num_inference_steps)356357# Some schedulers like PNDM have timesteps as arrays358# It's more optimized to move all timesteps to correct device beforehand359timesteps_tensor = self.scheduler.timesteps.to(self.device)360361# scale the initial noise by the standard deviation required by the scheduler362latents = latents * self.scheduler.init_noise_sigma363364# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature365# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.366# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502367# and should be between [0, 1]368accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())369extra_step_kwargs = {}370if accepts_eta:371extra_step_kwargs["eta"] = eta372373for i, t in enumerate(self.progress_bar(timesteps_tensor)):374# expand the latents if we are doing classifier free guidance375latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents376latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)377378# predict the noise residual379noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample380381# perform guidance382if do_classifier_free_guidance:383noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)384noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)385386# compute the previous noisy sample x_t -> x_t-1387latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample388389# call the callback, if provided390if callback is not None and i % callback_steps == 0:391callback(i, t, latents)392393latents = 1 / 0.18215 * latents394image = self.vae.decode(latents).sample395396image = (image / 2 + 0.5).clamp(0, 1)397398# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16399image = image.cpu().permute(0, 2, 3, 1).float().numpy()400401if self.safety_checker is not None:402safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(403self.device404)405image, has_nsfw_concept = self.safety_checker(406images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)407)408else:409has_nsfw_concept = None410411if output_type == "pil":412image = self.numpy_to_pil(image)413414if not return_dict:415return (image, has_nsfw_concept)416417return WildcardStableDiffusionOutput(images=image, nsfw_content_detected=has_nsfw_concept, prompts=prompt)418419420