o
    Gi3                  
   @   s  d dl Z d dlmZmZ d dl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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l0m1Z1 ddl2m3Z3 ddl4m5Z5 e& rd dl6m7  m8Z9 dZ:ndZ:e';e<Z=dZ>	d&dej?dej@dB deAfddZB				d'deCdB deAejDB dB d eEeC dB d!eEeF dB fd"d#ZGG d$d% d%e.e/eeeee5	ZHdS )(    N)AnyCallable)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)StableDiffusionSafetyChecker   )PAGMixinTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import AutoPipelineForImage2Image
        >>> from diffusers.utils import load_image

        >>> pipe = AutoPipelineForImage2Image.from_pretrained(
        ...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
        ...     torch_dtype=torch.float16,
        ...     enable_pag=True,
        ... )
        >>> pipe = pipe.to("cuda")
        >>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"

        >>> init_image = load_image(url).convert("RGB")
        >>> prompt = "a photo of an astronaut riding a horse on mars"
        >>> image = pipe(prompt, image=init_image, pag_scale=0.3).images[0]
        ```
sampleencoder_output	generatorsample_modec                 C   sR   t | dr|dkr| j|S t | dr|dkr| j S t | dr%| jS td)Nlatent_distr'   argmaxlatentsz3Could not access latents of provided encoder_output)hasattrr+   r'   moder-   AttributeError)r(   r)   r*    r1   c/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/pipelines/pag/pipeline_pag_sd_img2img.pyretrieve_latentsO   s   

r3   num_inference_stepsdevice	timestepssigmasc                 K   s  |dur|durt d|dur>dtt| jj v }|s(t d| j d| jd||d| | j}t	|}||fS |durpdtt| jj v }|sZt 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.
    NzYOnly one of `timesteps` or `sigmas` can be passed. Please choose one to set custom valuesr6   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r6   r5   r7   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r7   r5   r5   r1   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r6   len)	schedulerr4   r5   r6   r7   kwargsaccepts_timestepsaccept_sigmasr1   r1   r2   retrieve_timesteps]   s2   rE   c                1       s  e Zd ZdZdZg dZdgZg dZ			dYd	ed
e	de
dededededededeee B f fddZ					dZdejdB dejdB dedB dedB fddZd[ddZdd Zdd Zd d! Z						d\d"d#Zd$d% Zd[d&d'Zd(ej fd)ejd*ed+ej!d,ejfd-d.Z"e#d/d0 Z$e#d1d2 Z%e#d3d4 Z&e#d5d6 Z'e#d7d8 Z(e#d9d: Z)e* e+e,ddd;d<ddd=dd>d?dddddd@dddddAgdBd?fdCeee B dDe-dEedFedB dGee dHee dIedB dJeee B dB dKedB dLedB dMej.eej. B dB dejdB dejdB dNe-dB dOeej dB dPedB dQedRe/ee0f dB dedSe1eegdf e2B e3B dB dTee dUedVef.dWdXZ4  Z5S )]!StableDiffusionPAGImg2ImgPipelineaY  
    Pipeline for text-guided image-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_encoderrG   )r-   prompt_embedsnegative_prompt_embedsNTmidvaetext_encoder	tokenizerunetrA   rH   rI   requires_safety_checkerpag_applied_layersc              
      s  t    |d ur3t|jdddkr3d| d|jj d}tdd|dd	 t|j}d|d< t||_|d ur\t|jd
ddu r\d| d}tdd|dd	 t|j}d|d
< t||_|d u rl|	rlt	
d| j d |d urx|d u rxtd|d uot|jdott|jjjtdk }|d uot|jdo|jjdk }|r|rd}tdd|dd	 t|j}d|d< t||_| j||||||||d t| dd rdt| jjjd  nd| _t| jd| _| j|	d | |
 d S )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)rM   rN   rO   rP   rA   rG   rH   rI   rM   r       )vae_scale_factor)rQ   )super__init__getattrconfigrS   r   dictr   _internal_dictloggerwarningr?   r8   r.   r   parserX   base_versionrY   register_modulesr@   rM   block_out_channelsr\   r   image_processorregister_to_configset_pag_applied_layers)selfrM   rN   rO   rP   rA   rG   rH   rI   rQ   rR   deprecation_message
new_configis_unet_version_less_0_9_0is_unet_sample_size_less_64r?   r1   r2   r^      sj   





	


(
z*StableDiffusionPAGImg2ImgPipeline.__init__rJ   rK   
lora_scale	clip_skipc
              
   C   s  |durt | tr|| _tst| j| nt| j| |dur't |tr'd}
n|dur5t |tr5t	|}
n|j
d }
|du rt | trJ| || j}| j|d| jjddd}|j}| j|ddd	j}|j
d
 |j
d
 krt||s| j|dd| jjd d
f }td| jj d|  t| jjdr| jjjr|j|}nd}|	du r| j|||d}|d }n| j|||dd}|d
 |	d   }| jj|}| jdur| jj}n| jdur| jj}n|j}|j||d}|j
\}}}|d|d}||| |d
}|r|du r|du rdg|
 }nC|dur8t |t |ur8t!dt | dt | dt |trB|g}n|
t	|kr\t"d| dt	| d| d|
 d	|}t | trk| || j}|j
d }| j|d|ddd}t| jjdr| jjjr|j|}nd}| j|j||d}|d }|r|j
d }|j||d}|d|d}||
| |d
}| jdurt | trtrt#| 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)paddingrt   
truncationreturn_tensorslongest)rv   rx   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)dtyper5    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   rN   r   strlistr@   shaper   maybe_convert_promptrO   model_max_length	input_idstorchequalbatch_decoderc   rd   r.   r`   r{   r|   to
text_modelfinal_layer_normr~   rP   repeatviewtype	TypeErrorr8   r   )rl   promptr5   num_images_per_promptdo_classifier_free_guidancenegative_promptrJ   rK   rr   rs   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textr|   prompt_embeds_dtypebs_embedseq_len_uncond_tokensrt   uncond_inputr1   r1   r2   encode_prompt+  s   +











