
    bi                       d dl Z d dlmZmZmZmZmZmZmZ d dl	Z
d dlZd dlZd dlmc mZ d dlmZmZmZmZ ddlmZmZ ddlmZmZ ddlmZmZm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z' dd	l(m)Z) dd
l*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z; ddl<m=Z= ddl>m?Z?  e/       rd dl@mAc mBZC dZDndZD e0j                  eF      ZGdZH	 	 	 	 ddeeI   deeeJej                  f      deeeI      deeeL      fdZM G d de:e;e!e ee      ZNy)    N)AnyCallableDictListOptionalTupleUnion)CLIPImageProcessorCLIPTextModelCLIPTokenizerCLIPVisionModelWithProjection   )MultiPipelineCallbacksPipelineCallback)PipelineImageInputVaeImageProcessor)FromSingleFileMixinIPAdapterMixinStableDiffusionLoraLoaderMixinTextualInversionLoaderMixin)AutoencoderKLControlNetModelImageProjectionMultiControlNetModelUNet2DConditionModel)adjust_lora_scale_text_encoder)KarrasDiffusionSchedulers)USE_PEFT_BACKEND	deprecateis_torch_xla_availableloggingreplace_example_docstringscale_lora_layersunscale_lora_layers)empty_device_cacheis_compiled_moduleis_torch_versionrandn_tensor   )DiffusionPipelineStableDiffusionMixin)StableDiffusionPipelineOutput)StableDiffusionSafetyCheckerTFa  
    Examples:
        ```py
        >>> # !pip install opencv-python transformers accelerate
        >>> from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler
        >>> from diffusers.utils import load_image
        >>> import numpy as np
        >>> import torch

        >>> import cv2
        >>> from PIL import Image

        >>> # download an image
        >>> image = load_image(
        ...     "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
        ... )
        >>> image = np.array(image)

        >>> # get canny image
        >>> image = cv2.Canny(image, 100, 200)
        >>> image = image[:, :, None]
        >>> image = np.concatenate([image, image, image], axis=2)
        >>> canny_image = Image.fromarray(image)

        >>> # load control net and stable diffusion v1-5
        >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
        >>> pipe = StableDiffusionControlNetPipeline.from_pretrained(
        ...     "stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
        ... )

        >>> # speed up diffusion process with faster scheduler and memory optimization
        >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
        >>> # remove following line if xformers is not installed
        >>> pipe.enable_xformers_memory_efficient_attention()

        >>> pipe.enable_model_cpu_offload()

        >>> # generate image
        >>> generator = torch.manual_seed(0)
        >>> image = pipe(
        ...     "futuristic-looking woman", num_inference_steps=20, generator=generator, image=canny_image
        ... ).images[0]
        ```
