Path: blob/main/examples/community/imagic_stable_diffusion.py
1448 views
"""1modeled after the textual_inversion.py / train_dreambooth.py and the work2of justinpinkney here: https://github.com/justinpinkney/stable-diffusion/blob/main/notebooks/imagic.ipynb3"""4import inspect5import warnings6from typing import List, Optional, Union78import numpy as np9import PIL10import torch11import torch.nn.functional as F12from accelerate import Accelerator1314# TODO: remove and import from diffusers.utils when the new version of diffusers is released15from packaging import version16from tqdm.auto import tqdm17from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer1819from diffusers import DiffusionPipeline20from diffusers.models import AutoencoderKL, UNet2DConditionModel21from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput22from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker23from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler24from diffusers.utils import logging252627if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):28PIL_INTERPOLATION = {29"linear": PIL.Image.Resampling.BILINEAR,30"bilinear": PIL.Image.Resampling.BILINEAR,31"bicubic": PIL.Image.Resampling.BICUBIC,32"lanczos": PIL.Image.Resampling.LANCZOS,33"nearest": PIL.Image.Resampling.NEAREST,34}35else:36PIL_INTERPOLATION = {37"linear": PIL.Image.LINEAR,38"bilinear": PIL.Image.BILINEAR,39"bicubic": PIL.Image.BICUBIC,40"lanczos": PIL.Image.LANCZOS,41"nearest": PIL.Image.NEAREST,42}43# ------------------------------------------------------------------------------4445logger = logging.get_logger(__name__) # pylint: disable=invalid-name464748def preprocess(image):49w, h = image.size50w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 3251image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])52image = np.array(image).astype(np.float32) / 255.053image = image[None].transpose(0, 3, 1, 2)54image = torch.from_numpy(image)55return 2.0 * image - 1.0565758class ImagicStableDiffusionPipeline(DiffusionPipeline):59r"""60Pipeline for imagic image editing.61See paper here: https://arxiv.org/pdf/2210.09276.pdf6263This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the64library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)65Args:66vae ([`AutoencoderKL`]):67Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.68text_encoder ([`CLIPTextModel`]):69Frozen text-encoder. Stable Diffusion uses the text portion of70[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically71the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.72tokenizer (`CLIPTokenizer`):73Tokenizer of class74[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).75unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.76scheduler ([`SchedulerMixin`]):77A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of78[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].79safety_checker ([`StableDiffusionSafetyChecker`]):80Classification module that estimates whether generated images could be considered offsensive or harmful.81Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.82feature_extractor ([`CLIPImageProcessor`]):83Model that extracts features from generated images to be used as inputs for the `safety_checker`.84"""8586def __init__(87self,88vae: AutoencoderKL,89text_encoder: CLIPTextModel,90tokenizer: CLIPTokenizer,91unet: UNet2DConditionModel,92scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],93safety_checker: StableDiffusionSafetyChecker,94feature_extractor: CLIPImageProcessor,95):96super().__init__()97self.register_modules(98vae=vae,99text_encoder=text_encoder,100tokenizer=tokenizer,101unet=unet,102scheduler=scheduler,103safety_checker=safety_checker,104feature_extractor=feature_extractor,105)106107def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):108r"""109Enable sliced attention computation.110When this option is enabled, the attention module will split the input tensor in slices, to compute attention111in several steps. This is useful to save some memory in exchange for a small speed decrease.112Args:113slice_size (`str` or `int`, *optional*, defaults to `"auto"`):114When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If115a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,116`attention_head_dim` must be a multiple of `slice_size`.117"""118if slice_size == "auto":119# half the attention head size is usually a good trade-off between120# speed and memory121slice_size = self.unet.config.attention_head_dim // 2122self.unet.set_attention_slice(slice_size)123124def disable_attention_slicing(self):125r"""126Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go127back to computing attention in one step.128"""129# set slice_size = `None` to disable `attention slicing`130self.enable_attention_slicing(None)131132def train(133self,134prompt: Union[str, List[str]],135image: Union[torch.FloatTensor, PIL.Image.Image],136height: Optional[int] = 512,137width: Optional[int] = 512,138generator: Optional[torch.Generator] = None,139embedding_learning_rate: float = 0.001,140diffusion_model_learning_rate: float = 2e-6,141text_embedding_optimization_steps: int = 500,142model_fine_tuning_optimization_steps: int = 1000,143**kwargs,144):145r"""146Function invoked when calling the pipeline for generation.147Args:148prompt (`str` or `List[str]`):149The prompt or prompts to guide the image generation.150height (`int`, *optional*, defaults to 512):151The height in pixels of the generated image.152width (`int`, *optional*, defaults to 512):153The width in pixels of the generated image.154num_inference_steps (`int`, *optional*, defaults to 50):155The number of denoising steps. More denoising steps usually lead to a higher quality image at the156expense of slower inference.157guidance_scale (`float`, *optional*, defaults to 7.5):158Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).159`guidance_scale` is defined as `w` of equation 2. of [Imagen160Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >1611`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,162usually at the expense of lower image quality.163eta (`float`, *optional*, defaults to 0.0):164Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to165[`schedulers.DDIMScheduler`], will be ignored for others.166generator (`torch.Generator`, *optional*):167A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation168deterministic.169latents (`torch.FloatTensor`, *optional*):170Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image171generation. Can be used to tweak the same generation with different prompts. If not provided, a latents172tensor will ge generated by sampling using the supplied random `generator`.173output_type (`str`, *optional*, defaults to `"pil"`):174The output format of the generate image. Choose between175[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.176return_dict (`bool`, *optional*, defaults to `True`):177Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a178plain tuple.179Returns:180[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:181[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.182When returning a tuple, the first element is a list with the generated images, and the second element is a183list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"184(nsfw) content, according to the `safety_checker`.185"""186accelerator = Accelerator(187gradient_accumulation_steps=1,188mixed_precision="fp16",189)190191if "torch_device" in kwargs:192device = kwargs.pop("torch_device")193warnings.warn(194"`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."195" Consider using `pipe.to(torch_device)` instead."196)197198if device is None:199device = "cuda" if torch.cuda.is_available() else "cpu"200self.to(device)201202if height % 8 != 0 or width % 8 != 0:203raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")204205# Freeze vae and unet206self.vae.requires_grad_(False)207self.unet.requires_grad_(False)208self.text_encoder.requires_grad_(False)209self.unet.eval()210self.vae.eval()211self.text_encoder.eval()212213if accelerator.is_main_process:214accelerator.init_trackers(215"imagic",216config={217"embedding_learning_rate": embedding_learning_rate,218"text_embedding_optimization_steps": text_embedding_optimization_steps,219},220)221222# get text embeddings for prompt223text_input = self.tokenizer(224prompt,225padding="max_length",226max_length=self.tokenizer.model_max_length,227truncation=True,228return_tensors="pt",229)230text_embeddings = torch.nn.Parameter(231self.text_encoder(text_input.input_ids.to(self.device))[0], requires_grad=True232)233text_embeddings = text_embeddings.detach()234text_embeddings.requires_grad_()235text_embeddings_orig = text_embeddings.clone()236237# Initialize the optimizer238optimizer = torch.optim.Adam(239[text_embeddings], # only optimize the embeddings240lr=embedding_learning_rate,241)242243if isinstance(image, PIL.Image.Image):244image = preprocess(image)245246latents_dtype = text_embeddings.dtype247image = image.to(device=self.device, dtype=latents_dtype)248init_latent_image_dist = self.vae.encode(image).latent_dist249image_latents = init_latent_image_dist.sample(generator=generator)250image_latents = 0.18215 * image_latents251252progress_bar = tqdm(range(text_embedding_optimization_steps), disable=not accelerator.is_local_main_process)253progress_bar.set_description("Steps")254255global_step = 0256257logger.info("First optimizing the text embedding to better reconstruct the init image")258for _ in range(text_embedding_optimization_steps):259with accelerator.accumulate(text_embeddings):260# Sample noise that we'll add to the latents261noise = torch.randn(image_latents.shape).to(image_latents.device)262timesteps = torch.randint(1000, (1,), device=image_latents.device)263264# Add noise to the latents according to the noise magnitude at each timestep265# (this is the forward diffusion process)266noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)267268# Predict the noise residual269noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample270271loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()272accelerator.backward(loss)273274optimizer.step()275optimizer.zero_grad()276277# Checks if the accelerator has performed an optimization step behind the scenes278if accelerator.sync_gradients:279progress_bar.update(1)280global_step += 1281282logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}283progress_bar.set_postfix(**logs)284accelerator.log(logs, step=global_step)285286accelerator.wait_for_everyone()287288text_embeddings.requires_grad_(False)289290# Now we fine tune the unet to better reconstruct the image291self.unet.requires_grad_(True)292self.unet.train()293optimizer = torch.optim.Adam(294self.unet.parameters(), # only optimize unet295lr=diffusion_model_learning_rate,296)297progress_bar = tqdm(range(model_fine_tuning_optimization_steps), disable=not accelerator.is_local_main_process)298299logger.info("Next fine tuning the entire model to better reconstruct the init image")300for _ in range(model_fine_tuning_optimization_steps):301with accelerator.accumulate(self.unet.parameters()):302# Sample noise that we'll add to the latents303noise = torch.randn(image_latents.shape).to(image_latents.device)304timesteps = torch.randint(1000, (1,), device=image_latents.device)305306# Add noise to the latents according to the noise magnitude at each timestep307# (this is the forward diffusion process)308noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)309310# Predict the noise residual311noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample312313loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()314accelerator.backward(loss)315316optimizer.step()317optimizer.zero_grad()318319# Checks if the accelerator has performed an optimization step behind the scenes320if accelerator.sync_gradients:321progress_bar.update(1)322global_step += 1323324logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}325progress_bar.set_postfix(**logs)326accelerator.log(logs, step=global_step)327328accelerator.wait_for_everyone()329self.text_embeddings_orig = text_embeddings_orig330self.text_embeddings = text_embeddings331332@torch.no_grad()333def __call__(334self,335alpha: float = 1.2,336height: Optional[int] = 512,337width: Optional[int] = 512,338num_inference_steps: Optional[int] = 50,339generator: Optional[torch.Generator] = None,340output_type: Optional[str] = "pil",341return_dict: bool = True,342guidance_scale: float = 7.5,343eta: float = 0.0,344):345r"""346Function invoked when calling the pipeline for generation.347Args:348prompt (`str` or `List[str]`):349The prompt or prompts to guide the image generation.350height (`int`, *optional*, defaults to 512):351The height in pixels of the generated image.352width (`int`, *optional*, defaults to 512):353The width in pixels of the generated image.354num_inference_steps (`int`, *optional*, defaults to 50):355The number of denoising steps. More denoising steps usually lead to a higher quality image at the356expense of slower inference.357guidance_scale (`float`, *optional*, defaults to 7.5):358Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).359`guidance_scale` is defined as `w` of equation 2. of [Imagen360Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >3611`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,362usually at the expense of lower image quality.363eta (`float`, *optional*, defaults to 0.0):364Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to365[`schedulers.DDIMScheduler`], will be ignored for others.366generator (`torch.Generator`, *optional*):367A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation368deterministic.369latents (`torch.FloatTensor`, *optional*):370Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image371generation. Can be used to tweak the same generation with different prompts. If not provided, a latents372tensor will ge generated by sampling using the supplied random `generator`.373output_type (`str`, *optional*, defaults to `"pil"`):374The output format of the generate image. Choose between375[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.376return_dict (`bool`, *optional*, defaults to `True`):377Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a378plain tuple.379Returns:380[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:381[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.382When returning a tuple, the first element is a list with the generated images, and the second element is a383list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"384(nsfw) content, according to the `safety_checker`.385"""386if height % 8 != 0 or width % 8 != 0:387raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")388if self.text_embeddings is None:389raise ValueError("Please run the pipe.train() before trying to generate an image.")390if self.text_embeddings_orig is None:391raise ValueError("Please run the pipe.train() before trying to generate an image.")392393text_embeddings = alpha * self.text_embeddings_orig + (1 - alpha) * self.text_embeddings394395# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)396# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`397# corresponds to doing no classifier free guidance.398do_classifier_free_guidance = guidance_scale > 1.0399# get unconditional embeddings for classifier free guidance400if do_classifier_free_guidance:401uncond_tokens = [""]402max_length = self.tokenizer.model_max_length403uncond_input = self.tokenizer(404uncond_tokens,405padding="max_length",406max_length=max_length,407truncation=True,408return_tensors="pt",409)410uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]411412# duplicate unconditional embeddings for each generation per prompt, using mps friendly method413seq_len = uncond_embeddings.shape[1]414uncond_embeddings = uncond_embeddings.view(1, seq_len, -1)415416# For classifier free guidance, we need to do two forward passes.417# Here we concatenate the unconditional and text embeddings into a single batch418# to avoid doing two forward passes419text_embeddings = torch.cat([uncond_embeddings, text_embeddings])420421# get the initial random noise unless the user supplied it422423# Unlike in other pipelines, latents need to be generated in the target device424# for 1-to-1 results reproducibility with the CompVis implementation.425# However this currently doesn't work in `mps`.426latents_shape = (1, self.unet.in_channels, height // 8, width // 8)427latents_dtype = text_embeddings.dtype428if self.device.type == "mps":429# randn does not exist on mps430latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(431self.device432)433else:434latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)435436# set timesteps437self.scheduler.set_timesteps(num_inference_steps)438439# Some schedulers like PNDM have timesteps as arrays440# It's more optimized to move all timesteps to correct device beforehand441timesteps_tensor = self.scheduler.timesteps.to(self.device)442443# scale the initial noise by the standard deviation required by the scheduler444latents = latents * self.scheduler.init_noise_sigma445446# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature447# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.448# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502449# and should be between [0, 1]450accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())451extra_step_kwargs = {}452if accepts_eta:453extra_step_kwargs["eta"] = eta454455for i, t in enumerate(self.progress_bar(timesteps_tensor)):456# expand the latents if we are doing classifier free guidance457latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents458latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)459460# predict the noise residual461noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample462463# perform guidance464if do_classifier_free_guidance:465noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)466noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)467468# compute the previous noisy sample x_t -> x_t-1469latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample470471latents = 1 / 0.18215 * latents472image = self.vae.decode(latents).sample473474image = (image / 2 + 0.5).clamp(0, 1)475476# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16477image = image.cpu().permute(0, 2, 3, 1).float().numpy()478479if self.safety_checker is not None:480safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(481self.device482)483image, has_nsfw_concept = self.safety_checker(484images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)485)486else:487has_nsfw_concept = None488489if output_type == "pil":490image = self.numpy_to_pil(image)491492if not return_dict:493return (image, has_nsfw_concept)494495return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)496497498