CoolFace
Datasetpublic

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.

sourceHugging Faceupdated 1mo agoView on Hugging Face
9likes22kdownloads
imagic_stable_diffusion.py502 linesDownload Raw Back to v0.10.0
1"""2    modeled after the textual_inversion.py / train_dreambooth.py and the work3    of justinpinkney here: https://github.com/justinpinkney/stable-diffusion/blob/main/notebooks/imagic.ipynb4"""5import inspect6import warnings7from typing import List, Optional, Union8 9import numpy as np10import torch11import torch.nn.functional as F12 13import PIL14from accelerate import Accelerator15from diffusers.models import AutoencoderKL, UNet2DConditionModel16from diffusers.pipeline_utils import DiffusionPipeline17from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput18from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker19from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler20from diffusers.utils import deprecate, logging21 22# TODO: remove and import from diffusers.utils when the new version of diffusers is released23from packaging import version24from tqdm.auto import tqdm25from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer26 27 28if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):29    PIL_INTERPOLATION = {30        "linear": PIL.Image.Resampling.BILINEAR,31        "bilinear": PIL.Image.Resampling.BILINEAR,32        "bicubic": PIL.Image.Resampling.BICUBIC,33        "lanczos": PIL.Image.Resampling.LANCZOS,34        "nearest": PIL.Image.Resampling.NEAREST,35    }36else:37    PIL_INTERPOLATION = {38        "linear": PIL.Image.LINEAR,39        "bilinear": PIL.Image.BILINEAR,40        "bicubic": PIL.Image.BICUBIC,41        "lanczos": PIL.Image.LANCZOS,42        "nearest": PIL.Image.NEAREST,43    }44# ------------------------------------------------------------------------------45 46logger = logging.get_logger(__name__)  # pylint: disable=invalid-name47 48 49def preprocess(image):50    w, h = image.size51    w, h = map(lambda x: x - x % 32, (w, h))  # resize to integer multiple of 3252    image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])53    image = np.array(image).astype(np.float32) / 255.054    image = image[None].transpose(0, 3, 1, 2)55    image = torch.from_numpy(image)56    return 2.0 * image - 1.057 58 59class ImagicStableDiffusionPipeline(DiffusionPipeline):60    r"""61    Pipeline for imagic image editing.62    See paper here: https://arxiv.org/pdf/2210.09276.pdf63 64    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the65    library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)66    Args:67        vae ([`AutoencoderKL`]):68            Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.69        text_encoder ([`CLIPTextModel`]):70            Frozen text-encoder. Stable Diffusion uses the text portion of71            [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically72            the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.73        tokenizer (`CLIPTokenizer`):74            Tokenizer of class75            [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).76        unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.77        scheduler ([`SchedulerMixin`]):78            A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of79            [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].80        safety_checker ([`StableDiffusionSafetyChecker`]):81            Classification module that estimates whether generated images could be considered offsensive or harmful.82            Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.83        feature_extractor ([`CLIPFeatureExtractor`]):84            Model that extracts features from generated images to be used as inputs for the `safety_checker`.85    """86 87    def __init__(88        self,89        vae: AutoencoderKL,90        text_encoder: CLIPTextModel,91        tokenizer: CLIPTokenizer,92        unet: UNet2DConditionModel,93        scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],94        safety_checker: StableDiffusionSafetyChecker,95        feature_extractor: CLIPFeatureExtractor,96    ):97        super().__init__()98        self.register_modules(99            vae=vae,100            text_encoder=text_encoder,101            tokenizer=tokenizer,102            unet=unet,103            scheduler=scheduler,104            safety_checker=safety_checker,105            feature_extractor=feature_extractor,106        )107 108    def enable_attention_slicing(self, slice_size: Optional[Union[str, int]] = "auto"):109        r"""110        Enable sliced attention computation.111        When this option is enabled, the attention module will split the input tensor in slices, to compute attention112        in several steps. This is useful to save some memory in exchange for a small speed decrease.113        Args:114            slice_size (`str` or `int`, *optional*, defaults to `"auto"`):115                When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If116                a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case,117                `attention_head_dim` must be a multiple of `slice_size`.118        """119        if slice_size == "auto":120            # half the attention head size is usually a good trade-off between121            # speed and memory122            slice_size = self.unet.config.attention_head_dim // 2123        self.unet.set_attention_slice(slice_size)124 125    def disable_attention_slicing(self):126        r"""127        Disable sliced attention computation. If `enable_attention_slicing` was previously invoked, this method will go128        back to computing attention in one step.129        """130        # set slice_size = `None` to disable `attention slicing`131        self.enable_attention_slicing(None)132 133    def train(134        self,135        prompt: Union[str, List[str]],136        image: Union[torch.FloatTensor, PIL.Image.Image],137        height: Optional[int] = 512,138        width: Optional[int] = 512,139        generator: Optional[torch.Generator] = None,140        embedding_learning_rate: float = 0.001,141        diffusion_model_learning_rate: float = 2e-6,142        text_embedding_optimization_steps: int = 500,143        model_fine_tuning_optimization_steps: int = 1000,144        **kwargs,145    ):146        r"""147        Function invoked when calling the pipeline for generation.148        Args:149            prompt (`str` or `List[str]`):150                The prompt or prompts to guide the image generation.151            height (`int`, *optional*, defaults to 512):152                The height in pixels of the generated image.153            width (`int`, *optional*, defaults to 512):154                The width in pixels of the generated image.155            num_inference_steps (`int`, *optional*, defaults to 50):156                The number of denoising steps. More denoising steps usually lead to a higher quality image at the157                expense of slower inference.158            guidance_scale (`float`, *optional*, defaults to 7.5):159                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).160                `guidance_scale` is defined as `w` of equation 2. of [Imagen161                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >162                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,163                usually at the expense of lower image quality.164            eta (`float`, *optional*, defaults to 0.0):165                Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to166                [`schedulers.DDIMScheduler`], will be ignored for others.167            generator (`torch.Generator`, *optional*):168                A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation169                deterministic.170            latents (`torch.FloatTensor`, *optional*):171                Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image172                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents173                tensor will ge generated by sampling using the supplied random `generator`.174            output_type (`str`, *optional*, defaults to `"pil"`):175                The output format of the generate image. Choose between176                [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.177            return_dict (`bool`, *optional*, defaults to `True`):178                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a179                plain tuple.180        Returns:181            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:182            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.183            When returning a tuple, the first element is a list with the generated images, and the second element is a184            list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"185            (nsfw) content, according to the `safety_checker`.186        """187        message = "Please use `image` instead of `init_image`."188        init_image = deprecate("init_image", "0.12.0", message, take_from=kwargs)189        image = init_image or image190 191        accelerator = Accelerator(192            gradient_accumulation_steps=1,193            mixed_precision="fp16",194        )195 196        if "torch_device" in kwargs:197            device = kwargs.pop("torch_device")198            warnings.warn(199                "`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."200                " Consider using `pipe.to(torch_device)` instead."201            )202 203            if device is None:204                device = "cuda" if torch.cuda.is_available() else "cpu"205            self.to(device)206 207        if height % 8 != 0 or width % 8 != 0:208            raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")209 210        # Freeze vae and unet211        self.vae.requires_grad_(False)212        self.unet.requires_grad_(False)213        self.text_encoder.requires_grad_(False)214        self.unet.eval()215        self.vae.eval()216        self.text_encoder.eval()217 218        if accelerator.is_main_process:219            accelerator.init_trackers(220                "imagic",221                config={222                    "embedding_learning_rate": embedding_learning_rate,223                    "text_embedding_optimization_steps": text_embedding_optimization_steps,224                },225            )226 227        # get text embeddings for prompt228        text_input = self.tokenizer(229            prompt,230            padding="max_length",231            max_length=self.tokenizer.model_max_length,232            truncaton=True,233            return_tensors="pt",234        )235        text_embeddings = torch.nn.Parameter(236            self.text_encoder(text_input.input_ids.to(self.device))[0], requires_grad=True237        )238        text_embeddings = text_embeddings.detach()239        text_embeddings.requires_grad_()240        text_embeddings_orig = text_embeddings.clone()241 242        # Initialize the optimizer243        optimizer = torch.optim.Adam(244            [text_embeddings],  # only optimize the embeddings245            lr=embedding_learning_rate,246        )247 248        if isinstance(image, PIL.Image.Image):249            image = preprocess(image)250 251        latents_dtype = text_embeddings.dtype252        image = image.to(device=self.device, dtype=latents_dtype)253        init_latent_image_dist = self.vae.encode(image).latent_dist254        image_latents = init_latent_image_dist.sample(generator=generator)255        image_latents = 0.18215 * image_latents256 257        progress_bar = tqdm(range(text_embedding_optimization_steps), disable=not accelerator.is_local_main_process)258        progress_bar.set_description("Steps")259 260        global_step = 0261 262        logger.info("First optimizing the text embedding to better reconstruct the init image")263        for _ in range(text_embedding_optimization_steps):264            with accelerator.accumulate(text_embeddings):265                # Sample noise that we'll add to the latents266                noise = torch.randn(image_latents.shape).to(image_latents.device)267                timesteps = torch.randint(1000, (1,), device=image_latents.device)268 269                # Add noise to the latents according to the noise magnitude at each timestep270                # (this is the forward diffusion process)271                noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)272 273                # Predict the noise residual274                noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample275 276                loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()277                accelerator.backward(loss)278 279                optimizer.step()280                optimizer.zero_grad()281 282            # Checks if the accelerator has performed an optimization step behind the scenes283            if accelerator.sync_gradients:284                progress_bar.update(1)285                global_step += 1286 287            logs = {"loss": loss.detach().item()}  # , "lr": lr_scheduler.get_last_lr()[0]}288            progress_bar.set_postfix(**logs)289            accelerator.log(logs, step=global_step)290 291        accelerator.wait_for_everyone()292 293        text_embeddings.requires_grad_(False)294 295        # Now we fine tune the unet to better reconstruct the image296        self.unet.requires_grad_(True)297        self.unet.train()298        optimizer = torch.optim.Adam(299            self.unet.parameters(),  # only optimize unet300            lr=diffusion_model_learning_rate,301        )302        progress_bar = tqdm(range(model_fine_tuning_optimization_steps), disable=not accelerator.is_local_main_process)303 304        logger.info("Next fine tuning the entire model to better reconstruct the init image")305        for _ in range(model_fine_tuning_optimization_steps):306            with accelerator.accumulate(self.unet.parameters()):307                # Sample noise that we'll add to the latents308                noise = torch.randn(image_latents.shape).to(image_latents.device)309                timesteps = torch.randint(1000, (1,), device=image_latents.device)310 311                # Add noise to the latents according to the noise magnitude at each timestep312                # (this is the forward diffusion process)313                noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)314 315                # Predict the noise residual316                noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample317 318                loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()319                accelerator.backward(loss)320 321                optimizer.step()322                optimizer.zero_grad()323 324            # Checks if the accelerator has performed an optimization step behind the scenes325            if accelerator.sync_gradients:326                progress_bar.update(1)327                global_step += 1328 329            logs = {"loss": loss.detach().item()}  # , "lr": lr_scheduler.get_last_lr()[0]}330            progress_bar.set_postfix(**logs)331            accelerator.log(logs, step=global_step)332 333        accelerator.wait_for_everyone()334        self.text_embeddings_orig = text_embeddings_orig335        self.text_embeddings = text_embeddings336 337    @torch.no_grad()338    def __call__(339        self,340        alpha: float = 1.2,341        height: Optional[int] = 512,342        width: Optional[int] = 512,343        num_inference_steps: Optional[int] = 50,344        generator: Optional[torch.Generator] = None,345        output_type: Optional[str] = "pil",346        return_dict: bool = True,347        guidance_scale: float = 7.5,348        eta: float = 0.0,349        **kwargs,350    ):351        r"""352        Function invoked when calling the pipeline for generation.353        Args:354            prompt (`str` or `List[str]`):355                The prompt or prompts to guide the image generation.356            height (`int`, *optional*, defaults to 512):357                The height in pixels of the generated image.358            width (`int`, *optional*, defaults to 512):359                The width in pixels of the generated image.360            num_inference_steps (`int`, *optional*, defaults to 50):361                The number of denoising steps. More denoising steps usually lead to a higher quality image at the362                expense of slower inference.363            guidance_scale (`float`, *optional*, defaults to 7.5):364                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).365                `guidance_scale` is defined as `w` of equation 2. of [Imagen366                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >367                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,368                usually at the expense of lower image quality.369            eta (`float`, *optional*, defaults to 0.0):370                Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to371                [`schedulers.DDIMScheduler`], will be ignored for others.372            generator (`torch.Generator`, *optional*):373                A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation374                deterministic.375            latents (`torch.FloatTensor`, *optional*):376                Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image377                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents378                tensor will ge generated by sampling using the supplied random `generator`.379            output_type (`str`, *optional*, defaults to `"pil"`):380                The output format of the generate image. Choose between381                [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.382            return_dict (`bool`, *optional*, defaults to `True`):383                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a384                plain tuple.385        Returns:386            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:387            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.388            When returning a tuple, the first element is a list with the generated images, and the second element is a389            list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"390            (nsfw) content, according to the `safety_checker`.391        """392        if height % 8 != 0 or width % 8 != 0:393            raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")394        if self.text_embeddings is None:395            raise ValueError("Please run the pipe.train() before trying to generate an image.")396        if self.text_embeddings_orig is None:397            raise ValueError("Please run the pipe.train() before trying to generate an image.")398 399        text_embeddings = alpha * self.text_embeddings_orig + (1 - alpha) * self.text_embeddings400 401        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)402        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`403        # corresponds to doing no classifier free guidance.404        do_classifier_free_guidance = guidance_scale > 1.0405        # get unconditional embeddings for classifier free guidance406        if do_classifier_free_guidance:407            uncond_tokens = [""]408            max_length = self.tokenizer.model_max_length409            uncond_input = self.tokenizer(410                uncond_tokens,411                padding="max_length",412                max_length=max_length,413                truncation=True,414                return_tensors="pt",415            )416            uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]417 418            # duplicate unconditional embeddings for each generation per prompt, using mps friendly method419            seq_len = uncond_embeddings.shape[1]420            uncond_embeddings = uncond_embeddings.view(1, seq_len, -1)421 422            # For classifier free guidance, we need to do two forward passes.423            # Here we concatenate the unconditional and text embeddings into a single batch424            # to avoid doing two forward passes425            text_embeddings = torch.cat([uncond_embeddings, text_embeddings])426 427        # get the initial random noise unless the user supplied it428 429        # Unlike in other pipelines, latents need to be generated in the target device430        # for 1-to-1 results reproducibility with the CompVis implementation.431        # However this currently doesn't work in `mps`.432        latents_shape = (1, self.unet.in_channels, height // 8, width // 8)433        latents_dtype = text_embeddings.dtype434        if self.device.type == "mps":435            # randn does not exist on mps436            latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(437                self.device438            )439        else:440            latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)441 442        # set timesteps443        self.scheduler.set_timesteps(num_inference_steps)444 445        # Some schedulers like PNDM have timesteps as arrays446        # It's more optimized to move all timesteps to correct device beforehand447        timesteps_tensor = self.scheduler.timesteps.to(self.device)448 449        # scale the initial noise by the standard deviation required by the scheduler450        latents = latents * self.scheduler.init_noise_sigma451 452        # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature453        # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.454        # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502455        # and should be between [0, 1]456        accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())457        extra_step_kwargs = {}458        if accepts_eta:459            extra_step_kwargs["eta"] = eta460 461        for i, t in enumerate(self.progress_bar(timesteps_tensor)):462            # expand the latents if we are doing classifier free guidance463            latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents464            latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)465 466            # predict the noise residual467            noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample468 469            # perform guidance470            if do_classifier_free_guidance:471                noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)472                noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)473 474            # compute the previous noisy sample x_t -> x_t-1475            latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample476 477        latents = 1 / 0.18215 * latents478        image = self.vae.decode(latents).sample479 480        image = (image / 2 + 0.5).clamp(0, 1)481 482        # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16483        image = image.cpu().permute(0, 2, 3, 1).float().numpy()484 485        if self.safety_checker is not None:486            safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(487                self.device488            )489            image, has_nsfw_concept = self.safety_checker(490                images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)491            )492        else:493            has_nsfw_concept = None494 495        if output_type == "pil":496            image = self.numpy_to_pil(image)497 498        if not return_dict:499            return (image, has_nsfw_concept)500 501        return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)502