num_inference_stepsdevice	timestepssigmasc                    ||t        d      |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS  | j                  |fd	|i| | j                  }||fS )a  
    Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
    custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

    Args:
        scheduler (`SchedulerMixin`):
            The scheduler to get timesteps from.
        num_inference_steps (`int`):
            The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
            must be `None`.
        device (`str` or `torch.device`, *optional*):
            The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
        timesteps (`List[int]`, *optional*):
            Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
            `num_inference_steps` and `sigmas` must be `None`.
        sigmas (`List[float]`, *optional*):
            Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
            `num_inference_steps` and `timesteps` must be `None`.

    Returns:
        `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
        second element is the number of inference steps.
    zYOnly one of `timesteps` or `sigmas` can be passed. Please choose one to set custom valuesr0   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r0   r/   r1   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r1   r/   r/    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r0   len)	schedulerr.   r/   r0   r1   kwargsaccepts_timestepsaccept_sigmass           m/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/controlnet/pipeline_controlnet.pyretrieve_timestepsrB   g   s   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	 	M)FMfM''	!)n ))) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	 	GvfGG''	!)n ))) 	 	 3MFMfM''	)))    c            <           e Zd ZdZdZg dZdgZg dZ	 	 dMded	e	d
e
dedeeee   ee   ef   dededededef fdZ	 	 	 	 dNdeej2                     deej2                     dee   fdZ	 	 	 	 	 dOdeej2                     deej2                     dee   dee   fdZdPdZd Zd Z d Z!d Z"	 	 	 	 	 	 	 	 	 dQdZ#d  Z$	 	 dRd"Z%dPd#Z&d$ejN                  fd%ej2                  d&ed'ejP                  d(ej2                  fd)Z)e*d*        Z+e*d+        Z,e*d,        Z-e*d-        Z.e*d.        Z/e*d/        Z0 ejb                          e2e3      ddddd0ddd1dd2dddddddd3dddd!ddddd4gfd5ee4ee4   f   d6e5d7ee   d8ee   d9ed:ee   d;ee   d<ed=eee4ee4   f      d>ee   d?ed@eeejl                  eejl                     f      d4eej2                     deej2                     deej2                     dAee5   dBeeej2                        dCee4   dDedEee7e4e8f      dFeeee   f   dGedHeeee   f   dIeeee   f   dee   dJeee9eee7gdf   e:e;f      dKee4   f6dL              Z< xZ=S )S!StableDiffusionControlNetPipelinea	  
    Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a particular device, etc.).

    The pipeline also inherits the following loading methods:
        - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
        - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
        - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
        - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
        - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters

    Args:
        vae ([`AutoencoderKL`]):
            Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
        text_encoder ([`~transformers.CLIPTextModel`]):
            Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
        tokenizer ([`~transformers.CLIPTokenizer`]):
            A `CLIPTokenizer` to tokenize text.
        unet ([`UNet2DConditionModel`]):
            A `UNet2DConditionModel` to denoise the encoded image latents.
        controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
            Provides additional conditioning to the `unet` during the denoising process. If you set multiple
            ControlNets as a list, the outputs from each ControlNet are added together to create one combined
            additional conditioning.
        scheduler ([`SchedulerMixin`]):
            A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
            [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
        safety_checker ([`StableDiffusionSafetyChecker`]):
            Classification module that estimates whether generated images could be considered offensive or harmful.
            Please refer to the [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) for
            more details about a model's potential harms.
        feature_extractor ([`~transformers.CLIPImageProcessor`]):
            A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
    z&text_encoder->image_encoder->unet->vae)safety_checkerfeature_extractorimage_encoderrF   )latentsprompt_embedsnegative_prompt_embedsimageNTvaetext_encoder	tokenizerunet
controlnetr=   rG   rH   requires_safety_checkerc                     t         |           |%|
r#t        j                  d| j                   d       ||t        d      t        |t        t        f      rt        |      }| j                  |||||||||		       t        | dd       r/dt        | j                  j                  j                        dz
  z  nd| _        t#        | j                   d	
      | _        t#        | j                   d	d      | _        | j)                  |
       y )Nz)You have disabled the safety checker for a   by passing `safety_checker=None`. Ensure that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered results in services or applications open to the public. Both the diffusers team and Hugging Face strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling it only for use-cases that involve analyzing network behavior or auditing its results. For more information, please have a look at https://github.com/huggingface/diffusers/pull/254 .zMake sure to define a feature extractor when loading {self.__class__} if you want to use the safety checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead.)	rM   rN   rO   rP   rQ   r=   rF   rG   rH   rM   r)         T)vae_scale_factordo_convert_rgbF)rV   rW   do_normalize)rR   )super__init__loggerwarningr;   r4   
isinstancelisttupler   register_modulesgetattrr<   rM   configblock_out_channelsrV   r   image_processorcontrol_image_processorregister_to_config)selfrM   rN   rO   rP   rQ   r=   rF   rG   rH   rR   r;   s              rA   rZ   z*StableDiffusionControlNetPipeline.__init__   s'    	!&=NN;DNN;K Lj j %*;*Cx 
 j4-0-j9J%!)/' 	 
	
 W^^bdikoVpc$((//*L*L&MPQ&Q Rvw0$BWBWhlm'8!224V[(
$ 	8OPrC   rJ   rK   
lora_scalec	                     d}
t        dd|
d        | j                  d	||||||||d|	}t        j                  |d   |d   g      }|S )
Nz`_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.z_encode_prompt()1.0.0Fstandard_warn)promptr/   num_images_per_promptdo_classifier_free_guidancenegative_promptrJ   rK   rh   rT   r   r3   )r   encode_prompttorchcat)rg   rm   r/   rn   ro   rp   rJ   rK   rh   r>   deprecation_messageprompt_embeds_tuples               rA   _encode_promptz0StableDiffusionControlNetPipeline._encode_prompt	  s}     a$g/BRWX0d00 

"7(C+'#9!

 

 		#6q#9;Nq;Q"RSrC   	clip_skipc
                 H
   |Jt        | t              r:|| _        t        st	        | j
                  |       nt        | j
                  |       |t        |t              rd}
n-|t        |t              rt        |      }
n|j                  d   }
|t        | t              r| j                  || j                        }| j                  |d| j                  j                  dd      }|j                  }| j                  |dd	      j                  }|j                  d
   |j                  d
   k\  rt!        j"                  ||      sj| j                  j%                  |dd| j                  j                  dz
  d
f         }t&        j)                  d| j                  j                   d|        t+        | j
                  j,                  d      r<| j
                  j,                  j.                  r|j0                  j3                  |      }nd}|	(| j                  |j3                  |      |      }|d   }nT| j                  |j3                  |      |d      }|d
   |	dz       }| j
                  j4                  j7                  |      }| j
                  | j
                  j8                  }n/| j:                  | j:                  j8                  }n|j8                  }|j3                  ||      }|j                  \  }}}|j=                  d|d      }|j?                  ||z  |d
      }|rm|j|dg|
z  }n|:tA        |      tA        |      ur$tC        dtA        |       dtA        |       d      t        |t              r|g}n1|
t        |      k7  r!tE        d| dt        |       d| d|
 d	      |}t        | t              r| j                  || j                        }|j                  d   }| j                  |d|dd      }t+        | j
                  j,                  d      r<| j
                  j,                  j.                  r|j0                  j3                  |      }nd}| j                  |j                  j3                  |      |      }|d   }|rK|j                  d   }|j3                  ||      }|j=                  d|d      }|j?                  |
|z  |d
      }| j
                  ,t        | t              rt        rtG        | j
                  |       ||fS )a  
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            device: (`torch.device`):
                torch device
            num_images_per_prompt (`int`):
                number of images that should be generated per prompt
            do_classifier_free_guidance (`bool`):
                whether to use classifier free guidance or not
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            lora_scale (`float`, *optional*):
                A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
            clip_skip (`int`, *optional*):
                Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
                the output of the pre-final layer will be used for computing the prompt embeddings.
        NrT   r   
