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 27d agoView on Hugging Face
9likes22kdownloads
composable_stable_diffusion.py533 linesDownload Raw Back to root
1# Copyright 2024 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 hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 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 hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample 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 = hasattr(unet.config, "_diffusers_version") and version.parse(136            version.parse(unet.config._diffusers_version).base_version137        ) < version.parse("0.9.0.dev0")138        is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64139        if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:140            deprecation_message = (141                "The configuration file of the unet has set the default `sample_size` to smaller than"142                " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"143                " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"144                " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"145                " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"146                " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"147                " in the config might lead to incorrect results in future versions. If you have downloaded this"148                " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"149                " the `unet/config.json` file"150            )151            deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)152            new_config = dict(unet.config)153            new_config["sample_size"] = 64154            unet._internal_dict = FrozenDict(new_config)155 156        self.register_modules(157            vae=vae,158            text_encoder=text_encoder,159            tokenizer=tokenizer,160            unet=unet,161            scheduler=scheduler,162            safety_checker=safety_checker,163            feature_extractor=feature_extractor,164        )165        self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)166        self.register_to_config(requires_safety_checker=requires_safety_checker)167 168    def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):169        r"""170        Encodes the prompt into text encoder hidden states.171 172        Args:173            prompt (`str` or `list(int)`):174                prompt to be encoded175            device: (`torch.device`):176                torch device177            num_images_per_prompt (`int`):178                number of images that should be generated per prompt179            do_classifier_free_guidance (`bool`):180                whether to use classifier free guidance or not181            negative_prompt (`str` or `List[str]`):182                The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored183                if `guidance_scale` is less than `1`).184        """185        batch_size = len(prompt) if isinstance(prompt, list) else 1186 187        text_inputs = self.tokenizer(188            prompt,189            padding="max_length",190            max_length=self.tokenizer.model_max_length,191            truncation=True,192            return_tensors="pt",193        )194        text_input_ids = text_inputs.input_ids195        untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids196 197        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):198            removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])199            logger.warning(200                "The following part of your input was truncated because CLIP can only handle sequences up to"201                f" {self.tokenizer.model_max_length} tokens: {removed_text}"202            )203 204        if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:205            attention_mask = text_inputs.attention_mask.to(device)206        else:207            attention_mask = None208 209        text_embeddings = self.text_encoder(210            text_input_ids.to(device),211            attention_mask=attention_mask,212        )213        text_embeddings = text_embeddings[0]214 215        # duplicate text embeddings for each generation per prompt, using mps friendly method216        bs_embed, seq_len, _ = text_embeddings.shape217        text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)218        text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)219 220        # get unconditional embeddings for classifier free guidance221        if do_classifier_free_guidance:222            uncond_tokens: List[str]223            if negative_prompt is None:224                uncond_tokens = [""] * batch_size225            elif type(prompt) is not type(negative_prompt):226                raise TypeError(227                    f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="228                    f" {type(prompt)}."229                )230            elif isinstance(negative_prompt, str):231                uncond_tokens = [negative_prompt]232            elif batch_size != len(negative_prompt):233                raise ValueError(234                    f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"235                    f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"236                    " the batch size of `prompt`."237                )238            else:239                uncond_tokens = negative_prompt240 241            max_length = text_input_ids.shape[-1]242            uncond_input = self.tokenizer(243                uncond_tokens,244                padding="max_length",245                max_length=max_length,246                truncation=True,247                return_tensors="pt",248            )249 250            if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:251                attention_mask = uncond_input.attention_mask.to(device)252            else:253                attention_mask = None254 255            uncond_embeddings = self.text_encoder(256                uncond_input.input_ids.to(device),257                attention_mask=attention_mask,258            )259            uncond_embeddings = uncond_embeddings[0]260 261            # duplicate unconditional embeddings for each generation per prompt, using mps friendly method262            seq_len = uncond_embeddings.shape[1]263            uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)264            uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)265 266            # For classifier free guidance, we need to do two forward passes.267            # Here we concatenate the unconditional and text embeddings into a single batch268            # to avoid doing two forward passes269            text_embeddings = torch.cat([uncond_embeddings, text_embeddings])270 271        return text_embeddings272 273    def run_safety_checker(self, image, device, dtype):274        if self.safety_checker is not None:275            safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)276            image, has_nsfw_concept = self.safety_checker(277                images=image, clip_input=safety_checker_input.pixel_values.to(dtype)278            )279        else:280            has_nsfw_concept = None281        return image, has_nsfw_concept282 283    def decode_latents(self, latents):284        latents = 1 / 0.18215 * latents285        image = self.vae.decode(latents).sample286        image = (image / 2 + 0.5).clamp(0, 1)287        # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16288        image = image.cpu().permute(0, 2, 3, 1).float().numpy()289        return image290 291    def prepare_extra_step_kwargs(self, generator, eta):292        # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature293        # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.294        # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502295        # and should be between [0, 1]296 297        accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())298        extra_step_kwargs = {}299        if accepts_eta:300            extra_step_kwargs["eta"] = eta301 302        # check if the scheduler accepts generator303        accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())304        if accepts_generator:305            extra_step_kwargs["generator"] = generator306        return extra_step_kwargs307 308    def check_inputs(self, prompt, height, width, callback_steps):309        if not isinstance(prompt, str) and not isinstance(prompt, list):310            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")311 312        if height % 8 != 0 or width % 8 != 0:313            raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")314 315        if (callback_steps is None) or (316            callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)317        ):318            raise ValueError(319                f"`callback_steps` has to be a positive integer but is {callback_steps} of type"320                f" {type(callback_steps)}."321            )322 323    def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):324        shape = (325            batch_size,326            num_channels_latents,327            int(height) // self.vae_scale_factor,328            int(width) // self.vae_scale_factor,329        )330        if latents is None:331            if device.type == "mps":332                # randn does not work reproducibly on mps333                latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)334            else:335                latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)336        else:337            if latents.shape != shape:338                raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")339            latents = latents.to(device)340 341        # scale the initial noise by the standard deviation required by the scheduler342        latents = latents * self.scheduler.init_noise_sigma343        return latents344 345    @torch.no_grad()346    def __call__(347        self,348        prompt: Union[str, List[str]],349        height: Optional[int] = None,350        width: Optional[int] = None,351        num_inference_steps: int = 50,352        guidance_scale: float = 7.5,353        negative_prompt: Optional[Union[str, List[str]]] = None,354        num_images_per_prompt: Optional[int] = 1,355        eta: float = 0.0,356        generator: Optional[torch.Generator] = None,357        latents: Optional[torch.Tensor] = None,358        output_type: Optional[str] = "pil",359        return_dict: bool = True,360        callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,361        callback_steps: int = 1,362        weights: Optional[str] = "",363    ):364        r"""365        Function invoked when calling the pipeline for generation.366 367        Args:368            prompt (`str` or `List[str]`):369                The prompt or prompts to guide the image generation.370            height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):371                The height in pixels of the generated image.372            width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):373                The width in pixels of the generated image.374            num_inference_steps (`int`, *optional*, defaults to 50):375                The number of denoising steps. More denoising steps usually lead to a higher quality image at the376                expense of slower inference.377            guidance_scale (`float`, *optional*, defaults to 5.0):378                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).379                `guidance_scale` is defined as `w` of equation 2. of [Imagen380                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >381                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,382                usually at the expense of lower image quality.383            negative_prompt (`str` or `List[str]`, *optional*):384                The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored385                if `guidance_scale` is less than `1`).386            num_images_per_prompt (`int`, *optional*, defaults to 1):387                The number of images to generate per prompt.388            eta (`float`, *optional*, defaults to 0.0):389                Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to390                [`schedulers.DDIMScheduler`], will be ignored for others.391            generator (`torch.Generator`, *optional*):392                A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation393                deterministic.394            latents (`torch.Tensor`, *optional*):395                Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image396                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents397                tensor will ge generated by sampling using the supplied random `generator`.398            output_type (`str`, *optional*, defaults to `"pil"`):399                The output format of the generate image. Choose between400                [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.401            return_dict (`bool`, *optional*, defaults to `True`):402                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a403                plain tuple.404            callback (`Callable`, *optional*):405                A function that will be called every `callback_steps` steps during inference. The function will be406                called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.407            callback_steps (`int`, *optional*, defaults to 1):408                The frequency at which the `callback` function will be called. If not specified, the callback will be409                called at every step.410 411        Returns:412            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:413            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.414            When returning a tuple, the first element is a list with the generated images, and the second element is a415            list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"416            (nsfw) content, according to the `safety_checker`.417        """418        # 0. Default height and width to unet419        height = height or self.unet.config.sample_size * self.vae_scale_factor420        width = width or self.unet.config.sample_size * self.vae_scale_factor421 422        # 1. Check inputs. Raise error if not correct423        self.check_inputs(prompt, height, width, callback_steps)424 425        # 2. Define call parameters426        batch_size = 1 if isinstance(prompt, str) else len(prompt)427        device = self._execution_device428        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)429        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`430        # corresponds to doing no classifier free guidance.431        do_classifier_free_guidance = guidance_scale > 1.0432 433        if "|" in prompt:434            prompt = [x.strip() for x in prompt.split("|")]435            print(f"composing {prompt}...")436 437            if not weights:438                # specify weights for prompts (excluding the unconditional score)439                print("using equal positive weights (conjunction) for all prompts...")440                weights = torch.tensor([guidance_scale] * len(prompt), device=self.device).reshape(-1, 1, 1, 1)441            else:442                # set prompt weight for each443                num_prompts = len(prompt) if isinstance(prompt, list) else 1444                weights = [float(w.strip()) for w in weights.split("|")]445                # guidance scale as the default446                if len(weights) < num_prompts:447                    weights.append(guidance_scale)448                else:449                    weights = weights[:num_prompts]450                assert len(weights) == len(prompt), "weights specified are not equal to the number of prompts"451                weights = torch.tensor(weights, device=self.device).reshape(-1, 1, 1, 1)452        else:453            weights = guidance_scale454 455        # 3. Encode input prompt456        text_embeddings = self._encode_prompt(457            prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt458        )459 460        # 4. Prepare timesteps461        self.scheduler.set_timesteps(num_inference_steps, device=device)462        timesteps = self.scheduler.timesteps463 464        # 5. Prepare latent variables465        num_channels_latents = self.unet.config.in_channels466        latents = self.prepare_latents(467            batch_size * num_images_per_prompt,468            num_channels_latents,469            height,470            width,471            text_embeddings.dtype,472            device,473            generator,474            latents,475        )476 477        # composable diffusion478        if isinstance(prompt, list) and batch_size == 1:479            # remove extra unconditional embedding480            # N = one unconditional embed + conditional embeds481            text_embeddings = text_embeddings[len(prompt) - 1 :]482 483        # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline484        extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)485 486        # 7. Denoising loop487        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order488        with self.progress_bar(total=num_inference_steps) as progress_bar:489            for i, t in enumerate(timesteps):490                # expand the latents if we are doing classifier free guidance491                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents492                latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)493 494                # predict the noise residual495                noise_pred = []496                for j in range(text_embeddings.shape[0]):497                    noise_pred.append(498                        self.unet(latent_model_input[:1], t, encoder_hidden_states=text_embeddings[j : j + 1]).sample499                    )500                noise_pred = torch.cat(noise_pred, dim=0)501 502                # perform guidance503                if do_classifier_free_guidance:504                    noise_pred_uncond, noise_pred_text = noise_pred[:1], noise_pred[1:]505                    noise_pred = noise_pred_uncond + (weights * (noise_pred_text - noise_pred_uncond)).sum(506                        dim=0, keepdims=True507                    )508 509                # compute the previous noisy sample x_t -> x_t-1510                latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample511 512                # call the callback, if provided513                if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):514                    progress_bar.update()515                    if callback is not None and i % callback_steps == 0:516                        step_idx = i // getattr(self.scheduler, "order", 1)517                        callback(step_idx, t, latents)518 519        # 8. Post-processing520        image = self.decode_latents(latents)521 522        # 9. Run safety checker523        image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)524 525        # 10. Convert to PIL526        if output_type == "pil":527            image = self.numpy_to_pil(image)528 529        if not return_dict:530            return (image, has_nsfw_concept)531 532        return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)533