
    +h                        S SK r S SKJrJrJrJrJrJr  S SKrS SK	J
r
  S SKJrJrJrJr  SSKJrJr  SSKJr  SSKJrJr  SS	KJrJrJrJr  SS
KJrJrJ r   SSK!J"r"  SSK#J$r$  SSK%J&r&J'r'J(r(J)r)J*r*J+r+J,r,  SSK-J.r.  SSK/J0r0J1r1  SSK2J3r3  SSK4J5r5  \(" 5       (       a  S SK6J7s  J8r9  Sr:OSr:\)Rv                  " \<5      r=Sr>SS jr?    S S\\@   S\\\A\R                  4      S\\\@      S\\\C      4S jjrD " S S\0\1\\\\5      rEg)!    N)AnyCallableDictListOptionalUnion)version)CLIPImageProcessorCLIPTextModelCLIPTokenizerCLIPVisionModelWithProjection   )MultiPipelineCallbacksPipelineCallback)
FrozenDict)PipelineImageInputVaeImageProcessor)FromSingleFileMixinIPAdapterMixinStableDiffusionLoraLoaderMixinTextualInversionLoaderMixin)AutoencoderKLImageProjection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)randn_tensor   )DiffusionPipelineStableDiffusionMixin   )StableDiffusionPipelineOutput)StableDiffusionSafetyCheckerTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import StableDiffusionPipeline

        >>> pipe = StableDiffusionPipeline.from_pretrained(
        ...     "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to("cuda")

        >>> prompt = "a photo of an astronaut riding a horse on mars"
        >>> image = pipe(prompt).images[0]
        ```
c                     UR                  [        [        SUR                  5      5      SS9nU R                  [        [        SU R                  5      5      SS9nXU-  -  nX%-  SU-
  U -  -   n U $ )a  
Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
Flawed](https://huggingface.co/papers/2305.08891).

Args:
    noise_cfg (`torch.Tensor`):
        The predicted noise tensor for the guided diffusion process.
    noise_pred_text (`torch.Tensor`):
        The predicted noise tensor for the text-guided diffusion process.
    guidance_rescale (`float`, *optional*, defaults to 0.0):
        A rescale factor applied to the noise predictions.

Returns:
    noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
r(   T)dimkeepdim)stdlistrangendim)	noise_cfgnoise_pred_textguidance_rescalestd_textstd_cfgnoise_pred_rescaleds         x/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.pyrescale_noise_cfgr9   E   s{    " ""tE!_5I5I,J'KUY"ZHmmU1inn%= >mMG#''9: 6!>N:NR[9[[I    num_inference_stepsdevice	timestepssigmasc                    Ub  Ub  [        S5      eUb  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
X2S.UD6  U R                  n[        U5      nX14$ Ub  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
XBS.UD6  U R                  n[        U5      nX14$ U R                  " U4S	U0UD6  U R                  nX14$ )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 valuesr=   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r=   r<   r>   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r>   r<   r<    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r=   len)	schedulerr;   r<   r=   r>   kwargsaccepts_timestepsaccept_sigmass           r8   retrieve_timestepsrN   _   s}   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	M)MfM''	!)n )) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	GvGG''	!)n )) 	 3MFMfM''	))r:   c            4       p  ^  \ rS rSrSrSr/ SQrS/r/ SQr  SGS	\	S
\
S\S\S\S\S\S\S\4U 4S jjjr    SHS\\R*                     S\\R*                     S\\   4S jjr     SIS\\R*                     S\\R*                     S\\   S\\   4S jjrSJS jrS rS rS rS r      SKS jrSJS jr S\RB                  4S \R*                  S!\S"\RD                  S#\R*                  4S$ jjr#\$S% 5       r%\$S& 5       r&\$S' 5       r'\$S( 5       r(\$S) 5       r)\$S* 5       r*\$S+ 5       r+\RX                  " 5       \-" \.5      SSSS,SSS-SS.S/SSSSSSS0SSS/SSS1/4S2\/\0\1\0   4   S3\\   S4\\   S5\S6\1\   S7\1\   S8\S9\\/\0\1\0   4      S:\\   S;\S<\\/\Rd                  \1\Rd                     4      S1\\R*                     S\\R*                     S\\R*                     S=\\3   S>\\1\R*                        S?\\0   S@\SA\\4\0\54      SB\S\\   SC\\/\6\\\4/S4   \7\84      SD\1\0   4.SE jj5       5       r9SFr:U =r;$ )LStableDiffusionPipeline   a  
Pipeline for text-to-image generation using Stable Diffusion.

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.
    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_encoderrR   )latentsprompt_embedsnegative_prompt_embedsNTvaetext_encoder	tokenizerunetrJ   rS   rT   requires_safety_checkerc
                   > [         TU ]  5         Ubn  [        UR                  SS5      S:w  aS  SU SUR                  R                   S3n
[        SSU
SS	9  [        UR                  5      nSUS'   [        U5      Ul        UbV  [        UR                  S
S5      SL a<  SU S3n
[        SSU
SS	9  [        UR                  5      nSUS
'   [        U5      Ul        Uc*  U	(       a#  [        R                  SU R                   S35        Ub  Uc  [        S5      eUS L=(       a|    [        UR                  S5      =(       a_    [        R                  " [        R                  " UR                  R                   5      R"                  5      [        R                  " S5      :  nUS L=(       a$    [%        UR                  R&                  [(        5      U l        US L=(       aI    [        UR                  S5      =(       a,    U R*                  =(       a    UR                  R&                  S:  nU(       a?  U(       a8  Sn
[        SSU
SS	9  [        UR                  5      nSUS'   [        U5      Ul        U R-                  UUUUUUUUS9  [        U SS 5      (       a/  S[/        U R0                  R                  R2                  5      S-
  -  OSU l        [7        U R4                  S9U l        U R;                  U	S9  g )Nsteps_offsetr(   z*The configuration file of this scheduler: z; is outdated. `steps_offset` should be set to 1 instead of a(  . Please make sure to update the config accordingly as leaving `steps_offset` might led to incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json` filezsteps_offset!=11.0.0Fstandard_warnclip_sampleTa   has not set the configuration `clip_sample`. `clip_sample` should be set to False in the configuration file. Please make sure to update the config accordingly as not setting `clip_sample` in the config might lead to incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json` filezclip_sample not setz)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._diffusers_versionz
0.9.0.dev0sample_size@   a  The configuration file of the unet has set the default `sample_size` to smaller than 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the following: 
- CompVis/stable-diffusion-v1-4 
- CompVis/stable-diffusion-v1-3 
- CompVis/stable-diffusion-v1-2 
- CompVis/stable-diffusion-v1-1 
- stable-diffusion-v1-5/stable-diffusion-v1-5 
- stable-diffusion-v1-5/stable-diffusion-inpainting 
 you should change 'sample_size' to 64 in the configuration file. Please make sure to update the config accordingly as leaving `sample_size=32` in the config might lead to incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for the `unet/config.json` filezsample_size<64)rX   rY   rZ   r[   rJ   rR   rS   rT   rX   r%      )vae_scale_factor)r\   )super__init__getattrconfigr^   r   dictr   _internal_dictloggerwarningrH   rA   hasattrr	   parserc   base_version
isinstancerd   int_is_unet_config_sample_size_intregister_modulesrI   rX   block_out_channelsrg   r   image_processorregister_to_config)selfrX   rY   rZ   r[   rJ   rR   rS   rT   r\   deprecation_message
new_configis_unet_version_less_0_9_0is_unet_sample_size_less_64rH   s                 r8   ri    StableDiffusionPipeline.__init__   s    	 WY-=-=~q%QUV%V<YK H22;2B2B2O2O1P Q   '2EUZ[i../J)*J~&'1*'=I$ WY-=-=}e%TX\%\<YK Hh h   +W6IY^_i../J(-J}%'1*'=I$!&=NN;DNN;K Lj j %*;*Cx   x%9:xgmmDKK,J,JKXXY\c\i\ijv\ww 	#
 044/?/lJt{{OfOfhkDl, -]3-44- ''",	 	$ &*E/   &1DTYZdkk*J(*J}%",Z"8D%)/' 	 		
 W^^bdikoVpVpc$((//*L*L&MPQ&Q Rvw0$BWBWX8OPr:   rV   rW   
lora_scalec	                     Sn
[        SSU
SS9  U R                  " S	UUUUUUUUS.U	D6n[        R                  " US   US   /5      nU$ )
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()r_   Fr`   )promptr<   num_images_per_promptdo_classifier_free_guidancenegative_promptrV   rW   r   r(   r   r@   )r   encode_prompttorchcat)rz   r   r<   r   r   r   rV   rW   r   rK   r{   prompt_embeds_tuples               r8   _encode_prompt&StableDiffusionPipeline._encode_prompt,  s{     a$g/BRWX"00 

"7(C+'#9!

 

 		#6q#9;Nq;Q"RSr:   	clip_skipc
                 
   UbS  [        U [        5      (       a>  Xl        [        (       d  [	        U R
                  U5        O[        U R
                  U5        Ub  [        U[        5      (       a  Sn
O3Ub!  [        U[        5      (       a  [        U5      n
OUR                  S   n
UGc  [        U [        5      (       a  U R                  XR                  5      nU R                  USU R                  R                  SSS9nUR                  nU R                  USSS	9R                  nUR                  S
   UR                  S
   :  a  [         R"                  " X5      (       dj  U R                  R%                  USS2U R                  R                  S-
  S
24   5      n[&        R)                  SU R                  R                   SU 35        [+        U R
                  R,                  S5      (       aA  U R
                  R,                  R.                  (       a  UR0                  R3                  U5      nOSnU	c%  U R                  UR3                  U5      US9nUS   nOQU R                  UR3                  U5      USS9nUS
   U	S-   *    nU R
                  R4                  R7                  U5      nU R
                  b  U R
                  R8                  nO0U R:                  b  U R:                  R8                  nOUR8                  nUR3                  UUS9nUR                  u  nnnUR=                  SUS5      nUR?                  UU-  US
5      nU(       Ga  UGc|  Uc  S/U
-  nOUb;  [A        U5      [A        U5      La$  [C        S[A        U5       S[A        U5       S35      e[        U[        5      (       a  U/nO2U
[        U5      :w  a!  [E        SU S[        U5       SU SU
 S3	5      eUn[        U [        5      (       a  U R                  UU R                  5      nUR                  S   nU R                  USUSSS9n[+        U R
                  R,                  S5      (       aA  U R
                  R,                  R.                  (       a  UR0                  R3                  U5      nOSnU R                  UR                  R3                  U5      US9nUS   nU(       aG  UR                  S   nUR3                  UUS9nUR=                  SUS5      nUR?                  X-  US
5      nU R
                  b6  [        U [        5      (       a!  [        (       a  [G        U R
                  U5        Xg4$ )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)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`.)$rs   r   _lora_scaler   r   rY   r"   strr/   rI   shaper   maybe_convert_promptrZ   model_max_length	input_idsr   equalbatch_decodern   ro   rp   rk   r   r   to
text_modelfinal_layer_normr   r[   repeatviewtype	TypeErrorrA   r#   )rz   r   r<   r   r   r   rV   rW   r   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   %StableDiffusionPipeline.encode_promptL  sQ   V !j7U&V&V) $#.t/@/@*M!$"3"3Z@*VS"9"9JJvt$<$<VJ&,,Q/J $ ;<<226>>J..$>>::# ) K )22N"nnVYW[n\ffO$$R(N,@,@,DDU[[N N  $~~::#At~~'F'F'JR'O$OP  778	,Q
 t((//1EF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1!0 1s?33 )/)::J3K_J` ax/
| <33  !0 $ ;<< $ 9 9- X&,,Q/J>>$%# * L t((//1EFF4K\K\KcKcKvKv!-!<!<!?!?!G!%%)%6%6&&))&1- &7 &" &<A%>"&,2215G%;%>%>EXag%>%h"%;%B%B1F[]^%_"%;%@%@Acelnp%q"($ >??DTDT#D$5$5zB44r:   c                 d   [        U R                  R                  5       5      R                  n[	        U[
        R                  5      (       d  U R                  USS9R                  nUR                  X%S9nU(       aq  U R                  USS9R                  S   nUR                  USS9nU R                  [
        R                  " U5      SS9R                  S   nUR                  USS9nXg4$ U R                  U5      R                  nUR                  USS9n[
        R                  " U5      n	X4$ )	Nr   r   r<   r   T)r   r   r,   )nextrT   rF   r   rs   r   TensorrS   pixel_valuesr   hidden_statesrepeat_interleave
zeros_likeimage_embeds)
rz   imager<   r   r   r   image_enc_hidden_statesuncond_image_enc_hidden_statesr   uncond_image_embedss
             r8   encode_image$StableDiffusionPipeline.encode_image  s?   T''2245;;%..**5*FSSE4&*&8&8UY&8&Z&h&hik&l#&=&O&OPekl&O&m#-1-?-?  'd .@ .mB. * .L-]-]%1 .^ .* +JJ--e4AAL'99:OUV9WL"'"2"2<"@44r:   c                 
   / nU(       a  / nUGc&  [        U[        5      (       d  U/n[        U5      [        U R                  R                  R
                  5      :w  aB  [        S[        U5       S[        U R                  R                  R
                  5       S35      e[        XR                  R                  R
                  5       Hh  u  p[        U	[        5      (       + n
U R                  XSU
5      u  pUR                  US S S 24   5        U(       d  MP  WR                  US S S 24   5        Mj     OEU H?  nU(       a$  UR                  S5      u  pWR                  U5        UR                  U5        MA     / n[        U5       Hw  u  p[        R                  " U/U-  SS9nU(       a2  [        R                  " WU   /U-  SS9n[        R                  " X/SS9nUR                  US9nUR                  U5        My     U$ )	NzK`ip_adapter_image` must have same length as the number of IP Adapters. Got z images and z IP Adapters.r(   r%   r   r   )r<   )rs   r/   rI   r[   encoder_hid_projimage_projection_layersrA   zipr   r   appendchunk	enumerater   r   r   )rz   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_embedsis                 r8   prepare_ip_adapter_image_embeds7StableDiffusionPipeline.prepare_ip_adapter_image_embeds  s9    &$&!"*.5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>9' +55E*W&W#DHDUDU+Q8KEA# ##$7a$@A..)001MdTUg1VW> (?#.H[HaHabcHdE0)001MN##$78	 (? #%&/&="A"'))-@,ADY,Y_`"a*/4yy:OPQ:R9SVk9kqr/s,&+ii1M0cij&k#"5"8"8"8"G#**+>? '> '&r:   c                 `   U R                   c  S nX4$ [        R                  " U5      (       a  U R                  R	                  USS9nOU R                  R                  U5      nU R                  USS9R                  U5      nU R                  XR                  R                  U5      S9u  pX4$ )Npil)output_typer   r   )images
clip_input)	rR   r   	is_tensorrx   postprocessnumpy_to_pilrS   r   r   )rz   r   r<   r   has_nsfw_conceptfeature_extractor_inputsafety_checker_inputs          r8   run_safety_checker*StableDiffusionPipeline.run_safety_checkerG  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                 T   Sn[        SSUSS9  SU R                  R                  R                  -  U-  nU R                  R	                  USS9S   nUS	-  S
-   R                  SS5      nUR                  5       R                  SS	SS5      R                  5       R                  5       nU$ )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   rX   rk   scaling_factordecodeclampcpupermutefloatnumpy)rz   rU   r{   r   s       r8   r   &StableDiffusionPipeline.decode_latentsU  s     \"G-@PUVdhhoo444w>U;A>S''1-		##Aq!Q/557==?r:   c                 n   S[        [        R                  " U R                  R                  5      R
                  R                  5       5      ;   n0 nU(       a  X$S'   S[        [        R                  " U R                  R                  5      R
                  R                  5       5      ;   nU(       a  XS'   U$ )Neta	generator)rB   rC   rD   rJ   steprF   rG   )rz   r   r   accepts_etaextra_step_kwargsaccepts_generators         r8   prepare_extra_step_kwargs1StableDiffusionPipeline.prepare_extra_step_kwargs`  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  r:   c           
        ^  US-  S:w  d	  US-  S:w  a  [        SU SU S35      eUb6  [        U[        5      (       a  US::  a  [        SU S[        U5       S35      eU
bW  [	        U 4S jU
 5       5      (       d=  [        S	T R
                   S
U
 Vs/ s H  oT R
                  ;  d  M  UPM     sn 35      eUb  Ub  [        SU SU S35      eUc  Uc  [        S5      eUbA  [        U[        5      (       d,  [        U[        5      (       d  [        S[        U5       35      eUb  Ub  [        SU SU S35      eUbC  Ub@  UR                  UR                  :w  a&  [        SUR                   SUR                   S35      eUb  U	b  [        S5      eU	b\  [        U	[        5      (       d  [        S[        U	5       35      eU	S   R                  S;  a  [        SU	S   R                   S35      eg g s  snf )Nrf   r   z7`height` and `width` have to be divisible by 8 but are z and r   z5`callback_steps` has to be a positive integer but is z	 of type c              3   @   >#    U  H  oTR                   ;   v   M     g 7fN)_callback_tensor_inputs).0krz   s     r8   	<genexpr>7StableDiffusionPipeline.check_inputs.<locals>.<genexpr>  s      F
7Y!---7Ys   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` 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)
rA   rs   rt   r   allr   r   r/   r   r1   )rz   r   heightwidthcallback_stepsr   rV   rW   r   r   "callback_on_step_end_tensor_inputsr   s   `           r8   check_inputs$StableDiffusionPipeline.check_inputsq  s    A:?eai1nVW]V^^cdicjjklmm%z.#/N/NR`deReGGW X(),  .9# F
7YF
 C
 C
 DTEaEaDbbn  |^  pH  |^vw  ko  kG  kG  bGpq  |^  pH  oI  J  -";08N}o ^0 0  ^ 5w  FC)@)@TZ\`IaIaQRVW]R^Q_`aa&+A+M9/9J K*++]_ 
 $)?)K""&<&B&BB --:-@-@,A B.445Q8  ',C,O ^  #.5t<< PQUVmQnPop  )+00> \]tuv]w]|]|\}}~  ? /E pHs   G5*G5c	                 V   UU[        U5      U R                  -  [        U5      U R                  -  4n	[        U[        5      (       a*  [	        U5      U:w  a  [        S[	        U5       SU S35      eUc  [        XXeS9nOUR                  U5      nXR                  R                  -  nU$ )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   )
rt   rg   rs   r/   rI   rA   r$   r   rJ   init_noise_sigma)
rz   r   num_channels_latentsr  r  r   r<   r   rU   r   s
             r8   prepare_latents'StableDiffusionPipeline.prepare_latents  s     K4000J$///	
 i&&3y>Z+GA#i.AQ R&<'gi 
 ?"5fZGjj(G NN;;;r:   i   wembedding_dimr   returnc                 r   [        UR                  5      S:X  d   eUS-  nUS-  n[        R                  " [        R                  " S5      5      US-
  -  n[        R
                  " [        R                  " XCS9U* -  5      nUR                  U5      SS2S4   USSS24   -  n[        R                  " [        R                  " U5      [        R                  " U5      /SS9nUS-  S:X  a*  [        R                  R                  R                  US5      nUR                  UR                  S	   U4:X  d   eU$ )
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)`.
r(   g     @@r%   g     @)r   Nr   )r   r(   r   )rI   r   r   logtensorexparanger   r   sincosnn
functionalpad)rz   r  r  r   half_dimembs         r8   get_guidance_scale_embedding4StableDiffusionPipeline.get_guidance_scale_embedding  s    " 177|q   J A%iiW-.(Q,?iiX;sdBCdd5k!T'"Sq\1ii338a@1!((%%))#v6CyyQWWQZ7777
r:   c                     U R                   $ r   )_guidance_scalerz   s    r8   guidance_scale&StableDiffusionPipeline.guidance_scale  s    ###r:   c                     U R                   $ r   )_guidance_rescaler$  s    r8   r4   (StableDiffusionPipeline.guidance_rescale  s    %%%r:   c                     U R                   $ r   )
_clip_skipr$  s    r8   r   !StableDiffusionPipeline.clip_skip      r:   c                 r    U R                   S:  =(       a"    U R                  R                  R                  S L $ )Nr(   )r#  r[   rk   time_cond_proj_dimr$  s    r8   r   3StableDiffusionPipeline.do_classifier_free_guidance  s.    ##a'WDII,<,<,O,OSW,WWr:   c                     U R                   $ r   )_cross_attention_kwargsr$  s    r8   cross_attention_kwargs.StableDiffusionPipeline.cross_attention_kwargs  s    +++r:   c                     U R                   $ r   )_num_timestepsr$  s    r8   num_timesteps%StableDiffusionPipeline.num_timesteps  s    """r:   c                     U R                   $ r   )
_interruptr$  s    r8   	interrupt!StableDiffusionPipeline.interrupt  r-  r:   2   g      @r(           r   rU   r   r  r  r;   r=   r>   r%  r   r   r   r   r   r   r   r   r3  r4   callback_on_step_endr	  c                 "   UR                  SS5      nUR                  SS5      nUb  [        SSS5        Ub  [        SSS5        [        U[        [        45      (       a  UR
                  nU(       a  U(       d  U R                  (       a   U R                  R                  R                  O"U R                  R                  R                  S   nU R                  (       a   U R                  R                  R                  O"U R                  R                  R                  S   nX R                  -  X0R                  -  p2U R                  UUUUUUUUUU5
        Xpl        UU l        UU l        UU l        S	U l        Ub  [        U["        5      (       a  SnO3Ub!  [        U[$        5      (       a  ['        U5      nOUR(                  S   nU R*                  nU R,                  b  U R,                  R/                  S
S5      OSnU R1                  UUU	U R2                  UUUUU R4                  S9	u  pU R2                  (       a  [6        R8                  " X/5      nUc  Ub"  U R;                  UUUUU	-  U R2                  5      n[=        U R>                  UUXV5      u  pTU R                  R                  R@                  nU RC                  UU	-  UUUURD                  UUU5      nU RG                  X5      n Uc  Ub  SW0OSn!Sn"U R                  R                  RH                  b{  [6        RJ                  " U RL                  S-
  5      RO                  UU	-  5      n#U RQ                  U#U R                  R                  RH                  S9RS                  UURD                  S9n"['        U5      X@R>                  RT                  -  -
  n$['        U5      U l+        U RY                  US9 n%[[        U5       GH3  u  n&n'U R\                  (       a  M  U R2                  (       a  [6        R8                  " U/S-  5      OUn([_        U R>                  S5      (       a  U R>                  Ra                  U(U'5      n(U R                  U(U'UU"U R,                  U!S	S9S   n)U R2                  (       a)  U)Rc                  S5      u  n*n+U*U RL                  U+U*-
  -  -   n)U R2                  (       a%  U Rd                  S:  a  [g        U)W+U Rd                  S9n)U R>                  Rh                  " U)U'U40 U DSS	0D6S   nUb\  0 n,U H  n-[k        5       U-   U,U-'   M     U" U U&U'U,5      n.U.R                  SU5      nU.R                  SU5      nU.R                  SU5      nU&['        U5      S-
  :X  d)  U&S-   U$:  a`  U&S-   U R>                  RT                  -  S:X  a@  U%Rm                  5         Ub-  U&U-  S:X  a$  U&[o        U R>                  SS5      -  n/U" U/U'U5        [p        (       d  GM  [r        Rt                  " 5         GM6     SSS5        US:X  d_  U Rv                  Ry                  XRv                  R                  Rz                  -  S	US9S   n0U R}                  U0UURD                  5      u  n0n1OUn0Sn1U1c  S/U0R(                  S   -  n2OU1 V3s/ s H
  n3U3(       + PM     n2n3U R~                  R                  U0UU2S9n0U R                  5         U(       d  U0U14$ [        U0U1S9$ ! , (       d  f       N= fs  sn3f )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`.
    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.
    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).
    guidance_rescale (`float`, *optional*, defaults to 0.0):
        Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
        Flawed](https://huggingface.co/papers/2305.08891). Guidance rescale factor should fix overexposure when
        using zero terminal SNR.
    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   r(   Fscale)rV   rW   r   r   r   )r  r   )totalr%   scale_model_input)encoder_hidden_statestimestep_condr3  added_cond_kwargsr   r>  )r4   r   rU   rV   rW   orderlatent)r   r   T)r   do_denormalize)r   nsfw_content_detected)Cpopr   rs   r   r   tensor_inputsru   r[   rk   rd   rg   r
  r#  r(  r+  r2  r:  r   r/   rI   r   _execution_devicer3  getr   r   r   r   r   r   rN   rJ   in_channelsr  r   r   r/  r  r%  r   r   r   rH  r6  progress_barr   r;  rp   rD  r   r4   r9   r   localsupdaterj   XLA_AVAILABLExm	mark_steprX   r   r   r   rx   r   maybe_free_model_hooksr)   )4rz   r   r  r  r;   r=   r>   r%  r   r   r   r   rU   rV   rW   r   r   r   r   r3  r4   r   r?  r	  rK   rA  r  r   r<   r   r   r  r   rG  rF  guidance_scale_tensornum_warmup_stepsrQ  r   tlatent_model_input
noise_prednoise_pred_uncondr3   callback_kwargsr   callback_outputsstep_idxr   r   rJ  has_nsfws4                                                       r8   __call__ StableDiffusionPipeline.__call__
  s   j ::j$/$4d;|
 %  C *-=?U,VWW1E1S1S. U 77 		  ,,YY%%11!4  77 		  ,,YY%%11!4 
 #%:%::EDYDY<YE 	"#.	
  .!1#'=$ *VS"9"9JJvt$<$<VJ&,,Q/J'' ?C>Y>Y>eD''++GT:ko 	 150B0B!,,'#9!nn 1C 
1
- ++!II'=&MNM'+B+N?? '2200L *<NN/*
&	
  $yy//;;&&.. 	
 !::9J
 !,0G0S \* 	 99..:$)LL1D1Dq1H$I$P$PQ[^sQs$t! ==%TYY5E5E5X5X > bgmmb4 
 y>,?..BVBV,VV!)n%89\!),1>> BFAaAaUYYy1}%=gn"4>>+>??)-)I)IJ\^_)`& "YY&*7"/+/+F+F&7 % '  
 339C9I9I!9L6%!2T5H5HO^oLo5p!pJ338M8MPS8S!2:aeavav!wJ ..--j!WmHYmglmnop'3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s* I**A9I/IqSTuX\XfXfXlXlNlpqNq '')+N0Ba0G#$(K#K 1g6 =LLNe - :j h&HHOOGhhoo.L.L$LZ_ktOuE '+&=&=eV]M`M`&a#E#E##"Vekk!n4N;KL;Kx(l;KNL$$00K`n0o 	##%+,,,EQabbU :9B Ms   H%[;[;(\;
\	)
r+  r2  r(  r#  r:  ru   r   r6  rx   rg   )NTNNNN)NNNNNr   )NNNNNN)<__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seq_optional_components_exclude_from_cpu_offloadr   r   r   r   r   r   r*   r
   r   boolri   r   r   r   r   r   rt   r   r   r   r   r   r   r
  r  float32r   r   propertyr%  r4   r   r   r3  r7  r;  no_gradr!   EXAMPLE_DOC_STRINGr   r   r   	Generatorr   r   r   r   r   r   rb  __static_attributes____classcell__)rH   s   @r8   rP   rP      s   B ES!1 2T 8<(,bQbQ $bQ !	bQ
 #bQ -bQ 5bQ .bQ 5bQ "&bQ bQT 049=&*  - !) 6 UOL 049=&*#'t5  -t5 !) 6t5 UOt5 C=t5l50+'Z'	!. # $+/CJ0 58emm.1@E	< $ $ & &   X X , , # #   ]]_12 )- $##%#" #;?/0MQ*.049=9=@D%* ;?"%#' 9B5Dcc49n%Dc Dc }	Dc
 !Dc 9Dc UDc Dc "%T#Y"78Dc  (}Dc Dc E%//43H"HIJDc %,,'Dc  -Dc !) 6Dc  ##56!Dc" "*$u||*<!=#Dc$ c]%Dc& 'Dc( !)c3h 8)Dc*  +Dc, C=-Dc. '(Cd+T124DF\\]
/Dc4 -1I5Dc 3 Dcr:   rP   )r>  rd  )FrC   typingr   r   r   r   r   r   r   	packagingr	   transformersr
   r   r   r   	callbacksr   r   configuration_utilsr   rx   r   r   loadersr   r   r   r   modelsr   r   r   models.lorar   
schedulersr   utilsr   r   r   r    r!   r"   r#   utils.torch_utilsr$   pipeline_utilsr&   r'   pipeline_outputr)   rR   r*   torch_xla.core.xla_modelcore	xla_modelrU  rT  
get_loggerre  rn   rq  r9   rt   r   r<   r   rN   rP   r@   r:   r8   <module>r     s    = =   h h A - D w w J J 9 3   . D : 8 ))MM			H	% "8 *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vvc"vcr:   