max_lengthTpt)paddingry   
truncationreturn_tensorslongest)r{   r}   z\The following part of your input was truncated because CLIP can only handle sequences up to z	 tokens: use_attention_mask)attention_mask)r   output_hidden_states)dtyper/    z?`negative_prompt` should be the same type to `prompt`, but got z != .z`negative_prompt`: z has batch size z, but `prompt`: zT. Please make sure that passed `negative_prompt` matches the batch size of `prompt`.)$r]   r   _lora_scaler   r   rN   r#   strr^   r<   shaper   maybe_convert_promptrO   model_max_length	input_idsrr   equalbatch_decoder[   r\   hasattrrb   r   r   to
text_modelfinal_layer_normr   rP   repeatviewtype	TypeErrorr4   r$   )rg   rm   r/   rn   ro   rp   rJ   rK   rh   rw   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textr   prompt_embeds_dtypebs_embedseq_len_uncond_tokensry   uncond_inputs                          rA   rq   z/StableDiffusionControlNetPipeline.encode_prompt*  s6   V !j7U&V)D $.t/@/@*M!$"3"3Z@*VS"9JJvt$<VJ&,,Q/J $ ;<2264>>J..$>>::# ) K )22N"nnVYW[n\ffO$$R(N,@,@,DDU[[N  $~~::#At~~'F'F'JR'O$OP  778	,Q
 t((//1EF4K\K\KcKcKvKv!,!;!;!>!>v!F!%  $ 1 1.2C2CF2K\j 1 k -a 0 $ 1 1"%%f-ncg !2 ! !.b 1IM2B C
 !% 1 1 < < M Mm \("&"3"3"9"9YY""&))//"/"5"5%((/B6(R,22'1%,,Q0EqI%**86K+KWVXY '+A+I&!#z 1#VD<Q(QUVZ[jVkUl mV~Q(  OS1!0 1s?33 )/)::J3K_J` ax/
| <33  !0 $ ;< $ 9 9- X&,,Q/J>>$%# * L t((//1EF4K\K\KcKcKvKv!-!<!<!?!?!G!%%)%6%6&&))&1- &7 &" &<A%>"&,2215G%;%>%>EXag%>%h"%;%B%B1F[]^%_"%;%@%@NcAcelnp%q"($ >?DT#D$5$5zB444rC   c                 |   t        | j                  j                               j                  }t	        |t
        j                        s| j                  |d      j                  }|j                  ||      }|r}| j                  |d      j                  d   }|j                  |d      }| j                  t        j                  |      d      j                  d   }|j                  |d      }||fS | j                  |      j                  }|j                  |d      }t        j                  |      }	||	fS )	Nrz   r}   r/   r   T)r   r   dim)nextrH   r9   r   r]   rr   TensorrG   pixel_valuesr   hidden_statesrepeat_interleave
