
    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l4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< ddl=m>Z>  e/       rd dl?m@c mAZB dZCndZC e0j                  eE      ZFdZG	 ddej                  deej                     deJfdZKd ZL G d de9e:e!e ee      ZMy)    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randn_tensor   )DiffusionPipelineStableDiffusionMixin)StableDiffusionPipelineOutput)StableDiffusionSafetyCheckerTFa
  
    Examples:
        ```py
        >>> # !pip install opencv-python transformers accelerate
        >>> from diffusers import StableDiffusionControlNetImg2ImgPipeline, 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"
        ... )
        >>> np_image = np.array(image)

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

        >>> # load control net and stable diffusion v1-5
        >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
        >>> pipe = StableDiffusionControlNetImg2ImgPipeline.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)
        >>> pipe.enable_model_cpu_offload()

        >>> # generate image
        >>> generator = torch.manual_seed(0)
        >>> image = pipe(
        ...     "futuristic-looking woman",
        ...     num_inference_steps=20,
        ...     generator=generator,
        ...     image=image,
        ...     control_image=canny_image,
        ... ).images[0]
        ```
encoder_output	generatorsample_modec                     t        | d      r |dk(  r| j                  j                  |      S t        | d      r|dk(  r| j                  j                         S t        | d      r| j                  S t        d      )Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrr1   r2   moder4   AttributeError)r-   r.   r/   s      u/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.pyretrieve_latentsr9   g   st     ~}-+2I))00;;		/K84K))..00		+%%%RSS    c           	         t        | t        j                        rB| j                  dk(  r| j	                  d      } | j                  t        j                        } | S t        | t        j                  j                  t        j                  f      r| g} t        | t              rwt        | d   t        j                  j                        rP| D cg c]-  }t        j                  |j                  d            d d d f   / } }t        j                  | d      } nYt        | t              rIt        | d   t        j                        r,t        j                  | D cg c]  }|d d d f    c}d      } | j                  dddd      } t        j                   |       j                  t        j                        dz  d	z
  } | S c c}w c c}w )
Nr   r   dtypeRGB)axis   r(   g     _@      ?)
isinstancetorchTensorndim	unsqueezetofloat32PILImagenpndarraylistarrayconvertconcatenate	transpose
from_numpy)imageis     r8   prepare_imagerU   t   sS   %&::?OOA&Eu}}- L eciioorzz:;GEeT"z%(CIIOO'LBGHQRXXaii./a8HEHNN5q1Et$E!Hbjj)INN#>1AdAgJ#>QGE1a+  '***?%G#ML I $?s   2GGc            <       F    e Zd ZdZdZg dZdgZg dZ	 	 dId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	 	 	 	 dJdeej2                     deej2                     dee   fdZ	 	 	 	 	 dKdeej2                     deej2                     dee   dee   fdZdLdZd Zd Z d Z!d Z"	 	 	 	 	 	 	 	 	 dMdZ#d  Z$	 	 dNd"Z%d# Z&dLd$Z'e(d%        Z)e(d&        Z*e(d'        Z+e(d(        Z,e(d)        Z-e(d*        Z. ej^                          e0e1      dddddd+d,d-dd.dddddddd/ddd+d!ddddd0gfd1ee2ee2   f   d2e3d3e3d4ee   d5ee   d6ed7ed8ed9eee2ee2   f      d:ee   d;ed<eeejh                  eejh                     f      d0eej2                     deej2                     deej2                     d=ee3   d>eeej2                        d?ee2   d@edAee5e2e6f      dBeeee   f   dCedDeeee   f   dEeeee   f   dee   dFeee7eee5gdf   e8e9f      dGee2   f6dH              Z: xZ;S )O(StableDiffusionControlNetImg2ImgPipelinea	  
    Pipeline for image-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->unet->vae)safety_checkerfeature_extractorimage_encoderrX   )r4   prompt_embedsnegative_prompt_embedscontrol_imageNTvaetext_encoder	tokenizerunet
