
    bi                        d dl Z d dlmZmZmZmZmZmZ d dlZd dl	m
Z
 d dlmZmZmZmZ ddl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 dd
lmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4  e%       rd dl5m6c m7Z8 dZ9ndZ9 e&jt                  e;      Z<dZ=ddZ>	 	 	 	 d dee?   deee@ej                  f      deee?      deeeB      fdZC G d de-e.eeeee4	      ZDy)!    N)AnyCallableDictListOptionalUnion)version)CLIPImageProcessorCLIPTextModelCLIPTokenizerCLIPVisionModelWithProjection   )
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)StableDiffusionSafetyChecker   )PAGMixinTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import AutoPipelineForText2Image

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

        >>> prompt = "a photo of an astronaut riding a horse on mars"
        >>> image = pipe(prompt, pag_scale=0.3).images[0]
        ```
c                     |j                  t        t        d|j                              d      }| j                  t        t        d| j                              d      }| ||z  z  }||z  d|z
  | z  z   } | S )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         b/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/pag/pipeline_pag_sd.pyrescale_noise_cfgr8   G   s    " ""tE!_5I5I,J'KUY"ZHmmU1inn%= >mMG#x''9: #66!>N:NR[9[[I    num_inference_stepsdevice	timestepssigmasc                    ||t        d      |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS  | j                  |fd	|i| | j                  }||fS )a  
    Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
    custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

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

    Returns:
        `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
        second element is the number of inference steps.
    zYOnly one of `timesteps` or `sigmas` can be passed. Please choose one to set custom 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           r7   retrieve_timestepsrM   b   s   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	 	M)FMfM''	!)n ))) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	 	GvfGG''	!)n ))) 	 	 3MFMfM''	)))r9   c            5           e Zd ZdZdZg dZdgZg dZ	 	 	 dGded	e	d
e
dededededededeeee   f   f fdZ	 	 	 	 	 dHdeej.                     deej.                     dee   dee   fdZdIdZd Zd Zd Z	 	 	 	 	 	 dJdZdIdZ dejB                  fdej.                  ded ejD                  d!ej.                  fd"Z#e$d#        Z%e$d$        Z&e$d%        Z'e$d&        Z(e$d'        Z)e$d(        Z*e$d)        Z+ ejX                          e-e.      dddd*ddd+dd,d-ddddddd.ddd-ddd/gd0d-fd1eeee   f   d2ee   d3ee   d4ed5ee   d6ee   d7ed8eeeee   f      d9ee   d:ed;eeej^                  eej^                     f      d/eej.                     deej.                     deej.                     d<ee0   d=eeej.                        d>ee   d?ed@ee1ee2f      dAedee   dBee3eee1gdf      dCee   dDedEef2dF              Z4 xZ5S )KStableDiffusionPAGPipelinea?  
    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/runwayml/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_encoderrP   )latentsprompt_embedsnegative_prompt_embedsNTvaetext_encoder	tokenizerunetrI   rQ   rR   requires_safety_checkerpag_applied_layersc           
      :   t         |           |pt        |j                  dd      dk7  rVd| d|j                  j                   d}t        dd|d	       t        |j                        }d|d<   t        |      |_        |Xt        |j                  d
d      du r?d| d}t        dd|d	       t        |j                        }d|d
<   t        |      |_        |%|	r#t        j                  d| j                   d       ||t        d      |d uxrt t        |j                  d      xr\ t        j                  t        j                  |j                  j                         j"                        t        j                  d      k  }|d uxr1 t        |j                  d      xr |j                  j$                  dk  }|r=|r;d}t        dd|d	       t        |j                        }d|d<   t        |      |_        | j'                  ||||||||       t        | dd       r/dt)        | j*                  j                  j,                        dz
  z  nd| _        t1        | j.                        | _        | j5                  |	       | j7                  |
       y )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!=1z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 