zeros_likeimage_embeds)
rg   rL   r/   rn   r   r   image_enc_hidden_statesuncond_image_enc_hidden_statesr   uncond_image_embedss
             rA   encode_imagez.StableDiffusionControlNetPipeline.encode_image  sD   T''2245;;%.**5*FSSEe4&*&8&8UY&8&Z&h&hik&l#&=&O&OPekl&O&m#-1-?-?  'd .@ .mB. * .L-]-]%1 .^ .* +,JJJ--e4AAL'99:OUV9WL"'"2"2<"@!444rC   c                    g }|rg }|t        |t              s|g}t        |      t        | j                  j                  j
                        k7  rBt        dt        |       dt        | j                  j                  j
                         d      t        || j                  j                  j
                        D ]`  \  }}	t        |	t               }
| j                  ||d|
      \  }}|j                  |d d d f          |sIj                  |d d d f          b n?|D ]:  }|r%|j                  d      \  }}j                  |       |j                  |       < g }t        |      D ]|  \  }}t        j                  |g|z  d      }|r7t        j                  |   g|z  d      }t        j                  ||gd      }|j                  |      }|j                  |       ~ |S )	NzK`ip_adapter_image` must have same length as the number of IP Adapters. Got  images and z IP Adapters.rT   r)   r   r   )r/   )r]   r^   r<   rP   encoder_hid_projimage_projection_layersr4   zipr   r   appendchunk	enumeraterr   rs   r   )rg   ip_adapter_imageip_adapter_image_embedsr/   rn   ro   r   negative_image_embedssingle_ip_adapter_imageimage_proj_layeroutput_hidden_statesingle_image_embedssingle_negative_image_embedsis                 rA   prepare_ip_adapter_image_embedszAStableDiffusionControlNetPipeline.prepare_ip_adapter_image_embeds  sY    &$&!"*.5$4#5 #$DII,F,F,^,^(__ abefvbwax  yE  FI  JN  JS  JS  Jd  Jd  J|  J|  F}  E~  ~K  L  >A $))"<"<"T"T> 
X9')9 +55E*W&W#DHDUDU+VQ8KEA#%A ##$7a$@A.)001MdTUg1VW
X (? 9#.H[HaHabcHdE02E)001MN##$78	9 #%&/&= 	@"A""'))-@,ADY,Y_`"a*/4yy:OPQ:R9SVk9kqr/s,&+ii1MOb0cij&k#"5"8"8"8"G#**+>?	@ '&rC   c                 l   | j                   d }||fS t        j                  |      r| j                  j	                  |d      }n| j                  j                  |      }| j                  |d      j                  |      }| j                  ||j                  j                  |            \  }}||fS )Npil)output_typerz   r   )images
clip_input)	rF   rr   	is_tensorrd   postprocessnumpy_to_pilrG   r   r   )rg   rL   r/   r   has_nsfw_conceptfeature_extractor_inputsafety_checker_inputs          rA   run_safety_checkerz4StableDiffusionControlNetPipeline.run_safety_checker(  s    &# &&& u%*.*>*>*J*J5^c*J*d'*.*>*>*K*KE*R'#'#9#9:Qbf#9#g#j#jkq#r &*&9&9)=)J)J)M)Me)T ': '#E# &&&rC   c                 `   d}t        dd|d       d| j                  j                  j                  z  |z  }| j                  j	                  |d      d   }|d	z  d
z   j                  dd      }|j                         j                  dd	dd      j                         j                         }|S )Nz{The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) insteaddecode_latentsrj   Frk   rT   )return_dictr   r)   g      ?r   )
r   rM   rb   scaling_factordecodeclampcpupermutefloatnumpy)rg   rI   rt   rL   s       rA   r   z0StableDiffusionControlNetPipeline.decode_latents7  s     \"G-@PUVdhhoo444w>U;A>S''1-		##Aq!Q/557==?rC   c                 V   dt        t        j                  | j                  j                        j
                  j                               v }i }|r||d<   dt        t        j                  | j                  j                        j
                  j                               v }|r||d<   |S )Neta	generator)r5   r6   r7   r=   stepr9   r:   )rg   r   r   accepts_etaextra_step_kwargsaccepts_generators         rA   prepare_extra_step_kwargsz;StableDiffusionControlNetPipeline.prepare_extra_step_kwargsC  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  rC         ?        c                     |0t        |t              r|dk  rt        d| dt        |       d      |Lt	         fd|D              s8t        d j
                   d|D cg c]  }| j
                  vs| c}       ||t        d| d	| d
      ||t        d      |7t        |t              s't        |t              st        dt        |             ||t        d| d| d
      |A|?|j                  |j                  k7  r&t        d|j                   d|j                   d      t        t        d      xr8 t         j                  t        j                  j                  j                        }t         j                  t               s&|r9t         j                  j"                  t               r j%                  |||       nt         j                  t&              s(|rlt         j                  j"                  t&              rGt        |t              st)        d      t+        d |D              rt-        | D cg c]  }t        |       }}t/        |      t/         j                  j0                        k7  r8t        dt/        |       dt/         j                  j0                         d      |D ]  } j%                  |||        nt/        |      t/         j                  j0                        k7  r8t        dt/        |       dt/         j                  j0                         d      |D ]  } j%                  |||        nJ t         j                  t               s&|r?t         j                  j"                  t               rt        |	t2              st)        d      t         j                  t&              s&|rt         j                  j"                  t&              rst        |	t              rt+        d |	D              rSt        d      t        |	t              r8t/        |	      t/         j                  j0                        k7  rt        d      J t        |
t4        t        f      s|
g}
t        |t4        t        f      s|g}t/        |
      t/        |      k7  r$t        dt/        |
       dt/        |       d      t         j                  t&              rt/        |
      t/         j                  j0                        k7  r[t        d|
 d t/        |
       d!t/         j                  j0                         d"t/         j                  j0                         d	      t-        |
|      D ]D  \  }}||k\  rt        d#| d$| d      |d%k  rt        d#| d&      |d'kD  s7t        d(| d)       ||t        d*      |Ut        |t              st        d+t        |             |d   j6                  d,vrt        d-|d   j6                   d.      y y c c}w c c}w )/Nr   z5`callback_steps` has to be a positive integer but is z	 of type r   c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0krg   s     rA   	<genexpr>zAStableDiffusionControlNetPipeline.check_inputs.<locals>.<genexpr>i  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` scaled_dot_product_attentionz5For multiple controlnets: `image` must be type `list`c              3   <   K   | ]  }t        |t                y wr   r]   r^   r   r   s     rA   r   zAStableDiffusionControlNetPipeline.check_inputs.<locals>.<genexpr>  s     8QZ4(8   zFor multiple controlnets: if you pass`image` as a list of list, each sublist must have the same length as the number of controlnets, but the sublists in `image` got r   z ControlNets.zbFor multiple controlnets: `image` must have the same length as the number of controlnets, but got zLFor single controlnet: `controlnet_conditioning_scale` must be type `float`.c              3   <   K   | ]  }t        |t                y wr   r   r   s     rA   r   zAStableDiffusionControlNetPipeline.check_inputs.<locals>.<genexpr>  s     Rqz!T*Rr   zA single batch of varying conditioning scale settings (e.g. [[1.0, 0.5], [0.2, 0.8]]) is not supported at the moment. The conditioning scale must be fixed across the batch.zFor multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have the same length as the number of controlnetsz`control_guidance_start` has z* elements, but `control_guidance_end` has zI elements. Make sure to provide the same number of elements to each list.z`control_guidance_start`: z has z elements but there are z- controlnets available. Make sure to provide zcontrol guidance start: z4 cannot be larger or equal to control guidance end: r   z can't be smaller than 0.r   zcontrol guidance end: z can't be larger than 1.0.zProvide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined.z:`ip_adapter_image_embeds` has to be of type `list` but is )r      zF`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is D)r]   intr4   r   allr   r   r^   r   r   FrQ   rr   _dynamo
eval_frameOptimizedModuler   	_orig_modcheck_imager   r   anyr   r<   netsr   r_   ndim)rg   rm   rL   callback_stepsrp   rJ   rK   r   r   controlnet_conditioning_scalecontrol_guidance_startcontrol_guidance_end"callback_on_step_end_tensor_inputsr   is_compiledttransposed_imageimage_startends   `                   rA   check_inputsz.StableDiffusionControlNetPipeline.check_inputsT  s    %z.#/NR`deReGGW X(), 
 .9# F