controlnet	schedulerrY   rZ   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.)	r^   r_   r`   ra   rb   rc   rX   rY   rZ   r^   r(   r@      T)vae_scale_factordo_convert_rgbF)rg   rh   do_normalize)rd   )super__init__loggerwarning	__class__
ValueErrorrB   rM   tupler   register_modulesgetattrlenr^   configblock_out_channelsrg   r   image_processorcontrol_image_processorregister_to_config)selfr^   r_   r`   ra   rb   rc   rX   rY   rZ   rd   rn   s              r8   rk   z1StableDiffusionControlNetImg2ImgPipeline.__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Pr:   r[   r\   
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)promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_promptr[   r\   rz   r@   r    )r   encode_promptrC   cat)ry   r   r   r   r   r   r[   r\   rz   kwargsdeprecation_messageprompt_embeds_tuples               r8   _encode_promptz7StableDiffusionControlNetImg2ImgPipeline._encode_prompt   s}     a$g/BRWX0d00 

"7(C+'#9!

 

 		#6q#9;Nq;Q"RSr:   	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.
        Nr@   r   
max_lengthTpt)paddingr   
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)r=   r    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`.)$rB   r   _lora_scaler   r   r_   r#   strrM   rs   shaper   maybe_convert_promptr`   model_max_length	input_idsrC   equalbatch_decoderl   rm   r5   rt   r   r   rG   
text_modelfinal_layer_normr=   ra   repeatviewtype	TypeErrorro   r$   )ry   r   r   r   r   r   r[   r\   rz   r   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textr   prompt_embeds_dtypebs_embedseq_len_uncond_tokensr   uncond_inputs                          r8   r   z6StableDiffusionControlNetImg2ImgPipeline.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4r:   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 )	Nr   r   r   r=   T)r   r   dim)nextrZ   
parametersr=   rB   rC   rD   rY   pixel_valuesrG   hidden_statesrepeat_interleave
zeros_likeimage_embeds)
ry   rS   r   r   r   r=   image_enc_hidden_statesuncond_image_enc_hidden_statesr   uncond_image_embedss
             r8   encode_imagez5StableDiffusionControlNetImg2ImgPipeline.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4r:   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.r@   r(   r   r   r   )rB   rM   rs   ra   encoder_hid_projimage_projection_layersro   zipr   r   appendchunk	enumeraterC   r   rG   )ry   ip_adapter_imageip_adapter_image_embedsr   r   r   r   negative_image_embedssingle_ip_adapter_imageimage_proj_layeroutput_hidden_statesingle_image_embedssingle_negative_image_embedsrT   s                 r8   prepare_ip_adapter_image_embedszHStableDiffusionControlNetImg2ImgPipeline.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#**+>?	@ '&r:   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_typer   r   )images