- runwayml/stable-diffusion-v1-5 
- runwayml/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)rV   rW   rX   rY   rI   rP   rQ   rR   rV   r#      )vae_scale_factor)rZ   )super__init__getattrconfigr]   r   dictr   _internal_dictloggerwarningrG   r@   hasattrr	   parser`   base_versionra   register_modulesrH   rV   block_out_channelsrd   r   image_processorregister_to_configset_pag_applied_layers)selfrV   rW   rX   rY   rI   rP   rQ   rR   rZ   r[   deprecation_message
new_configis_unet_version_less_0_9_0is_unet_sample_size_less_64rG   s                  r7   rf   z#StableDiffusionPAGPipeline.__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 	# em!DeI`I`ceIe 	$ &*E/   &1DTYZdkk*J(*J}%",Z"8D%)/' 	 		
 W^^bdikoVpc$((//*L*L&MPQ&Q Rvw0$BWBWX8OP##$67r9   rT   rU   
lora_scale	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)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`.)$
isinstancer   _lora_scaler   r   rW   r    strr.   rH   shaper   maybe_convert_promptrX   model_max_length	input_idstorchequalbatch_decoderk   rl   rm   rh   r   r   to
text_modelfinal_layer_normr   rY   repeatviewtype	TypeErrorr@   r!   )ru   promptr;   num_images_per_promptdo_classifier_free_guidancenegative_promptrT   rU   rz   r{   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textr   prompt_embeds_dtypebs_embedseq_len_uncond_tokensr}   uncond_inputs                          r7   encode_promptz(StableDiffusionPAGPipeline.encode_prompt0  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4r9   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   r+   )nextrR   rE   r   r   r   TensorrQ   pixel_valuesr   hidden_statesrepeat_interleave
zeros_likeimage_embeds)
ru   imager;   r   r   r   image_enc_hidden_statesuncond_image_enc_hidden_statesr   uncond_image_embedss
             r7   encode_imagez'StableDiffusionPAGPipeline.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4r9   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 z images and z IP Adapters.r(   r#   r   r   )r;   )r   r.   rH   rY   encoder_hid_projimage_projection_layersr@   zipr   r   appendchunk	enumerater   catr   )ru   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                 r7   prepare_ip_adapter_image_embedsz:StableDiffusionPAGPipeline.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#**+>?	@ '&r9   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)	rP   r   	is_tensorrr   postprocessnumpy_to_pilrQ   r   r   )ru   r   r;   r   has_nsfw_conceptfeature_extractor_inputsafety_checker_inputs          r7   run_safety_checkerz-StableDiffusionPAGPipeline.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# &&&r9   c                 V   dt        t        j                  | j                  j                        j
                  j                               v }i }|r||d<   dt        t        j                  | j                  j                        j
                  j                               v }|r||d<   |S )Neta	generator)rA   rB   rC   rI   steprE   rF   )ru   r   r   accepts_etaextra_step_kwargsaccepts_generators         r7   prepare_extra_step_kwargsz4StableDiffusionPAGPipeline.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*  r9   c           
          |dz  dk7  s|dz  dk7  rt        d| d| d      |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        d      |	Ut        |	t              st        dt        |	             |	d   j                  dvrt        d|	d   j                   d      y y c c}w )Nrc   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   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0kru   s     r7   	<genexpr>z:StableDiffusionPAGPipeline.check_inputs.<locals>.<genexpr>d  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` zProvide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined.z:`ip_adapter_image_embeds` has to be of type `list` but is )r      zF`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is D)
r@   r   intr   allr   r   r.   r   r0   )ru   r   heightwidthcallback_stepsr   rT   rU   r   r   "callback_on_step_end_tensor_inputsr   s   `           r7   check_inputsz'StableDiffusionPAGPipeline.check_inputsO  s    A:?eai1nVW]V^^cdicjjklmm%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  ',C,O ^  #.5t< PQUVmQnPop  )+00> \]tuv]w]|]|\}}~  ? /E pHs   GGc	                 T   ||t        |      | j                  z  t        |      | j                  z  f}	t        |t              r)t	        |      |k7  rt        dt	        |       d| d      |t        |	|||      }n|j                  |      }|| j                  j                  z  }|S )Nz/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.)r   r;   r   )
r   rd   r   r.   rH   r@   r"   r   rI   init_noise_sigma)
ru   r   num_channels_latentsr   r   r   r;   r   rS   r   s
             r7   prepare_latentsz*StableDiffusionPAGPipeline.prepare_latents  s     K4000J$///	
 i&3y>Z+GA#i.AQ R&<'gi 
 ?"5IfTYZGjj(G DNN;;;r9   i   wembedding_dimr   returnc                 l   t        |j                        dk(  sJ |dz  }|dz  }t        j                  t        j                  d            |dz
  z  }t        j
                  t        j                  ||      | z        }|j                  |      dddf   |dddf   z  }t        j                  t        j                  |      t        j                  |      gd      }|dz  dk(  r*t        j                  j                  j                  |d      }|j                  |j                  d	   |fk(  sJ |S )