7YF
 C
 DTEaEaDbbn  |^  pHvw  bc  ko  kG  kG  bGpq  pH  oI  J  -";08N}o ^0 0  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa&+A+M9/9J K*++]_ 
 $)?)K""&<&B&BB --:-@-@,A B.445Q8  a!?@ 
ZOOU]]55EEF
 t84??44oFUFM:t(<=4??446JKeT* WXX 8%8858%[#ADG#A #A'(C0D0D,EE$ @  AD  EU  AV  @W  Wc  dg  hl  hw  hw  h|  h|  d}  c~  ~K  L  / DF$$VV]CDUs4??#7#788 xy|  ~C  zD  yE  EQ  RU  VZ  Ve  Ve  Vj  Vj  Rk  Ql  ly  z  $ DF$$VV]CD 5 t84??44oF;UC noot(<=4??446JK7>R4QRR$Q  94@SIfEgkn$$l F !D 
 505$-@&<%=".>$8#9 %&#.B*CC/4J0K/LLvwz  |P  xQ  wR  R[  \  doo';<)*c$//2F2F.GG 01G0HcRhNiMj  kC  DG  HL  HW  HW  H\  H\  D]  C^  ^K  LO  PT  P_  P_  Pd  Pd  Le  Kf  fg  h  46JK 	[JE3| .ug5ijminnop  s{ #;E7B[!\]]Sy #9#>X!YZZ	[ ',C,O ^  #.5t< PQUVmQnPop  )+00> \]tuv]w]|]|\}}~  ? /A pHd $Bs   !X:5X:X?c                    t        |t        j                  j                        }t        |t        j                        }t        |t
        j                        }t        |t              xr' t        |d   t        j                  j                        }t        |t              xr t        |d   t        j                        }t        |t              xr t        |d   t
        j                        }	|s!|s|s|s|s|	st        dt        |             |rd}
nt        |      }
|t        |t              rd}n/|t        |t              rt        |      }n||j                  d   }|
dk7  r|
k7  rt        d|
 d|       y y )Nr   zimage must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is rT   zdIf image batch size is not 1, image batch size must be same as prompt batch size. image batch size: z, prompt batch size: )r]   PILImagerr   r   npndarrayr^   r   r   r<   r   r   r4   )rg   rL   rm   rJ   image_is_pilimage_is_tensorimage_is_npimage_is_pil_listimage_is_tensor_listimage_is_np_listimage_batch_sizeprompt_batch_sizes               rA   r   z-StableDiffusionControlNetPipeline.check_image  s   !%9$UELL9 

3&ud3]
58SYY__8])%6]:eAhPUP\P\;]%eT2Wz%(BJJ7W #%($ f  gk  lq  gr  fs  t   "5z*VS"9 !Jvt$< #F& - 3 3A 6q %59J%Jv  xH  wI  I^  _p  ^q  r  &K rC   Fc
                 6   | j                   j                  |||      j                  t        j                        }|j
                  d   }
|
dk(  r|}n|}|j                  |d      }|j                  ||      }|r|	st        j                  |gdz        }|S )N)heightwidthr   r   rT   r   r   r)   )re   
preprocessr   rr   float32r   r   rs   )rg   rL   r  r  r   rn   r/   r   ro   
guess_moder  	repeat_bys               rA   prepare_imagez/StableDiffusionControlNetPipeline.prepare_image  s     ,,77fTY7Z]]didqdq]r ;;q>q "I .I''	q'9e4&zIIugk*ErC   c	                 T   ||t        |      | j                  z  t        |      | j                  z  f}	t        |t              r)t	        |      |k7  rt        dt	        |       d| d      |t        |	|||      }n|j                  |      }|| j                  j                  z  }|S )Nz/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.)r   r/   r   )
r   rV   r]   r^   r<   r4   r(   r   r=   init_noise_sigma)
rg   r   num_channels_latentsr  r  r   r/   r   rI   r   s
             rA   prepare_latentsz1StableDiffusionControlNetPipeline.prepare_latents;  s     K4000J$///	
 i&3y>Z+GA#i.AQ R&<'gi 
 ?"5IfTYZGjj(G DNN;;;rC   i   wembedding_dimr   returnc                 l   t        |j                        dk(  sJ |dz  }|dz  }t        j                  t        j                  d            |dz
  z  }t        j
                  t        j                  ||      | z        }|j                  |      dddf   |dddf   z  }t        j                  t        j                  |      t        j                  |      gd      }|dz  dk(  r*t        j                  j                  j                  |d      }|j                  |j                  d	   |fk(  sJ |S )