z/StableDiffusionPAGImg2ImgPipeline.encode_promptc           
      C   s   t | j j}t|tjs| j|ddj}|j	||d}|rH| j|ddj
d }|j|dd}| jt|ddj
d }|j|dd}||fS | |j}|j|dd}t|}	||	fS )	Nru   rx   r5   r~   T)r}   r   dim)nextrI   r=   r~   r   r   TensorrH   pixel_valuesr   hidden_statesrepeat_interleave
zeros_likeimage_embeds)
rl   imager5   r   r}   r~   image_enc_hidden_statesuncond_image_enc_hidden_statesr   uncond_image_embedsr1   r1   r2   encode_image  s(   

z.StableDiffusionPAGImg2ImgPipeline.encode_imagec                 C   sl  g }|rg }|d u ret |ts|g}t|t| jjjkr/tdt| dt| jjj dt|| jjjD ],\}}	t |	t }
| 	||d|
\}}|
|d d d f  |rc|
|d d d f  q7n|D ]}|rw|d\}}|
| |
| qgg }t|D ]0\}}tj|g| dd}|rtj|| g| dd}tj||gdd}|j|d}|
| q|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   )r5   )r   r   r@   rP   encoder_hid_projimage_projection_layersr8   zipr   r   appendchunk	enumerater   catr   )rl   ip_adapter_imageip_adapter_image_embedsr5   r   r   r   negative_image_embedssingle_ip_adapter_imageimage_proj_layeroutput_hidden_statesingle_image_embedssingle_negative_image_embedsir1   r1   r2   prepare_ip_adapter_image_embeds  sH   


zAStableDiffusionPAGImg2ImgPipeline.prepare_ip_adapter_image_embedsc                 C   st   | j d u rd }||fS t|r| jj|dd}n| j|}| j|dd|}| j ||j|d\}}||fS )Npil)output_typeru   r   )images
clip_input)	rG   r   	is_tensorri   postprocessnumpy_to_pilrH   r   r   )rl   r   r5   r~   has_nsfw_conceptfeature_extractor_inputsafety_checker_inputr1   r1   r2   run_safety_checker)  s   



z4StableDiffusionPAGImg2ImgPipeline.run_safety_checkerc                 C   sX   dt t| jjj v }i }|r||d< dt t| jjj v }|r*||d< |S )Netar)   )r9   r:   r;   rA   stepr=   r>   )rl   r)   r   accepts_etaextra_step_kwargsaccepts_generatorr1   r1   r2   prepare_extra_step_kwargs8  s   z;StableDiffusionPAGImg2ImgPipeline.prepare_extra_step_kwargsc	           	         s  |dk s|dkrt d| |d ur0t fdd|D s0t d j d fdd	|D  |d urC|d urCt d
| d| d|d u rO|d u rOt d|d urft|tsft|tsft dt| |d ury|d uryt d| d| d|d ur|d ur|j|jkrt d|j d|j d|d ur|d urt d|d urt|tst dt| |d jdvrt d|d j dd S d S )Nr   r%   z2The value of strength should in [0.0, 1.0] but is c                 3   s    | ]}| j v V  qd S N_callback_tensor_inputs.0krl   r1   r2   	<genexpr>W  s    

