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 28d agoView on Hugging Face
9likes22kdownloads
pipeline_stable_diffusion_upscale_ldm3d.py773 linesDownload Raw Back to root
1# Copyright 2024 The Intel Labs Team Authors and 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 Any, Callable, Dict, List, Optional, Union17 18import numpy as np19import PIL20import torch21from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer22 23from diffusers import DiffusionPipeline24from diffusers.image_processor import PipelineDepthInput, PipelineImageInput, VaeImageProcessorLDM3D25from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin26from diffusers.models import AutoencoderKL, UNet2DConditionModel27from diffusers.models.lora import adjust_lora_scale_text_encoder28from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker29from diffusers.pipelines.stable_diffusion_ldm3d.pipeline_stable_diffusion_ldm3d import LDM3DPipelineOutput30from diffusers.schedulers import DDPMScheduler, KarrasDiffusionSchedulers31from diffusers.utils import (32    USE_PEFT_BACKEND,33    deprecate,34    logging,35    scale_lora_layers,36    unscale_lora_layers,37)38from diffusers.utils.torch_utils import randn_tensor39 40 41logger = logging.get_logger(__name__)  # pylint: disable=invalid-name42 43EXAMPLE_DOC_STRING = """44    Examples:45        ```python46        >>> from diffusers import StableDiffusionUpscaleLDM3DPipeline47        >>> from PIL import Image48        >>> from io import BytesIO49        >>> import requests50 51        >>> pipe = StableDiffusionUpscaleLDM3DPipeline.from_pretrained("Intel/ldm3d-sr")52        >>> pipe = pipe.to("cuda")53        >>> rgb_path = "https://huggingface.co/Intel/ldm3d-sr/resolve/main/lemons_ldm3d_rgb.jpg"54        >>> depth_path = "https://huggingface.co/Intel/ldm3d-sr/resolve/main/lemons_ldm3d_depth.png"55        >>> low_res_rgb = Image.open(BytesIO(requests.get(rgb_path).content)).convert("RGB")56        >>> low_res_depth = Image.open(BytesIO(requests.get(depth_path).content)).convert("L")57        >>> output = pipe(58        ...     prompt="high quality high resolution uhd 4k image",59        ...     rgb=low_res_rgb,60        ...     depth=low_res_depth,61        ...     num_inference_steps=50,62        ...     target_res=[1024, 1024],63        ... )64        >>> rgb_image, depth_image = output.rgb, output.depth65        >>> rgb_image[0].save("hr_ldm3d_rgb.jpg")66        >>> depth_image[0].save("hr_ldm3d_depth.png")67        ```68"""69 70 71class StableDiffusionUpscaleLDM3DPipeline(72    DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin73):74    r"""75    Pipeline for text-to-image and 3D generation using LDM3D.76 77    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods78    implemented for all pipelines (downloading, saving, running on a particular device, etc.).79 80    The pipeline also inherits the following loading methods:81        - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings82        - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights83        - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights84        - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files85 86    Args:87        vae ([`AutoencoderKL`]):88            Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.89        text_encoder ([`~transformers.CLIPTextModel`]):90            Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).91        tokenizer ([`~transformers.CLIPTokenizer`]):92            A `CLIPTokenizer` to tokenize text.93        unet ([`UNet2DConditionModel`]):94            A `UNet2DConditionModel` to denoise the encoded image latents.95        low_res_scheduler ([`SchedulerMixin`]):96            A scheduler used to add initial noise to the low resolution conditioning image. It must be an instance of97            [`DDPMScheduler`].98        scheduler ([`SchedulerMixin`]):99            A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of100            [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].101        safety_checker ([`StableDiffusionSafetyChecker`]):102            Classification module that estimates whether generated images could be considered offensive or harmful.103            Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details104            about a model's potential harms.105        feature_extractor ([`~transformers.CLIPImageProcessor`]):106            A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.107    """108 109    _optional_components = ["safety_checker", "feature_extractor"]110 111    def __init__(112        self,113        vae: AutoencoderKL,114        text_encoder: CLIPTextModel,115        tokenizer: CLIPTokenizer,116        unet: UNet2DConditionModel,117        low_res_scheduler: DDPMScheduler,118        scheduler: KarrasDiffusionSchedulers,119        safety_checker: StableDiffusionSafetyChecker,120        feature_extractor: CLIPImageProcessor,121        requires_safety_checker: bool = True,122        watermarker: Optional[Any] = None,123        max_noise_level: int = 350,124    ):125        super().__init__()126 127        if safety_checker is None and requires_safety_checker:128            logger.warning(129                f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"130                " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"131                " results in services or applications open to the public. Both the diffusers team and Hugging Face"132                " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"133                " it only for use-cases that involve analyzing network behavior or auditing its results. For more"134                " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."135            )136 137        if safety_checker is not None and feature_extractor is None:138            raise ValueError(139                "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"140                " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."141            )142 143        self.register_modules(144            vae=vae,145            text_encoder=text_encoder,146            tokenizer=tokenizer,147            unet=unet,148            low_res_scheduler=low_res_scheduler,149            scheduler=scheduler,150            safety_checker=safety_checker,151            watermarker=watermarker,152            feature_extractor=feature_extractor,153        )154        self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)155        self.image_processor = VaeImageProcessorLDM3D(vae_scale_factor=self.vae_scale_factor, resample="bilinear")156        # self.register_to_config(requires_safety_checker=requires_safety_checker)157        self.register_to_config(max_noise_level=max_noise_level)158 159    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_ldm3d.StableDiffusionLDM3DPipeline._encode_prompt160    def _encode_prompt(161        self,162        prompt,163        device,164        num_images_per_prompt,165        do_classifier_free_guidance,166        negative_prompt=None,167        prompt_embeds: Optional[torch.Tensor] = None,168        negative_prompt_embeds: Optional[torch.Tensor] = None,169        lora_scale: Optional[float] = None,170        **kwargs,171    ):172        deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."173        deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)174 175        prompt_embeds_tuple = self.encode_prompt(176            prompt=prompt,177            device=device,178            num_images_per_prompt=num_images_per_prompt,179            do_classifier_free_guidance=do_classifier_free_guidance,180            negative_prompt=negative_prompt,181            prompt_embeds=prompt_embeds,182            negative_prompt_embeds=negative_prompt_embeds,183            lora_scale=lora_scale,184            **kwargs,185        )186 187        # concatenate for backwards comp188        prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])189 190        return prompt_embeds191 192    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_ldm3d.StableDiffusionLDM3DPipeline.encode_prompt193    def encode_prompt(194        self,195        prompt,196        device,197        num_images_per_prompt,198        do_classifier_free_guidance,199        negative_prompt=None,200        prompt_embeds: Optional[torch.Tensor] = None,201        negative_prompt_embeds: Optional[torch.Tensor] = None,202        lora_scale: Optional[float] = None,203        clip_skip: Optional[int] = None,204    ):205        r"""206        Encodes the prompt into text encoder hidden states.207 208        Args:209            prompt (`str` or `List[str]`, *optional*):210                prompt to be encoded211            device: (`torch.device`):212                torch device213            num_images_per_prompt (`int`):214                number of images that should be generated per prompt215            do_classifier_free_guidance (`bool`):216                whether to use classifier free guidance or not217            negative_prompt (`str` or `List[str]`, *optional*):218                The prompt or prompts not to guide the image generation. If not defined, one has to pass219                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is220                less than `1`).221            prompt_embeds (`torch.Tensor`, *optional*):222                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not223                provided, text embeddings will be generated from `prompt` input argument.224            negative_prompt_embeds (`torch.Tensor`, *optional*):225                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt226                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input227                argument.228            lora_scale (`float`, *optional*):229                A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.230            clip_skip (`int`, *optional*):231                Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that232                the output of the pre-final layer will be used for computing the prompt embeddings.233        """234        # set lora scale so that monkey patched LoRA235        # function of text encoder can correctly access it236        if lora_scale is not None and isinstance(self, LoraLoaderMixin):237            self._lora_scale = lora_scale238 239            # dynamically adjust the LoRA scale240            if not USE_PEFT_BACKEND:241                adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)242            else:243                scale_lora_layers(self.text_encoder, lora_scale)244 245        if prompt is not None and isinstance(prompt, str):246            batch_size = 1247        elif prompt is not None and isinstance(prompt, list):248            batch_size = len(prompt)249        else:250            batch_size = prompt_embeds.shape[0]251 252        if prompt_embeds is None:253            # textual inversion: process multi-vector tokens if necessary254            if isinstance(self, TextualInversionLoaderMixin):255                prompt = self.maybe_convert_prompt(prompt, self.tokenizer)256 257            text_inputs = self.tokenizer(258                prompt,259                padding="max_length",260                max_length=self.tokenizer.model_max_length,261                truncation=True,262                return_tensors="pt",263            )264            text_input_ids = text_inputs.input_ids265            untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids266 267            if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(268                text_input_ids, untruncated_ids269            ):270                removed_text = self.tokenizer.batch_decode(271                    untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]272                )273                logger.warning(274                    "The following part of your input was truncated because CLIP can only handle sequences up to"275                    f" {self.tokenizer.model_max_length} tokens: {removed_text}"276                )277 278            if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:279                attention_mask = text_inputs.attention_mask.to(device)280            else:281                attention_mask = None282 283            if clip_skip is None:284                prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)285                prompt_embeds = prompt_embeds[0]286            else:287                prompt_embeds = self.text_encoder(288                    text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True289                )290                # Access the `hidden_states` first, that contains a tuple of291                # all the hidden states from the encoder layers. Then index into292                # the tuple to access the hidden states from the desired layer.293                prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]294                # We also need to apply the final LayerNorm here to not mess with the295                # representations. The `last_hidden_states` that we typically use for296                # obtaining the final prompt representations passes through the LayerNorm297                # layer.298                prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)299 300        if self.text_encoder is not None:301            prompt_embeds_dtype = self.text_encoder.dtype302        elif self.unet is not None:303            prompt_embeds_dtype = self.unet.dtype304        else:305            prompt_embeds_dtype = prompt_embeds.dtype306 307        prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)308 309        bs_embed, seq_len, _ = prompt_embeds.shape310        # duplicate text embeddings for each generation per prompt, using mps friendly method311        prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)312        prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)313 314        # get unconditional embeddings for classifier free guidance315        if do_classifier_free_guidance and negative_prompt_embeds is None:316            uncond_tokens: List[str]317            if negative_prompt is None:318                uncond_tokens = [""] * batch_size319            elif prompt is not None and type(prompt) is not type(negative_prompt):320                raise TypeError(321                    f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="322                    f" {type(prompt)}."323                )324            elif isinstance(negative_prompt, str):325                uncond_tokens = [negative_prompt]326            elif batch_size != len(negative_prompt):327                raise ValueError(328                    f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"329                    f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"330                    " the batch size of `prompt`."331                )332            else:333                uncond_tokens = negative_prompt334 335            # textual inversion: process multi-vector tokens if necessary336            if isinstance(self, TextualInversionLoaderMixin):337                uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)338 339            max_length = prompt_embeds.shape[1]340            uncond_input = self.tokenizer(341                uncond_tokens,342                padding="max_length",343                max_length=max_length,344                truncation=True,345                return_tensors="pt",346            )347 348            if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:349                attention_mask = uncond_input.attention_mask.to(device)350            else:351                attention_mask = None352 353            negative_prompt_embeds = self.text_encoder(354                uncond_input.input_ids.to(device),355                attention_mask=attention_mask,356            )357            negative_prompt_embeds = negative_prompt_embeds[0]358 359        if do_classifier_free_guidance:360            # duplicate unconditional embeddings for each generation per prompt, using mps friendly method361            seq_len = negative_prompt_embeds.shape[1]362 363            negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)364 365            negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)366            negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)367 368        if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:369            # Retrieve the original scale by scaling back the LoRA layers370            unscale_lora_layers(self.text_encoder, lora_scale)371 372        return prompt_embeds, negative_prompt_embeds373 374    def run_safety_checker(self, image, device, dtype):375        if self.safety_checker is None:376            has_nsfw_concept = None377        else:378            if torch.is_tensor(image):379                feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")380            else:381                feature_extractor_input = self.image_processor.numpy_to_pil(image)382            rgb_feature_extractor_input = feature_extractor_input[0]383            safety_checker_input = self.feature_extractor(rgb_feature_extractor_input, return_tensors="pt").to(device)384            image, has_nsfw_concept = self.safety_checker(385                images=image, clip_input=safety_checker_input.pixel_values.to(dtype)386            )387        return image, has_nsfw_concept388 389    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs390    def prepare_extra_step_kwargs(self, generator, eta):391        # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature392        # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.393        # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502394        # and should be between [0, 1]395 396        accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())397        extra_step_kwargs = {}398        if accepts_eta:399            extra_step_kwargs["eta"] = eta400 401        # check if the scheduler accepts generator402        accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())403        if accepts_generator:404            extra_step_kwargs["generator"] = generator405        return extra_step_kwargs406 407    def check_inputs(408        self,409        prompt,410        image,411        noise_level,412        callback_steps,413        negative_prompt=None,414        prompt_embeds=None,415        negative_prompt_embeds=None,416        target_res=None,417    ):418        if (callback_steps is None) or (419            callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)420        ):421            raise ValueError(422                f"`callback_steps` has to be a positive integer but is {callback_steps} of type"423                f" {type(callback_steps)}."424            )425 426        if prompt is not None and prompt_embeds is not None:427            raise ValueError(428                f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"429                " only forward one of the two."430            )431        elif prompt is None and prompt_embeds is None:432            raise ValueError(433                "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."434            )435        elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):436            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")437 438        if negative_prompt is not None and negative_prompt_embeds is not None:439            raise ValueError(440                f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"441                f" {negative_prompt_embeds}. Please make sure to only forward one of the two."442            )443 444        if prompt_embeds is not None and negative_prompt_embeds is not None:445            if prompt_embeds.shape != negative_prompt_embeds.shape:446                raise ValueError(447                    "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"448                    f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"449                    f" {negative_prompt_embeds.shape}."450                )451 452        if (453            not isinstance(image, torch.Tensor)454            and not isinstance(image, PIL.Image.Image)455            and not isinstance(image, np.ndarray)456            and not isinstance(image, list)457        ):458            raise ValueError(459                f"`image` has to be of type `torch.Tensor`, `np.ndarray`, `PIL.Image.Image` or `list` but is {type(image)}"460            )461 462        # verify batch size of prompt and image are same if image is a list or tensor or numpy array463        if isinstance(image, (list, np.ndarray, torch.Tensor)):464            if prompt is not None and isinstance(prompt, str):465                batch_size = 1466            elif prompt is not None and isinstance(prompt, list):467                batch_size = len(prompt)468            else:469                batch_size = prompt_embeds.shape[0]470 471            if isinstance(image, list):472                image_batch_size = len(image)473            else:474                image_batch_size = image.shape[0]475            if batch_size != image_batch_size:476                raise ValueError(477                    f"`prompt` has batch size {batch_size} and `image` has batch size {image_batch_size}."478                    " Please make sure that passed `prompt` matches the batch size of `image`."479                )480 481        # check noise level482        if noise_level > self.config.max_noise_level:483            raise ValueError(f"`noise_level` has to be <= {self.config.max_noise_level} but is {noise_level}")484 485        if (callback_steps is None) or (486            callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)487        ):488            raise ValueError(489                f"`callback_steps` has to be a positive integer but is {callback_steps} of type"490                f" {type(callback_steps)}."491            )492 493    def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):494        shape = (batch_size, num_channels_latents, height, width)495        if latents is None:496            latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)497        else:498            if latents.shape != shape:499                raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")500            latents = latents.to(device)501 502        # scale the initial noise by the standard deviation required by the scheduler503        latents = latents * self.scheduler.init_noise_sigma504        return latents505 506    # def upcast_vae(self):507    #     dtype = self.vae.dtype508    #     self.vae.to(dtype=torch.float32)509    #     use_torch_2_0_or_xformers = isinstance(510    #         self.vae.decoder.mid_block.attentions[0].processor,511    #         (512    #             AttnProcessor2_0,513    #             XFormersAttnProcessor,514    #             LoRAXFormersAttnProcessor,515    #             LoRAAttnProcessor2_0,516    #         ),517    #     )518    #     # if xformers or torch_2_0 is used attention block does not need519    #     # to be in float32 which can save lots of memory520    #     if use_torch_2_0_or_xformers:521    #         self.vae.post_quant_conv.to(dtype)522    #         self.vae.decoder.conv_in.to(dtype)523    #         self.vae.decoder.mid_block.to(dtype)524 525    @torch.no_grad()526    def __call__(527        self,528        prompt: Union[str, List[str]] = None,529        rgb: PipelineImageInput = None,530        depth: PipelineDepthInput = None,531        num_inference_steps: int = 75,532        guidance_scale: float = 9.0,533        noise_level: int = 20,534        negative_prompt: Optional[Union[str, List[str]]] = None,535        num_images_per_prompt: Optional[int] = 1,536        eta: float = 0.0,537        generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,538        latents: Optional[torch.Tensor] = None,539        prompt_embeds: Optional[torch.Tensor] = None,540        negative_prompt_embeds: Optional[torch.Tensor] = None,541        output_type: Optional[str] = "pil",542        return_dict: bool = True,543        callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,544        callback_steps: int = 1,545        cross_attention_kwargs: Optional[Dict[str, Any]] = None,546        target_res: Optional[List[int]] = [1024, 1024],547    ):548        r"""549        The call function to the pipeline for generation.550 551        Args:552            prompt (`str` or `List[str]`, *optional*):553                The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.554            image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):555                `Image` or tensor representing an image batch to be upscaled.556            num_inference_steps (`int`, *optional*, defaults to 50):557                The number of denoising steps. More denoising steps usually lead to a higher quality image at the558                expense of slower inference.559            guidance_scale (`float`, *optional*, defaults to 5.0):560                A higher guidance scale value encourages the model to generate images closely linked to the text561                `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.562            negative_prompt (`str` or `List[str]`, *optional*):563                The prompt or prompts to guide what to not include in image generation. If not defined, you need to564                pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).565            num_images_per_prompt (`int`, *optional*, defaults to 1):566                The number of images to generate per prompt.567            eta (`float`, *optional*, defaults to 0.0):568                Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies569                to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.570            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):571                A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make572                generation deterministic.573            latents (`torch.Tensor`, *optional*):574                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image575                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents576                tensor is generated by sampling using the supplied random `generator`.577            prompt_embeds (`torch.Tensor`, *optional*):578                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not579                provided, text embeddings are generated from the `prompt` input argument.580            negative_prompt_embeds (`torch.Tensor`, *optional*):581                Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If582                not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.583            output_type (`str`, *optional*, defaults to `"pil"`):584                The output format of the generated image. Choose between `PIL.Image` or `np.array`.585            return_dict (`bool`, *optional*, defaults to `True`):586                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a587                plain tuple.588            callback (`Callable`, *optional*):589                A function that calls every `callback_steps` steps during inference. The function is called with the590                following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.591            callback_steps (`int`, *optional*, defaults to 1):592                The frequency at which the `callback` function is called. If not specified, the callback is called at593                every step.594            cross_attention_kwargs (`dict`, *optional*):595                A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in596                [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).597 598        Examples:599 600        Returns:601            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:602                If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,603                otherwise a `tuple` is returned where the first element is a list with the generated images and the604                second element is a list of `bool`s indicating whether the corresponding generated image contains605                "not-safe-for-work" (nsfw) content.606        """607        # 1. Check inputs. Raise error if not correct608        self.check_inputs(609            prompt,610            rgb,611            noise_level,612            callback_steps,613            negative_prompt,614            prompt_embeds,615            negative_prompt_embeds,616        )617        # 2. Define call parameters618        if prompt is not None and isinstance(prompt, str):619            batch_size = 1620        elif prompt is not None and isinstance(prompt, list):621            batch_size = len(prompt)622        else:623            batch_size = prompt_embeds.shape[0]624 625        device = self._execution_device626        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)627        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`628        # corresponds to doing no classifier free guidance.629        do_classifier_free_guidance = guidance_scale > 1.0630 631        # 3. Encode input prompt632        prompt_embeds, negative_prompt_embeds = self.encode_prompt(633            prompt,634            device,635            num_images_per_prompt,636            do_classifier_free_guidance,637            negative_prompt,638            prompt_embeds=prompt_embeds,639            negative_prompt_embeds=negative_prompt_embeds,640        )641        # For classifier free guidance, we need to do two forward passes.642        # Here we concatenate the unconditional and text embeddings into a single batch643        # to avoid doing two forward passes644        if do_classifier_free_guidance:645            prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])646 647        # 4. Preprocess image648        rgb, depth = self.image_processor.preprocess(rgb, depth, target_res=target_res)649        rgb = rgb.to(dtype=prompt_embeds.dtype, device=device)650        depth = depth.to(dtype=prompt_embeds.dtype, device=device)651 652        # 5. set timesteps653        self.scheduler.set_timesteps(num_inference_steps, device=device)654        timesteps = self.scheduler.timesteps655 656        # 6. Encode low resolutiom image to latent space657        image = torch.cat([rgb, depth], axis=1)658        latent_space_image = self.vae.encode(image).latent_dist.sample(generator)659        latent_space_image *= self.vae.scaling_factor660        noise_level = torch.tensor([noise_level], dtype=torch.long, device=device)661        # noise_rgb = randn_tensor(rgb.shape, generator=generator, device=device, dtype=prompt_embeds.dtype)662        # rgb = self.low_res_scheduler.add_noise(rgb, noise_rgb, noise_level)663        # noise_depth = randn_tensor(depth.shape, generator=generator, device=device, dtype=prompt_embeds.dtype)664        # depth = self.low_res_scheduler.add_noise(depth, noise_depth, noise_level)665 666        batch_multiplier = 2 if do_classifier_free_guidance else 1667        latent_space_image = torch.cat([latent_space_image] * batch_multiplier * num_images_per_prompt)668        noise_level = torch.cat([noise_level] * latent_space_image.shape[0])669 670        # 7. Prepare latent variables671        height, width = latent_space_image.shape[2:]672        num_channels_latents = self.vae.config.latent_channels673 674        latents = self.prepare_latents(675            batch_size * num_images_per_prompt,676            num_channels_latents,677            height,678            width,679            prompt_embeds.dtype,680            device,681            generator,682            latents,683        )684 685        # 8. Check that sizes of image and latents match686        num_channels_image = latent_space_image.shape[1]687        if num_channels_latents + num_channels_image != self.unet.config.in_channels:688            raise ValueError(689                f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"690                f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"691                f" `num_channels_image`: {num_channels_image} "692                f" = {num_channels_latents+num_channels_image}. Please verify the config of"693                " `pipeline.unet` or your `image` input."694            )695 696        # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline697        extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)698 699        # 10. Denoising loop700        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order701        with self.progress_bar(total=num_inference_steps) as progress_bar:702            for i, t in enumerate(timesteps):703                # expand the latents if we are doing classifier free guidance704                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents705 706                # concat latents, mask, masked_image_latents in the channel dimension707                latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)708                latent_model_input = torch.cat([latent_model_input, latent_space_image], dim=1)709 710                # predict the noise residual711                noise_pred = self.unet(712                    latent_model_input,713                    t,714                    encoder_hidden_states=prompt_embeds,715                    cross_attention_kwargs=cross_attention_kwargs,716                    class_labels=noise_level,717                    return_dict=False,718                )[0]719 720                # perform guidance721                if do_classifier_free_guidance:722                    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)723                    noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)724 725                # compute the previous noisy sample x_t -> x_t-1726                latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]727 728                # call the callback, if provided729                if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):730                    progress_bar.update()731                    if callback is not None and i % callback_steps == 0:732                        callback(i, t, latents)733 734        if not output_type == "latent":735            # make sure the VAE is in float32 mode, as it overflows in float16736            needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast737 738            if needs_upcasting:739                self.upcast_vae()740                latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)741 742            image = self.vae.decode(latents / self.vae.scaling_factor, return_dict=False)[0]743 744            # cast back to fp16 if needed745            if needs_upcasting:746                self.vae.to(dtype=torch.float16)747 748            image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)749 750        else:751            image = latents752            has_nsfw_concept = None753 754        if has_nsfw_concept is None:755            do_denormalize = [True] * image.shape[0]756        else:757            do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]758 759        rgb, depth = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)760 761        # 11. Apply watermark762        if output_type == "pil" and self.watermarker is not None:763            rgb = self.watermarker.apply_watermark(rgb)764 765        # Offload last model to CPU766        if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:767            self.final_offload_hook.offload()768 769        if not return_dict:770            return ((rgb, depth), has_nsfw_concept)771 772        return LDM3DPipelineOutput(rgb=rgb, depth=depth, nsfw_content_detected=has_nsfw_concept)773