a  
        See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

        Args:
            w (`torch.Tensor`):
                Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
            embedding_dim (`int`, *optional*, defaults to 512):
                Dimension of the embeddings to generate.
            dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
                Data type of the generated embeddings.

        Returns:
            `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
        rT   g     @@r)   g     @r  Nr   )r   rT   r   )r<   r   rr   logtensorexparanger   rs   sincosnn
functionalpad)rg   r$  r%  r   half_dimembs         rA   get_guidance_scale_embeddingz>StableDiffusionControlNetPipeline.get_guidance_scale_embeddingR  s   " 177|q   J A%iiW-.(Q,?iiXU;sdBCdd5k!T'"Sq\1ii338a@1!((%%))#v6CyyQWWQZ7777
rC   c                     | j                   S r   )_guidance_scalerg   s    rA   guidance_scalez0StableDiffusionControlNetPipeline.guidance_scalep  s    ###rC   c                     | j                   S r   )
_clip_skipr6  s    rA   rw   z+StableDiffusionControlNetPipeline.clip_skipt      rC   c                 h    | j                   dkD  xr" | j                  j                  j                  d u S )NrT   )r5  rP   rb   time_cond_proj_dimr6  s    rA   ro   z=StableDiffusionControlNetPipeline.do_classifier_free_guidance{  s.    ##a'WDII,<,<,O,OSW,WWrC   c                     | j                   S r   )_cross_attention_kwargsr6  s    rA   cross_attention_kwargsz8StableDiffusionControlNetPipeline.cross_attention_kwargs  s    +++rC   c                     | j                   S r   )_num_timestepsr6  s    rA   num_timestepsz/StableDiffusionControlNetPipeline.num_timesteps  s    """rC   c                     | j                   S r   )
_interruptr6  s    rA   	interruptz+StableDiffusionControlNetPipeline.interrupt  r:  rC   2   g      @rT   r   rI   rm   rL   r  r  r.   r0   r1   r7  rp   rn   r   r   r   r   r   r   r?  r   r  r   r  callback_on_step_endr  c                 j   |j                  dd      }|j                  dd      }|t        ddd       |t        ddd       t        |t        t        f      r|j
                  }t        | j                        r| j                  j                  n| j                  }t        |t              s t        |t              rt        |      |gz  }nt        |t              s t        |t              rt        |      |gz  }nSt        |t              sCt        |t              s3t        |t              rt        |j                        nd} | |gz  | |gz  }}| j                  ||||	||||||||       || _        || _        || _        d| _        |t        |t$              rd}!n-|t        |t              rt        |      }!n|j&                  d	   }!| j(                  }"t        |t              r)t        |t*              r|gt        |j                        z  }t        |t,              r|j.                  j0                  n"|j                  d	   j.                  j0                  }#|xs |#}| j2                  | j2                  j5                  d
d      nd}$| j7                  ||"|
| j8                  |	|||$| j:                  	      \  }}| j8                  rt=        j>                  ||g      }||"| jA                  |||"|!|
z  | j8                        }%t        |t,              rD| jC                  ||||!|
z  |
|"|jD                  | j8                  |	      }|j&                  dd \  }}nt        |t              rg }&t        |d	   t              rtG        | D 'cg c]  }'t        |'       }}'|D ]D  }(| jC                  |(|||!|
z  |
|"|jD                  | j8                  |	      }(|&jI                  |(       F |&}|d	   j&                  dd \  }}nJ tK        | jL                  ||"||      \  }}t        |      | _'        | jP                  j.                  jR                  })| jU                  |!|
z  |)|||jD                  |"||      }d}*| jP                  j.                  jV                  t=        jX                  | jZ                  dz
        j]                  |!|
z        }+| j_                  |+| jP                  j.                  jV                        ja                  |"|jD                        }*| jc                  ||      },||d%ind}-g }.te        t        |            D ]w  }/tG        ||      D 01cg c]8  \  }0}1dt+        |/t        |      z  |0k  xs |/dz   t        |      z  |1kD        z
  : }2}0}1|.jI                  t        |t,              r|2d	   n|2       y t        |      || jL                  jf                  z  z
  }3t        | jP                        }4t        | j                        }5ti        dd      }6| jk                  |      5 }7tm        |      D ]"  \  }/}'| jn                  r|4r"|5r |6rt<        jp                  js                          | j8                  rt=        j>                  |gdz        n|}8| jL                  ju                  |8|'      }8|r?| j8                  r3|}9| jL                  ju                  |9|'      }9|jw                  d      d   }:n|8}9|}:t        |.|/   t              r%tG        ||.|/         D ;0cg c]
  \  };}0|;|0z   }<};}0n|}=t        |=t              r|=d	   }=|=|.|/   z  }<| j                  |9|'|:||<|d      \  }>}?|rm| j8                  ra|>D @cg c],  }@t=        j>                  t=        jx                  |@      |@g      . }>}@t=        j>                  t=        jx                  |?      |?g      }?| jQ                  |8|'||*| j2                  |>|?|-d	      d	   }A| j8                  r)Ajw                  d      \  }B}C|B| jZ                  |C|Bz
  z  z   }A | jL                  jz                  A|'|fi |,ddid	   }|li }D|D ]  }Et}               |E   D|E<     || |/|'D      }F|Fj                  d|      }|Fj                  d|      }|Fj                  d|      }|Fj                  d|      }|/t        |      dz
  k(  s'|/dz   |3kD  r]|/dz   | jL                  jf                  z  d	k(  r>|7j                          |,|/|z  d	k(  r$|/t        | jL                  dd      z  }G ||G|'|       t        st        j                          % 	 ddd       t        | d      rL| j                  @| jP                  ja                  d       | j                  ja                  d       t                |d k(  sc| j                  j                  || j                  j.                  j                  z  d|!      d	   }| j                  ||"|jD                        \  }}Hn|}d}HHd"g|j&                  d	   z  }InHD Jcg c]  }J|J  }I}J| j                  j                  ||I#      }| j                          |s|HfS t        |H$      S c c}'w c c}1}0w c c}0};w c c}@w # 1 sw Y   KxY wc c}Jw )%uO$  
        The call function to the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
            image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
                    `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
                The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
                specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
                as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
                width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
                images must be passed as a list such that each element of the list can be correctly batched for input
                to a single ControlNet. When `prompt` is a list, and if a list of images is passed for a single
                ControlNet, each will be paired with each prompt in the `prompt` list. This also applies to multiple
                ControlNets, where a list of image lists can be passed to batch for each prompt and each ControlNet.
            height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
                The height in pixels of the generated image.
            width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
                The width in pixels of the generated image.
            num_inference_steps (`int`, *optional*, defaults to 50):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            timesteps (`List[int]`, *optional*):
                Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
                in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
                passed will be used. Must be in descending order.
            sigmas (`List[float]`, *optional*):
                Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
                their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
                will be used.
            guidance_scale (`float`, *optional*, defaults to 7.5):
                A higher guidance scale value encourages the model to generate images closely linked to the text
                `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide what to not include in image generation. If not defined, you need to
                pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            eta (`float`, *optional*, defaults to 0.0):
                Corresponds to parameter eta (η) from the [DDIM](https://huggingface.co/papers/2010.02502) paper. Only
                applies to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
                generation deterministic.
            latents (`torch.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
                not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
            ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
            ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
                Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
                IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
                contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
                provided, embeddings are computed from the `ip_adapter_image` input argument.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
                plain tuple.
            callback (`Callable`, *optional*):
                A function that calls every `callback_steps` steps during inference. The function is called with the
                following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
            callback_steps (`int`, *optional*, defaults to 1):
                The frequency at which the `callback` function is called. If not specified, the callback is called at
                every step.
            cross_attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
                [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
                The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
                to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
                the corresponding scale as a list.
            guess_mode (`bool`, *optional*, defaults to `False`):
                The ControlNet encoder tries to recognize the content of the input image even if you remove all
                prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
            control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
                The percentage of total steps at which the ControlNet starts applying.
            control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
                The percentage of total steps at which the ControlNet stops applying.
            clip_skip (`int`, *optional*):
                Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
                the output of the pre-final layer will be used for computing the prompt embeddings.
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
                each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
                DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
                list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.

        Examples:

        Returns:
            [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
                otherwise a `tuple` is returned where the first element is a list with the generated images and the
                second element is a list of `bool`s indicating whether the corresponding generated image contains
                "not-safe-for-work" (nsfw) content.
        callbackNr   rj   zjPassing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`zpPassing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`rT   Fr   scale)rJ   rK   rh   rw   )	rL   r  r  r   rn   r/   r   ro   r  r   )r%  r   r   r   z>=z2.1)totalr)   )encoder_hidden_statescontrolnet_condconditioning_scaler  r   )rL  timestep_condr?  down_block_additional_residualsmid_block_additional_residualadded_cond_kwargsr   r   rI   rJ   rK   rL   orderfinal_offload_hookr   latent)r   r   T)r   do_denormalize)r   nsfw_content_detected)Opopr   r]   r   r   tensor_inputsr&   rQ   r   r^   r<   r   r   r	  r5  r9  r>  rD  r   r   _execution_devicer   r   rb   global_pool_conditionsr?  getrq   ro   rw   rr   rs   r   r  r   r   r   rB   r=   rA  rP   in_channelsr#  r<  r)  r7  r   r3  r   r   rangerS  r'   progress_barr   rE  	_inductorcudagraph_mark_step_beginscale_model_inputr   r   r   localsupdatera   XLA_AVAILABLExm	mark_stepr   rT  r%   rM   r   r   r   rd   r   maybe_free_model_hooksr,   )Krg   rm   rL   r  r  r.   r0   r1   r7  rp   rn   r   r   rI   rJ   rK   r   r   r   r   r?  r   r  r   r  rw   rG  r  r>   rI  r   rQ   multr   r/   r[  text_encoder_lora_scaler   r   r  r  r"  rO  guidance_scale_tensorr   rR  controlnet_keepr   sekeepsnum_warmup_stepsis_unet_compiledis_controlnet_compiledis_torch_higher_equal_2_1r_  latent_model_inputcontrol_model_inputcontrolnet_prompt_embedsc