clip_input)	rX   rC   	is_tensorrv   postprocessnumpy_to_pilrY   rG   r   )ry   rS   r   r=   has_nsfw_conceptfeature_extractor_inputsafety_checker_inputs          r8   run_safety_checkerz;StableDiffusionControlNetImg2ImgPipeline.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# &&&r:   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_latentsr|   Fr}   r@   )return_dictr   r(   g      ?r   )
r   r^   rt   scaling_factordecodeclampcpupermutefloatnumpy)ry   r4   r   rS   s       r8   r   z7StableDiffusionControlNetImg2ImgPipeline.decode_latents!  s     \"G-@PUVdhhoo444w>U;A>S''1-		##Aq!Q/557==?r:   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etar.   )setinspect	signaturerc   stepr   keys)ry   r.   r   accepts_etaextra_step_kwargsaccepts_generators         r8   prepare_extra_step_kwargszBStableDiffusionControlNetImg2ImgPipeline.prepare_extra_step_kwargs-  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  r:   rA           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         j                  t              rRt        |t              rBt        j                  dt         j                  j                         dt        |       d       t        t         d      xr8 t         j                  t"        j$                  j&                  j(                        }t         j                  t*              s&|r8t         j                  j,                  t*              r j/                  |||       nt         j                  t              s&|rt         j                  j,                  t              rt        |t              st1        d      t3        d |D              rt        d      t        |      t         j                  j                        k7  r8t        dt        |       dt         j                  j                         d      |D ]  } j/                  |||        nJ t         j                  t*              s&|r?t         j                  j,                  t*              rt        |	t4              st1        d      t         j                  t              s&|rt         j                  j,                  t              rst        |	t              rt3        d |	D              rSt        d      t        |	t              r8t        |	      t         j                  j                        k7  rt        d      J t        |
      t        |      k7  r$t        dt        |
       dt        |       d       t         j                  t              rt        |
      t         j                  j                        k7  r[t        d!|
 d"t        |
       d#t         j                  j                         d$t         j                  j                         d	      t7        |
|      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   j8                  d.vrt        d/|d   j8                   d0      y y c c}w )1Nr   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kry   s     r8   	<genexpr>zHStableDiffusionControlNetImg2ImgPipeline.check_inputs.<locals>.<genexpr>S  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` z	You have z! ControlNets and you have passed z= prompts. The conditionings will be fixed across the prompts.scaled_dot_product_attentionz5For multiple controlnets: `image` must be type `list`c              3   <   K   | ]  }t        |t                y wr   rB   rM   r   rT   s     r8   r   zHStableDiffusionControlNetImg2ImgPipeline.check_inputs.<locals>.<genexpr>  s     8QZ4(8   zEA single batch of multiple conditionings are supported at the moment.zbFor multiple controlnets: `image` must have the same length as the number of controlnets, but got r   z ControlNets.zLFor single controlnet: `controlnet_conditioning_scale` must be type `float`.c              3   <   K   | ]  }t        |t                y wr   r   r  s     r8   r   zHStableDiffusionControlNetImg2ImgPipeline.check_inputs.<locals>.<genexpr>  s     Rqz!T*Rr  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.rA   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)rB   intro   r   allr   r   rM   r   rb   r   rl   rm   rs   netsr5   FrC   _dynamo
eval_frameOptimizedModuler   	_orig_modcheck_imager   anyr   r   rE   )ry   r   rS   callback_stepsr   r[   r\   r   r   controlnet_conditioning_scalecontrol_guidance_startcontrol_guidance_end"callback_on_step_end_tensor_inputsr   is_compiledimage_startends   `                 r8   check_inputsz5StableDiffusionControlNetImg2ImgPipeline.check_inputs>  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  doo';<&$'DOO$8$8 9::[\_`f\g[hST 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8 !hii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    @  ?@ 5 t84??44oF;UC noot(<=4??446JK7>R4QRR$%lmm94@SIfEgkn$$l F !D 
 5%&#.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]|]|\}}~  ? /u pHs   !W 5W 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 r@   zdIf image batch size is not 1, image batch size must be same as prompt batch size. image batch size: z, prompt batch size: )rB   rI   rJ   rC   rD   rK   rL   rM   r   r   rs   r   r   ro   )ry   rS   r   r[   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               r8   r  z4StableDiffusionControlNetImg2ImgPipeline.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 r:   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widthr<   r   r@   r   r   r(   )rw   
preprocessrG   rC   rH   r   r   r   )ry   rS   r&  r%  r   r   r   r=   r   
guess_moder!  	repeat_bys               r8   prepare_control_imagez>StableDiffusionControlNetImg2ImgPipeline.prepare_control_image  s     ,,77fTY7Z]]didqdq]r ;;q>q "I .I''	q'9e4&zIIugk*Er:   c                 N   t        t        ||z        |      }t        ||z
  d      }| j                  j                  || j                  j
                  z  d  }t        | j                  d      r2| j                  j                  || j                  j
                  z         |||z
  fS )Nr   set_begin_index)minr  maxrc   	timestepsorderr5   r,  )ry   num_inference_stepsstrengthr   init_timestept_startr/  s          r8   get_timestepsz6StableDiffusionControlNetImg2ImgPipeline.get_timesteps!  s    C 3h >?ATU)M91=NN,,Wt~~7K7K-K-MN	4>>#45NN**7T^^5I5I+IJ-777r:   c                 @   t        |t        j                  t        j                  j                  t
        f      st        dt        |             |j                  ||      }||z  }|j                  d   dk(  r|}nt        |t
              r)t        |      |k7  rt        dt        |       d| d      t        |t
              r|j                  d   |k  rA||j                  d   z  dk(  r,t        j                  |g||j                  d   z  z  d	      }nF|j                  d   |k  r4||j                  d   z  dk7  rt        d
|j                  d    d| d      t        |      D 	cg c]1  }	t        | j                  j                  ||	|	dz          ||	         3 }}	t        j                  |d	      }n&t        | j                  j                  |      |      }| j                  j                   j"                  |z  }||j                  d   kD  rh||j                  d   z  dk(  rSd| d|j                  d    d}
t%        dd|
d       ||j                  d   z  }t        j                  |g|z  d	      }n^||j                  d   kD  r4||j                  d   z  dk7  rt        d
|j                  d    d| d      t        j                  |gd	      }|j                  }t'        ||||      }| j(                  j+                  |||      }|}|S c c}	w )NzK`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is r   r@   r  z/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   z'Cannot duplicate `image` of batch size z to effective batch_size  )r.   zYou have passed z# text prompts (`prompt`), but only a    initial images (`image`). Initial images are now duplicating to match the number of text prompts. Note that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update your script to pass as many initial images as text prompts to suppress this warning.zlen(prompt) != len(image)r|   Fr}   z to z text prompts.)r.   r   r=   )rB   rC   rD   rI   rJ   rM   ro   r   rG   r   rs   r   ranger9   r^   encodert   r   r   r'   rc   	add_noise)ry   rS   timestepr   r   r=   r   r.   init_latentsrT   r   additional_image_per_promptr   noiser4   s                  r8   prepare_latentsz8StableDiffusionControlNetImg2ImgPipeline.prepare_latents-  s=   %%,,		!FG]^bch^i]jk  e4"77
;;q>Q L )T*s9~/K Ec)nEU V  *|+km 
 It,;;q>J.:A3NRS3S!IIugu{{1~1M&NTUVE[[^j0Z%++a.5PTU5U$A%++a.AQQjkujvvwx  #:.  %TXX__U1q1u5E%FR[\]R^_     %yy1=/0FR[\88??99LHL**1--*|?Q?QRS?T2TXY2Y #:,.QR^RdRdefRgQh ih h   17<O_de*48J8J18M*M' 99l^6Q%QWXYL,,,Q//JASASTUAV4VZ[4[9,:L:LQ:O9PPTU_T``no  !99l^;L""UieT ~~//eXNG s   .6Lc                     | j                   S r   _guidance_scalery   s    r8   guidance_scalez7StableDiffusionControlNetImg2ImgPipeline.guidance_scalen  s    ###r:   c                     | j                   S r   )
_clip_skiprC  s    r8   r   z2StableDiffusionControlNetImg2ImgPipeline.clip_skipr      r:   c                      | j                   dkD  S )Nr@   rA  rC  s    r8   r   zDStableDiffusionControlNetImg2ImgPipeline.do_classifier_free_guidancey  s    ##a''r:   c                     | j                   S r   )_cross_attention_kwargsrC  s    r8   cross_attention_kwargsz?StableDiffusionControlNetImg2ImgPipeline.cross_attention_kwargs}  s    +++r:   c                     | j                   S r   )_num_timestepsrC  s    r8   num_timestepsz6StableDiffusionControlNetImg2ImgPipeline.num_timesteps  s    """r:   c                     | j                   S r   )
_interruptrC  s    r8   	interruptz2StableDiffusionControlNetImg2ImgPipeline.interrupt  rG  r:   g?2   g      @r@   r   r4   r   rS   r]   r%  r&  r2  r1  rD  r   r   r   r.   r   r   r   r   rK  r  r(  r  r  callback_on_step_endr  c                 2   |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                        }%| jB                  jE                  |||      jG                  t<        jH                        }t        |t,              r2| jK                  ||||!|
z  |
|"|jL                  | j8                  |	      }n`t        |t              rNg }&|D ]D  }'| jK                  |'|||!|
z  |
|"|jL                  | j8                  |	      }'|&jO                  |'       F |&}nJ | jP                  jS                  ||"       | jU                  |||"      \  }(}|(dd jW                  |!|
z        })t        |(      | _,        |!| j[                  ||)|!|
|jL                  |"|      }| j]                  ||      }*||d%ind}+g },t_        t        |(            D ]w  }-ta        ||      D ./cg c]8  \  }.}/dt+        |-t        |(      z  |.k  xs |-dz   t        |(      z  |/kD        z
  : }0}.}/|,jO                  t        |t,              r|0d	   n|0       y t        |(      || jP                  jb                  z  z
  }1| je                  |      5 }2tg        |(      D ]  \  }-}3| jh                  r| j8                  rt=        j>                  |gdz        n|}4| jP                  jk                  |4|3      }4|r?| j8                  r3|}5| jP                  jk                  |5|3      }5|jm                  d      d   }6n|4}5|}6t        |,|-   t              r%ta        ||,|-         D 7.cg c]
  \  }7}.|7|.z   }8}7}.n|}9t        |9t              r|9d	   }9|9|,|-   z  }8| j                  |5|3|6||8|d      \  }:};|rm| j8                  ra|:D <cg c],  }<t=        j>                  t=        jn                  |<      |<g      . }:}<t=        j>                  t=        jn                  |;      |;g      };| jq                  |4|3|| j2                  |:|;|+d      d	   }=| j8                  r|=jm                  d      \  }>}?|>||?|>z
  z  z   }= | jP                  jr                  |=|3|fi |*ddid	   }|li }@|D ]  }Atu               |A   @|A<     || |-|3@      }B|Bj                  d|      }|Bj                  d|      }|Bj                  d|      }|Bj                  d|      }|-t        |(      dz
  k(  s'|-dz   |1kD  r]|-dz   | jP                  jb                  z  d	k(  r>|2jw                          |,|-|z  d	k(  r$|-ty        | jP                  dd      z  }C ||C|3|       tz        st}        j~                           	 ddd       t        | d      rL| j                  @| jp                  jG                  d       | j                  jG                  d       t                |dk(  sc| j                  j                  || j                  j.                  j                  z  d|      d	   }| j                  ||"|jL                        \  }}Dn|}d}DDd g|j&                  d	   z  }EnDD Fcg c]  }F|F  }E}F| jB                  j                  ||E!      }| j                          |s|DfS t        |D"      S c c}/}.w c c}.}7w c c}<w # 1 sw Y   FxY wc c}Fw )#u"  
        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 initial image to be used as the starting point for the image generation process. Can also accept
                image latents as `image`, and if passing latents directly they are not encoded again.
            control_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.
            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.
            strength (`float`, *optional*, defaults to 0.8):
                Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
                starting point and more noise is added the higher the `strength`. The number of denoising steps depends
                on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
                process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
                essentially ignores `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.
            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.
            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  r|   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`r@   Fr   scale)r[   r\   rz   r   r$  r<   )	rS   r&  r%  r   r   r   r=   r   r(  r   r   rA   )totalr(   )encoder_hidden_statescontrolnet_condconditioning_scaler(  r   )rX  rK  down_block_additional_residualsmid_block_additional_residualadded_cond_kwargsr   r   r4   r[   r\   r]   r0  final_offload_hookr   latent)r   r.   T)r   do_denormalize)r   nsfw_content_detected)Jpopr   rB   r   r   tensor_inputsr&   rb   r  rM   rs   r   r  r  rB  rF  rJ  rP  r   r   _execution_devicer   r   rt   global_pool_conditionsrK  getr   r   r   rC   r   r   rv   r'  rG   rH   r*  r=   r   rc   set_timestepsr5  r   rM  r?  r   r8  r   r0  progress_barr   rQ  scale_model_inputr   r   ra   r   localsupdaterr   XLA_AVAILABLExm	mark_stepr5   r^  r%   r^   r   r   r   r   maybe_free_model_hooksr+   )Gry   r   rS   r]   r%  r&  r2  r1  rD  r   r   r   r.   r4   r[   r\   r   r   r   r   rK  r  r(  r  r  r   rS  r  r   rU  r  rb   multr   r   re  text_encoder_lora_scaler   control_imagescontrol_image_r/  latent_timestepr   r]  controlnet_keeprT   sekeepsnum_warmup_stepsrh  t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   r`  has_nsfwsG                                                                          r8   __call__z1StableDiffusionControlNetImg2ImgPipeline.__call__  sd
   T ::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 $$//fE/RUU\a\i\iUj j/2 66#%(==&; &&,0,L,L% 7 