a  
        See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

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

        Returns:
            `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
        r(   g     @@r#   g     @)r   Nr   )r   r(   r   )rH   r   r   logtensorexparanger   r   sincosnn
functionalpad)ru   r   r   r   half_dimembs         r7   get_guidance_scale_embeddingz7StableDiffusionPAGPipeline.get_guidance_scale_embedding  s   " 177|q   J A%iiW-.(Q,?iiXU;sdBCdd5k!T'"Sq\1ii338a@1!((%%))#v6CyyQWWQZ7777
r9   c                     | j                   S r   )_guidance_scaleru   s    r7   guidance_scalez)StableDiffusionPAGPipeline.guidance_scale  s    ###r9   c                     | j                   S r   )_guidance_rescaler  s    r7   r3   z+StableDiffusionPAGPipeline.guidance_rescale  s    %%%r9   c                     | j                   S r   )
_clip_skipr  s    r7   r{   z$StableDiffusionPAGPipeline.clip_skip      r9   c                 h    | j                   dkD  xr" | j                  j                  j                  d u S )Nr(   )r  rY   rh   time_cond_proj_dimr  s    r7   r   z6StableDiffusionPAGPipeline.do_classifier_free_guidance  s.    ##a'WDII,<,<,O,OSW,WWr9   c                     | j                   S r   )_cross_attention_kwargsr  s    r7   cross_attention_kwargsz1StableDiffusionPAGPipeline.cross_attention_kwargs  s    +++r9   c                     | j                   S r   )_num_timestepsr  s    r7   num_timestepsz(StableDiffusionPAGPipeline.num_timesteps  s    """r9   c                     | j                   S r   )
_interruptr  s    r7   	interruptz$StableDiffusionPAGPipeline.interrupt  r  r9   2   g      @r(           r   rS   g      @r   r   r   r:   r<   r=   r	  r   r   r   r   r   r   r   return_dictr  r3   callback_on_step_endr   	pag_scalepag_adaptive_scalec                    |xs- | j                   j                  j                  | j                  z  }|xs- | j                   j                  j                  | j                  z  }| j	                  |||d||||||
       || _        || _        || _        || _        d| _	        || _
        || _        |t        |t              rd}n-|t        |t              rt        |      }n|j                   d   }| j"                  }| j$                  | j$                  j'                  dd      nd}| j)                  |||	| j*                  ||||| j,                  	      \  }}| j.                  r| j1                  ||| j*                        }n#| j*                  rt3        j4                  ||g      }||| j7                  |||||	z  | j*                        }t9        |      D ]  \  }}d}| j*                  r|j;                  d      \  }}| j.                  r| j1                  ||| j*                        }n%| j*                  rt3        j4                  ||gd      }|j=                  |      }|||<    t?        | j@                  ||||      \  }}| j                   j                  jB                  } | jE                  ||	z  | |||jF                  |||      }| jI                  ||
      }!||d	|ind}"d}#| j                   j                  jJ                  t3        jL                  | jN                  dz
        jQ                  ||	z        }$| jS                  |$| j                   j                  jJ                  
      j=                  ||jF                        }#t        |      || j@                  jT                  z  z
  }%| j.                  r=| j                   jV                  }&| jY                  | jZ                  | j*                         t        |      | _.        | j_                  |      5 }'t9        |      D ]  \  }}(| j`                  rt3        j4                  |g|j                   d   |j                   d   z  z        })| j@                  jc                  |)|(      })| j                  |)|(||#| j$                  |"d      d   }*| j.                  r-| je                  |*| j*                  | jN                  |(d      \  }*}+n5| j*                  r)|*j;                  d      \  },}+|,| jN                  |+|,z
  z  z   }*| j*                  r'| jf                  dkD  rti        |*+| jf                        }* | j@                  jj                  |*|(|fi |!ddid   }|Zi }-|D ]  }.tm               |.   |-|.<     || ||(|-      }/|/jo                  d|      }|/jo                  d|      }|/jo                  d|      }|t        |      dz
  k(  s'|dz   |%kD  r/|dz   | j@                  jT                  z  dk(  r|'jq                          tr        stu        jv                           	 ddd       |dk(  sc| jx                  j{                  || jx                  j                  j|                  z  d|      d   }0| j                  |0||jF                        \  }0}1n|}0d}1|1dg|0j                   d   z  }2n|1D 3cg c]  }3|3  }2}3| j                  j                  |0||2      }0| j                          | j.                  r| j                   j                  &       |s|0|1fS t        |0|1      S # 1 sw Y   xY wc c}3w )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.
            pag_scale (`float`, *optional*, defaults to 3.0):
                The scale factor for the perturbed attention guidance. If it is set to 0.0, the perturbed attention
                guidance will not be used.
            pag_adaptive_scale (`float`, *optional*, defaults to 0.0):
                The adaptive scale factor for the perturbed attention guidance. If it is set to 0.0, `pag_scale` is
                used.

        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.
        NFr(   r   scale)rT   rU   rz   r{   r#   r   r   )r   r   )r[   r   )total)encoder_hidden_statestimestep_condr  added_cond_kwargsr  Tr  )r3   r  rS   rT   rU   latent)r  r   )r   do_denormalize)r   nsfw_content_detected)ErY   rh   ra   rd   r   r  r  r  r  r  
_pag_scale_pag_adaptive_scaler   r   r.   rH   r   _execution_devicer  getr   r   r{   do_perturbed_attention_guidance%_prepare_perturbed_attention_guidancer   r   r   r   r   r   rM   rI   in_channelsr   r   r   r  r   r	  r   r  orderattn_processors_set_pag_attn_processorr[   r  progress_barr  scale_model_input#_apply_perturbed_attention_guidancer3   r8   r   localspopupdateXLA_AVAILABLExm	mark_steprV   decodescaling_factorr   rr   r   maybe_free_model_hooksset_attn_processorr&   )4ru   r   r   r   r:   r<   r=   r	  r   r   r   r   rS   rT   rU   r   r   r   r  r  r3   r{   r  r   r  r  r   r;   rz   r   r   r   r   r   r%  r$  guidance_scale_tensornum_warmup_stepsoriginal_attn_procr3  tlatent_model_input
noise_predr2   noise_pred_uncondcallback_kwargsr   callback_outputsr   r   r'  has_nsfws4                                                       r7   __call__z#StableDiffusionPAGPipeline.__call__  s   v O499++77$:O:OOM))558M8MM 	"#.	
  .!1#'=$##5  *VS"9JJvt$<VJ&,,Q/J'' ?C>Y>Y>eD''++GT:ko 	 150B0B!,,'#9!nn 1C 
1
-- // FF5t7W7WM --!II'=}&MNM'+B+N&*&J&J '2200'# $--D#E :<(,%33:F:L:LQ:O7)<77#'#M#M$&;T=]=]$L 55#(99.C\-RXY#ZL+v6-9'*: *<NN/F*
&	&
  $yy//;;&&.. 	
 !::9cJ
 !,0G0S 45 	 99..:$)LL1D1Dq1H$I$P$PQ[^sQs$t! ==%TYY5E5E5X5X > bgmmb4 
 y>,?$..BVBV,VV//!%!:!:((#'#:#:,0,L,L )  ")n%89 4	#\!), 3#1>> &+YYyM<O<OPQ<RV]VcVcdeVf<f/g%h"%)^^%E%EFXZ[%\" "YY&*7"/+/+F+F&7 % '  
 77262Z2Z"D$D$DdFYFY[\^b3/J 559C9I9I!9L6%!2T5H5HO^oLo5p!pJ338M8MPS8S!2:aeavav!wJ .$..--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* I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNg3#4	#l 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 	##%//II(();<+,,,EQabb_4	# 4	#D Ms   H\7\7
]7])NTmid)NNNNNr   )NNNNNN)6__name__
__module____qualname____doc__model_cpu_offload_seq_optional_components_exclude_from_cpu_offloadr   r   r   r   r   r   r'   r
   r   boolr   r   r   rf   r   r   r   floatr   r   r   r   r   r   r   r   float32r   r  propertyr	  r3   r{   r   r  r  r  no_gradr   EXAMPLE_DOC_STRING	Generatorr   r   r   r   rJ  __classcell__)rG   s   @r7   rO   rO      sc   B ES!1 2T 8<(,49a8a8 $a8 !	a8
 #a8 -a8 5a8 .a8 5a8 "&a8 "#tCy.1a8T 049=&*#'t5  -t5 !) 6t5 UOt5 C=t5n52+'\'!0 # $+/CL0 58emm.1@E	< $ $ & &   X X , , # #   U]]_12 )- $##%#" #;?/0MQ*.049=9=@D%* ;?"%#'KO9B$'5Kcc49n%Kc Kc }	Kc
 !Kc 9Kc UKc Kc "%T#Y"78Kc  (}Kc Kc E%//43H"HIJKc %,,'Kc  -Kc !) 6Kc  ##56!Kc" "*$u||*<!=#Kc$ c]%Kc& 'Kc( !)c3h 8)Kc*  +Kc, C=-Kc. 'xc40@$0F'GH/Kc0 -1I1Kc2 3Kc4 "5Kc 3 Kcr9   rO   )r  )NNNN)ErB   typingr   r   r   r   r   r   r   	packagingr	   transformersr
   r   r   r   configuration_utilsr   rr   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%    stable_diffusion.pipeline_outputr&   stable_diffusion.safety_checkerr'   	pag_utilsr)   torch_xla.core.xla_modelcore	xla_modelr:  r9  
get_loggerrL  rk   rX  r8   r   r   r;   rT  rM   rO   r?   r9   r7   <module>rm     s    = =   h h - D w w J J 9 3   . D L J  ))MM			H	% $: *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vYc"Ycr9   