cond_scalecontrolnet_cond_scaledown_block_res_samplesmid_block_res_sampled
noise_prednoise_pred_uncondnoise_pred_textcallback_kwargsr   callback_outputsstep_idxr   rV  has_nsfwsK                                                                              rA   __call__z*StableDiffusionControlNetPipeline.__call__  sJ   ` ::j$/$4d;|
 %  C *-=?U,VW1E1S1S.2DT__2UT__..[_[j[j
 0$7JG[]a<b%()=%>BXAY%Y"0$7JG]_c<d#&'=#>BVAW#W 2D9*MacgBh+5jBV+W3z']^D.//,-- %9" 	"#)" .	
  .#'=$ *VS"9JJvt$<VJ&,,Q/J''j"67JGdfk<l-J,KcR\RaRaNb,b) *o6 44#**AA 	
  9#9
 ?C>Y>Y>eD''++GT:ko 	  150B0B!,,'#9.nn 1C 
1
-- ++!II'=}&MNM'+B+N?? '2200L j/2&&%(==&; &&,0,L,L% ' 
E "KK,MFE
$89F %(D)*-u+6Qa66 &++ !),AA*?!$**040P0P) , 
 f%& E!!HNN23/MFE5 *<NN/F*
&	& ")n  $yy//;;&&.. 	
 99..:$)LL1D1Dq1H$I$P$PQ[^sQs$t! ==%TYY5E5E5X5X > bgmmb4 
 !::9cJ
  +/F/R \* 	 s9~& 	cA   68LMAq eAI.2Rq1uI6NQR6RSSE  ""z*o/V58\ab	c y>,?$..BVBV,VV-dii8!3DOO!D$4T5$A!%89 X	#\!), W#1>> %)?E^OO==?AEAaAaUYYy1}%=gn"%)^^%E%EFXZ[%\" $"B"B*1'*...*J*JK^`a*b'/</B/B1/Ea/H,*<'/<,oa0$7478UWfghWi4j!kDAq!a%!kJ!k,I)!"7>0Ea0H-!69K!KJ?C'*B$)'1) % @O @<&(< $"B"B \r-rVWeii9I9I!9La8P.Q-r*-r+099e6F6FG[6\^r5s+t( "YY&*7"/+/+F+F4J2F&7 % ' 
 

 339C9I9I!9L6%!2T5H5HO^oLo5p!pJ .$..--j!WmHYmglmnop'3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s*,00%@E I**A9I/IqSTuX\XfXfXlXlNlpqNq '')+N0Ba0G#$(K#K 1g6 LLNoW#X	#v 4-.43J3J3VIILLOOu% h&HHOOGdhhoo.L.L$LZ_ktOuE '+&=&=eV]M`M`&a#E#E##"Vekk!n4N;KLx(lLNL$$00K`n0o 	##%+,,,EQabb 7|F "l* .s[X	# X	#X MsE   j=j'C1j#j