M 
$89N"/ 6!%!;!;(!),AA*?!$**040P0P) "< 
" %%n56 +M5 	$$%8$H)-););<OQY[a)b&	&#BQ-..z<Q/QR!)n ?**%##G !::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%89 S	#\!), R#1>> BFAaAaUYY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'1) % @O @<&(< $"B"B \r-rVWeii9I9I!9La8P.Q-r*-r+099e6F6FG[6\^r5s+t( "YY&*7+/+F+F4J2F&7 % ' 	 	
 339C9I9I!9L6%!2^YjGj5k!kJ .$..--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*$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '')+N0Ba0G#$(K#K 1g6 LLNeR#S	#n 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bu8 "l* .sSS	# S	#P Ms?    =e6?Cfe<
Af+1fFf+f)
f<ff)NT)NNNN)NNNNNr   )	NNNNNrA   r   rA   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   boolrk   r   rC   rD   r   r   r  r   r   r   r   r   r   r  r  r*  r5  r?  propertyrD  r   r   rK  rN  rQ  no_gradr"   EXAMPLE_DOC_STRINGr   r   	Generatorr   r   r   r   r   r  __classcell__)rn   s   @r8   rW   rW      s   #J 6S!1 2e 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+'\'	!, # $&)" +/[|#^ %*>	8?B $ $   ( ( , , # #   U]]_12 )-$(,0 $##% #;?/0MQ*.049=9=@D%* ;?CF <?:=#' 9B=occ49n%oc "oc *	oc
 oc }oc oc !oc oc "%T#Y"78oc  (}oc oc E%//43H"HIJoc %,,'oc  -oc  !) 6!oc" ##56#oc$ "*$u||*<!=%oc& c]'oc( )oc* !)c3h 8+oc, (-UDK-?'@-oc. /oc0 !&eT%[&8 91oc2 $E4;$673oc4 C=5oc6 '(Cd+T124DF\\]
7oc< -1I=oc 3 ocr:   rW   )Nr2   )Nr   typingr   r   r   r   r   r   r	   r   rK   	PIL.ImagerI   rC   torch.nn.functionalnn
functionalr	  transformersr
   r   r   r   	callbacksr   r   rv   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'   pipeline_utilsr)   r*   stable_diffusionr+   stable_diffusion.safety_checkerr,   torch_xla.core.xla_modelcore	xla_modelrm  rl  
get_loggerr  rl   r  rD   r  r   r9   rU   rW   r   r:   r8   <module>r     s     D D D      h h A D w w q q 9 3   V U D < J ))MM			H	%, b ck
TLL
T-5eoo-F
T\_
T0nc"ncr:   