Path: blob/main/examples/community/ddim_noise_comparative_analysis.py
1448 views
# Copyright 2022 The HuggingFace Team. All rights reserved.1#2# Licensed under the Apache License, Version 2.0 (the "License");3# you may not use this file except in compliance with the License.4# You may obtain a copy of the License at5#6# http://www.apache.org/licenses/LICENSE-2.07#8# Unless required by applicable law or agreed to in writing, software9# distributed under the License is distributed on an "AS IS" BASIS,10# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11# See the License for the specific language governing permissions and12# limitations under the License.1314from typing import List, Optional, Tuple, Union1516import PIL17import torch18from torchvision import transforms1920from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput21from diffusers.schedulers import DDIMScheduler22from diffusers.utils import randn_tensor232425trans = transforms.Compose(26[27transforms.Resize((256, 256)),28transforms.ToTensor(),29transforms.Normalize([0.5], [0.5]),30]31)323334def preprocess(image):35if isinstance(image, torch.Tensor):36return image37elif isinstance(image, PIL.Image.Image):38image = [image]3940image = [trans(img.convert("RGB")) for img in image]41image = torch.stack(image)42return image434445class DDIMNoiseComparativeAnalysisPipeline(DiffusionPipeline):46r"""47This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the48library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)4950Parameters:51unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.52scheduler ([`SchedulerMixin`]):53A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of54[`DDPMScheduler`], or [`DDIMScheduler`].55"""5657def __init__(self, unet, scheduler):58super().__init__()5960# make sure scheduler can always be converted to DDIM61scheduler = DDIMScheduler.from_config(scheduler.config)6263self.register_modules(unet=unet, scheduler=scheduler)6465def check_inputs(self, strength):66if strength < 0 or strength > 1:67raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")6869def get_timesteps(self, num_inference_steps, strength, device):70# get the original timestep using init_timestep71init_timestep = min(int(num_inference_steps * strength), num_inference_steps)7273t_start = max(num_inference_steps - init_timestep, 0)74timesteps = self.scheduler.timesteps[t_start:]7576return timesteps, num_inference_steps - t_start7778def prepare_latents(self, image, timestep, batch_size, dtype, device, generator=None):79if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):80raise ValueError(81f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"82)8384init_latents = image.to(device=device, dtype=dtype)8586if isinstance(generator, list) and len(generator) != batch_size:87raise ValueError(88f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"89f" size of {batch_size}. Make sure the batch size matches the length of the generators."90)9192shape = init_latents.shape93noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)9495# get latents96print("add noise to latents at timestep", timestep)97init_latents = self.scheduler.add_noise(init_latents, noise, timestep)98latents = init_latents99100return latents101102@torch.no_grad()103def __call__(104self,105image: Union[torch.FloatTensor, PIL.Image.Image] = None,106strength: float = 0.8,107batch_size: int = 1,108generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,109eta: float = 0.0,110num_inference_steps: int = 50,111use_clipped_model_output: Optional[bool] = None,112output_type: Optional[str] = "pil",113return_dict: bool = True,114) -> Union[ImagePipelineOutput, Tuple]:115r"""116Args:117image (`torch.FloatTensor` or `PIL.Image.Image`):118`Image`, or tensor representing an image batch, that will be used as the starting point for the119process.120strength (`float`, *optional*, defaults to 0.8):121Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`122will be used as a starting point, adding more noise to it the larger the `strength`. The number of123denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will124be maximum and the denoising process will run for the full number of iterations specified in125`num_inference_steps`. A value of 1, therefore, essentially ignores `image`.126batch_size (`int`, *optional*, defaults to 1):127The number of images to generate.128generator (`torch.Generator`, *optional*):129One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)130to make generation deterministic.131eta (`float`, *optional*, defaults to 0.0):132The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM).133num_inference_steps (`int`, *optional*, defaults to 50):134The number of denoising steps. More denoising steps usually lead to a higher quality image at the135expense of slower inference.136use_clipped_model_output (`bool`, *optional*, defaults to `None`):137if `True` or `False`, see documentation for `DDIMScheduler.step`. If `None`, nothing is passed138downstream to the scheduler. So use `None` for schedulers which don't support this argument.139output_type (`str`, *optional*, defaults to `"pil"`):140The output format of the generate image. Choose between141[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.142return_dict (`bool`, *optional*, defaults to `True`):143Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.144145Returns:146[`~pipelines.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if `return_dict` is147True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images.148"""149# 1. Check inputs. Raise error if not correct150self.check_inputs(strength)151152# 2. Preprocess image153image = preprocess(image)154155# 3. set timesteps156self.scheduler.set_timesteps(num_inference_steps, device=self.device)157timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, self.device)158latent_timestep = timesteps[:1].repeat(batch_size)159160# 4. Prepare latent variables161latents = self.prepare_latents(image, latent_timestep, batch_size, self.unet.dtype, self.device, generator)162image = latents163164# 5. Denoising loop165for t in self.progress_bar(timesteps):166# 1. predict noise model_output167model_output = self.unet(image, t).sample168169# 2. predict previous mean of image x_t-1 and add variance depending on eta170# eta corresponds to η in paper and should be between [0, 1]171# do x_t -> x_t-1172image = self.scheduler.step(173model_output,174t,175image,176eta=eta,177use_clipped_model_output=use_clipped_model_output,178generator=generator,179).prev_sample180181image = (image / 2 + 0.5).clamp(0, 1)182image = image.cpu().permute(0, 2, 3, 1).numpy()183if output_type == "pil":184image = self.numpy_to_pil(image)185186if not return_dict:187return (image, latent_timestep.item())188189return ImagePipelineOutput(images=image)190191192