'Aj#71j(Fj#j# 
j0j##j-)NTNNNN)NNNNNr   )	NNNNNr   r   r   N)FF)>__name__
__module____qualname____doc__model_cpu_offload_seq_optional_components_exclude_from_cpu_offloadr   r   r   r   r   r	   r   r   r   r   r   r-   r
   r   boolrZ   r   rr   r   r   rv   r   rq   r   r   r   r   r   r	  r   r  r#  r  r   r3  propertyr7  rw   ro   r?  rB  rE  no_gradr"   EXAMPLE_DOC_STRINGr   r   	Generatorr   r   r   r   r   r  __classcell__)r;   s   @rA   rE   rE      s   #J ES!1 2] 8<(,2Q2Q $2Q !	2Q
 #2Q /4+@%BXZnno2Q -2Q 52Q .2Q 52Q "&2Qv 049=&*  - !) 6 UON 049=&*#'t5  -t5 !) 6t5 UOt5 C=t5n52+'\'	!, # $&)" +/aF#\ %*>0 58emm.1@E	< $ $   X X , , # #   U]]_12 )-$( $##%#" #;?/0MQ*.049=9=@D%* ;?CF <?:=#' 9B=Icc49n%Ic "Ic 	Ic
 }Ic !Ic 9Ic UIc Ic "%T#Y"78Ic  (}Ic Ic E%//43H"HIJIc %,,'Ic  -Ic  !) 6!Ic" ##56#Ic$ "*$u||*<!=%Ic& c]'Ic( )Ic* !)c3h 8+Ic, (-UDK-?'@-Ic. /Ic0 !&eT%[&8 91Ic2 $E4;$673Ic4 C=5Ic6 '(Cd+T124DF\\]
7Ic< -1I=Ic 3 IcrC   rE   r  )Or6   typingr   r   r   r   r   r   r	   r   r  	PIL.Imager  rr   torch.nn.functionalr.  r/  r   transformersr
   r   r   r   	callbacksr   r   rd   r   r   loadersr   r   r   r   modelsr   r   r   r   r   models.lorar   
schedulersr   utilsr   r   r    r!   r"   r#   r$   utils.torch_utilsr%   r&   r'   r(   pipeline_utilsr*   r+    stable_diffusion.pipeline_outputr,   stable_diffusion.safety_checkerr-   torch_xla.core.xla_modelcore	xla_modelrf  re  
get_loggerr  r[   r  r   r   r/   r   rB   rE   r3   rC   rA   <module>r     s     D D D      h h A D w w q q 9 3   h g D L J ))MM			H	%+ b *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vtc"tcrC   