zAStableDiffusionPAGImg2ImgPipeline.check_inputs.<locals>.<genexpr>z2`callback_on_step_end_tensor_inputs` has to be in z, but found c                    s   g | ]	}| j vr|qS r1   r   r   r   r1   r2   
<listcomp>[  s    zBStableDiffusionPAGImg2ImgPipeline.check_inputs.<locals>.<listcomp>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` r   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)	r8   allr   r   r   r   r   r   ndim)	rl   r   strengthr   rJ   rK   r   r   "callback_on_step_end_tensor_inputsr1   r   r2   check_inputsI  s`   
z.StableDiffusionPAGImg2ImgPipeline.check_inputsc                 C   sd   t t|| |}t|| d}| jj|| jj d  }t| jdr,| j|| jj  ||| fS )Nr   set_begin_index)minintmaxrA   r6   orderr.   r   )rl   r4   r   r5   init_timestept_startr6   r1   r1   r2   get_timesteps  s   z/StableDiffusionPAGImg2ImgPipeline.get_timestepsc                    s:  t tjtjjtfstdt j||d|| }j	d dkr)}nt  trAt
 |krAtdt
  d| dt  trj	d |k rf|j	d  dkrftjg|j	d   dd	nj	d |k r|j	d  dkrtd
j	d  d| d fddt|D }tj|dd	}n
tj d}jjj| }||j	d kr||j	d  dkrd| d|j	d  d}	tdd|	dd ||j	d  }
tj|g|
 dd	}n&||j	d kr||j	d  dkrtd
|j	d  d| dtj|gdd	}|j	}t| ||d}j|||}|}|S )NzK`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is r   r%   r   z/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.r   r   z'Cannot duplicate `image` of batch size z to effective batch_size  c              	      s0   g | ]}t j||d    | dqS )r%   r)   )r3   rM   encode)r   r   r)   r   rl   r1   r2   r     s    "zEStableDiffusionPAGImg2ImgPipeline.prepare_latents.<locals>.<listcomp>r   zYou have passed z# text prompts (`prompt`), but only a    initial images (`image`). Initial images are now duplicating to match the number of text prompts. Note that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update your script to pass as many initial images as text prompts to suppress this warning.zlen(prompt) != len(image)rT   FrU   z to z text prompts.)r)   r5   r~   )r   r   r   PILImager   r8   r   r   r   r@   r   ranger3   rM   r   r`   scaling_factorr   r   rA   	add_noise)rl   r   timestepr   r   r~   r5   r)   init_latentsrm   additional_image_per_promptr   noiser-   r1   r   r2   prepare_latents  sV   
     z1StableDiffusionPAGImg2ImgPipeline.prepare_latentsi   wembedding_dimr~   returnc                 C   s   t |jdks	J |d }|d }ttd|d  }ttj||d|  }||dddf |dddf  }tjt	|t
|gdd}|d dkrZtjj|d}|j|jd	 |fksfJ |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   )r@   r   r   logtensorexparanger   r   sincosnn
functionalpad)rl   r   r   r~   half_dimembr1   r1   r2   get_guidance_scale_embedding  s   &z>StableDiffusionPAGImg2ImgPipeline.get_guidance_scale_embeddingc                 C      | j S r   )_guidance_scaler   r1   r1   r2   guidance_scale     z0StableDiffusionPAGImg2ImgPipeline.guidance_scalec                 C   r  r   )
_clip_skipr   r1   r1   r2   rs     r  z+StableDiffusionPAGImg2ImgPipeline.clip_skipc                 C   s   | j dko| jjjd u S )Nr%   )r  rP   r`   time_cond_proj_dimr   r1   r1   r2   r     s   z=StableDiffusionPAGImg2ImgPipeline.do_classifier_free_guidancec                 C   r  r   )_cross_attention_kwargsr   r1   r1   r2   cross_attention_kwargs  r  z8StableDiffusionPAGImg2ImgPipeline.cross_attention_kwargsc                 C   r  r   )_num_timestepsr   r1   r1   r2   num_timesteps  r  z/StableDiffusionPAGImg2ImgPipeline.num_timestepsc                 C   r  r   )
_interruptr   r1   r1   r2   	interrupt
  r  z+StableDiffusionPAGImg2ImgPipeline.interruptg?2   g      @r%   g        r   r-   g      @r   r   r   r4   r6   r7   r  r   r   r   r)   r   r   r   return_dictr  callback_on_step_endr   	pag_scalepag_adaptive_scalec           2      C   sN  t |ttfr
|j}| |||||||| || _|| _|| _d| _|| _	|| _
|dur4t |tr4d}n|durBt |trBt|}n|jd }| j}| jdurV| jddnd}| j|||	| j||||| jd	\}}| jrv| ||| j}n
| jrt||g}|dus|dur| |||||	 | j}t|D ]1\}}d}| jr|d\}}| jr| ||| j}n| jrtj||gdd}||}|||< q| j|}trd	}n|}t | j!||||\}}| "|||\}}|dd #||	 }| $||||	|j%||} | &||
}!|dus|durd
|ind}"d}#| j'j(j)dur?t*| j+d #||	 }$| j,|$| j'j(j)dj|| j%d}#t||| j!j-  }%| jrZ| j'j.}&| j/| j0| jd t|| _1t2t||| j!j-  d}%| j3|d}'t|D ]\}}(| j4rqwt| g|jd | jd   })| j!5|)|(})|dur||"d
< | j'|)|(||#| j|"ddd }*| jr| 6|*| j| j+|(}*n| jr|*d\}+},|+| j+|,|+   }*| j!j7|*|(| fi |!ddid } |duri }-|D ]
}.t8 |. |-|.< q|| ||(|-}/|/9d| } |/9d|}|/9d|}|t|d ks-|d |%kr1|d | j!j- dkr1|':  tr8t;<  qwW d   n	1 sEw   Y  |dksj| j=j>| | j=j(j? d|dd }| @|||j%\}}0n| }d}0|0du r|dg|jd  }1ndd |0D }1| jjA|||1d}| B  | jr| j'C|& |s||0fS tD||0dS )u  
        The call function to the pipeline for generation.

        Args:
            prompt (`str` or `list[str]`, *optional*):
                The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
            image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `list[torch.Tensor]`, `list[PIL.Image.Image]`, or `list[np.ndarray]`):
                `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
                numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
                or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
                list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
                latents as `image`, but if passing latents directly it is not encoded again.
            strength (`float`, *optional*, defaults to 0.8):
                Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
                starting point and more noise is added the higher the `strength`. The number of denoising steps depends
                on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
                process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
                essentially ignores `image`.
            num_inference_steps (`int`, *optional*, defaults to 50):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference. This parameter is modulated by `strength`.
            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.
            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).
            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.
        FNr%   r   scale)rJ   rK   rr   rs   r    r   cpur   )r   r   )rR   r   )total)encoder_hidden_statestimestep_condr  added_cond_kwargsr  r  r-   rJ   rK   latent)r  r)   Tc                 S   s   g | ]}| qS r1   r1   )r   has_nsfwr1   r1   r2   r   K  s    z>StableDiffusionPAGImg2ImgPipeline.__call__.<locals>.<listcomp>)r   do_denormalize)r   nsfw_content_detected)Er   r   r
   tensor_inputsr   r  r  r  r  
_pag_scale_pag_adaptive_scaler   r   r@   r   _execution_devicer  getr   r   rs   do_perturbed_attention_guidance%_prepare_perturbed_attention_guidancer   r   r   r   r   r   ri   
preprocessXLA_AVAILABLErE   rA   r   r   r   r~   r   rP   r`   r  r   r  r
  r   attn_processors_set_pag_attn_processorrR   r  r   progress_barr  scale_model_input#_apply_perturbed_attention_guidancer   localspopupdatexm	mark_steprM   decoder   r   r   maybe_free_model_hooksset_attn_processorr#   )2rl   r   r   r   r4   r6   r7   r  r   r   r   r)   rJ   rK   r   r   r   r  r  rs   r  r   r  r  r   r5   text_encoder_lora_scaler   r   r   timestep_devicelatent_timestepr-   r   r!  r   guidance_scale_tensornum_warmup_stepsoriginal_attn_procr1  tlatent_model_input
noise_prednoise_pred_uncondnoise_pred_textcallback_kwargsr   callback_outputsr   r$  r1   r1   r2   __call__  sD  x






 
$
6
2
z*StableDiffusionPAGImg2ImgPipeline.__call__)NTrL   )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^   r   r   floatr   r   r   r   r   r   r   r   r   float32r~   r
  propertyr  rs   r   r  r  r  no_gradr   EXAMPLE_DOC_STRINGr   	Generatorra   r   r   r   r
   rI  __classcell__r1   r1   rq   r2   rF      s0   	!	

j	

 
8.
>
C







	
rF   )Nr'   )NNNN)Ir:   typingr   r   	PIL.Imager   r   	packagingr   transformersr   r   r   r   	callbacksr
   r   configuration_utilsr   ri   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_modelr7  r.  
get_loggerrJ  rc   rV  r   rW  r   r3   r   r5   r   rR  rE   rF   r1   r1   r1   r2   <module>   sn   $	





;