
    i                        d dl Z d dlmZmZmZmZmZ d dlZd dl	Z
d dlZd dlmZ d dlmZmZmZmZ ddlmZmZ ddlmZmZ ddlmZ dd	lmZ dd
lm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* ddl+m,Z,  e$       rd dl-m.c m/Z0 dZ1ndZ1 e%jd                  e3      Z4 e#       rd dl5Z5 e%jd                  e3      Z4dZ6d Z7d Z8d Z9 G d de*e      Z:y)    N)CallableDictListOptionalUnion)
functional)CLIPTextModelCLIPTokenizer"Qwen2_5_VLForConditionalGenerationQwen2VLProcessor   )MultiPipelineCallbacksPipelineCallback)PipelineImageInputVaeImageProcessor)KandinskyLoraLoaderMixin)AutoencoderKL)Kandinsky5Transformer3DModel)FlowMatchEulerDiscreteScheduler)is_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipeline   )KandinskyImagePipelineOutputTFa<  
    Examples:

        ```python
        >>> import torch
        >>> from diffusers import Kandinsky5I2IPipeline

        >>> # Available models:
        >>> # kandinskylab/Kandinsky-5.0-I2I-Lite-sft-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-I2I-Lite-pretrain-Diffusers

        >>> model_id = "kandinskylab/Kandinsky-5.0-I2I-Lite-sft-Diffusers"
        >>> pipe = Kandinsky5I2IPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
        >>> pipe = pipe.to("cuda")

        >>> prompt = "A cat and a dog baking a cake together in a kitchen."

        >>> output = pipe(
        ...     prompt=prompt,
        ...     negative_prompt="",
        ...     height=1024,
        ...     width=1024,
        ...     num_inference_steps=50,
        ...     guidance_scale=3.5,
        ... ).frames[0]
        ```
c                     t               rt        j                  |       } t        j                  t        j                  |             } | j                         S )z
    Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py

    Clean text using ftfy if available and unescape HTML entities.
    )r   ftfyfix_texthtmlunescapestriptexts    /home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/pipelines/kandinsky5/pipeline_kandinsky_i2i.pybasic_cleanr(   W   s;     }}T"==t,-D::<    c                 T    t        j                  dd|       } | j                         } | S )z
    Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py

    Normalize whitespace in text by replacing multiple spaces with single space.
    z\s+ )resubr$   r%   s    r'   whitespace_cleanr.   c   s&     66&#t$D::<DKr)   c                 .    t        t        |             } | S )z
    Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py

    Apply both basic cleaning and whitespace normalization to prompts.
    )r.   r(   r%   s    r'   prompt_cleanr0   n   s     K-.DKr)   c            .           e Zd ZdZdZg dZdededede	de
d	ed
ef fdZ	 	 	 	 d6dee   dee   deej&                     dedeej*                     f
dZ	 	 d7deeee   f   deej&                     deej*                     fdZ	 	 	 	 d8deeee   f   dej2                  dededeej&                     deej*                     fdZ	 	 	 	 	 	 	 	 d9dZ	 	 	 	 	 	 	 d:dedededededeej*                     deej&                     deeej8                  eej8                     f      deej2                     dej2                  fd Zed!        Zed"        Z ed#        Z! ejD                          e#e$      ddddd$d%dddddddddd&d'ddgdfdedeeee   f   d(eeeee   f      dee   dee   d)ed*e%dee   deeej8                  eej8                     f      deej2                     d+eej2                     d,eej2                     d-eej2                     d.eej2                     d/eej2                     d0eej2                     d1ee   d2e&d3eee'eee(gdf   e)e*f      d4ee   def*d5              Z+ xZ,S );Kandinsky5I2IPipelinea  
    Pipeline for image-to-image generation using Kandinsky 5.0.

    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.).

    Args:
        transformer ([`Kandinsky5Transformer3DModel`]):
            Conditional Transformer to denoise the encoded image latents.
        vae ([`AutoencoderKL`]):
            Variational Auto-Encoder Model [black-forest-labs/FLUX.1-dev
            (vae)](https://huggingface.co/black-forest-labs/FLUX.1-dev) to encode and decode videos to and from latent
            representations.
        text_encoder ([`Qwen2_5_VLForConditionalGeneration`]):
            Frozen text-encoder [Qwen2.5-VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct).
        tokenizer ([`AutoProcessor`]):
            Tokenizer for Qwen2.5-VL.
        text_encoder_2 ([`CLIPTextModel`]):
            Frozen [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel),
            specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
        tokenizer_2 ([`CLIPTokenizer`]):
            Tokenizer for CLIP.
        scheduler ([`FlowMatchEulerDiscreteScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
    z.text_encoder->text_encoder_2->transformer->vae)latentsprompt_embeds_qwenprompt_embeds_clipnegative_prompt_embeds_qwennegative_prompt_embeds_cliptransformervaetext_encoder	tokenizertext_encoder_2tokenizer_2	schedulerc           	          t         |           | j                  |||||||       d| _        d| _        d| _        t        | j
                        | _        g d| _        y )N)r8   r9   r:   r;   r<   r=   r>   a=  <|im_start|>system
You are a promt engineer. Based on the provided source image (first image) and target image (second image), create an interesting text prompt that can be used together with the source image to create the target image:<|im_end|><|im_start|>user{}<|vision_start|><|image_pad|><|vision_end|><|im_end|>7      )vae_scale_factor))   rC   )    )rE   rD   )      )rG   rF   )    )rI   rH   )	super__init__register_modulesprompt_template prompt_template_encode_start_idxvae_scale_factor_spatialr   image_processorresolutions)	selfr8   r9   r:   r;   r<   r=   r>   	__class__s	           r'   rK   zKandinsky5I2IPipeline.__init__   sn     	#%)# 	 	
  `02-()%0$B_B_`wr)   NrC   promptimagedevicemax_sequence_lengthdtypec           	          |xs | j                   }|xs | j                  j                  }t        |t              s|g}|D cg c]5  }|j                  |j                  d   dz  |j                  d   dz  f      7 }}|D cg c]  }| j                  j                  |       }}| j                  |z   }	| j                  ||ddd      d   }
|
j                  d	   |	kD  rt        |      D ]  \  }}|
|   }|| j                  j                  k(  j                         }||| j                  j                  k7     | j                  d
 }| j                  j                  |||z
  dz
  d       }t!        |      dkD  s|dt!        |        ||<   t"        j%                  d| d|         | j                  ||d|	ddd      j'                  |      } | j                  di |dddd   d	   dd| j                  df   }|d   dd| j                  df   }t)        j*                  |j                  d      d      }t-        j.                  |dd      j'                  t(        j0                        }|j'                  |      |fS c c}w c c}w )a  
        Encode prompt using Qwen2.5-VL text encoder.

        This method processes the input prompt through the Qwen2.5-VL model to generate text embeddings suitable for
        image generation.

        Args:
            prompt List[str]: Input list of prompts
            image (PipelineImageInput): Input list of images to condition the generation on
            device (torch.device): Device to run encoding on
            max_sequence_length (int): Maximum sequence length for tokenization
            dtype (torch.dtype): Data type for embeddings

        Returns:
            Tuple[torch.Tensor, torch.Tensor]: Text embeddings and cumulative sequence lengths
        r   r   r   Nptlongest)r&   imagesvideosreturn_tensorspadding	input_idsr   zXThe following part of your input was truncated because `max_sequence_length` is set to  z	 tokens: T)r&   r\   r]   
max_length
truncationr^   r_   )return_dictoutput_hidden_stateshidden_statesattention_mask)dim)r   r   )valuerX    )_execution_devicer:   rX   
isinstancelistresizesizerM   formatrN   r;   shape	enumerateimage_token_idsumdecodelenloggerwarningtotorchcumsumFpadint32)rR   rT   rU   rV   rW   rX   ip
full_textsmax_allowed_lenuntruncated_idsr&   tokensnum_image_tokensremoved_textinputsembedsrh   
cu_seqlenss                      r'   _encode_prompt_qwenz)Kandinsky5I2IPipeline._encode_prompt_qwen   s   0 14110**00%&GEEJK166!9>166!9>:;KK>DEd**11!4E
E??BUU.. ) 
    $6$Z0 
4(+$*dnn.K.K$K#P#P#R $..*G*G GHInInqst#~~44V<ORb<bef<f<h5ij|$q($()=C,=+=$>JqMNN/0	,I
 &   
 "V* 	 #"" 

!%
 	 	  !$"G"G"II	K   01!T5Z5Z5\2\]\\."4"4Q"7Q?
UU:vQ7:::M
yy++[ LEs   :J"Jc                     |xs | j                   }|xs | j                  j                  }| j                  |ddddd      j	                  |      } | j                  di |d   }|j	                  |      S )a  
        Encode prompt using CLIP text encoder.

        This method processes the input prompt through the CLIP model to generate pooled embeddings that capture
        semantic information.

        Args:
            prompt (Union[str, List[str]]): Input prompt or list of prompts
            device (torch.device): Device to run encoding on
            dtype (torch.dtype): Data type for embeddings

        Returns:
            torch.Tensor: Pooled text embeddings from CLIP
        M   Trc   rZ   )rc   rd   add_special_tokensr_   r^   pooler_outputrl   )rm   r<   rX   r=   r{   )rR   rT   rV   rX   r   pooled_embeds         r'   _encode_prompt_clipz)Kandinsky5I2IPipeline._encode_prompt_clip  s    ( 14112,,22!!#  " 
 "V* 	 +t**4V4_Eu%%r)   r   num_images_per_promptc                    |xs | j                   }|xs | j                  j                  }t        |t              s|g}t        |      }|D cg c]  }t        |       }}| j                  |||||      \  }	}
| j                  |||      }|	j                  d|d      }	|	j                  ||z  d|	j                  d         }	|j                  d|d      }|j                  ||z  d      }|
j                         }|j                  |      }t        j                  t        j                   dg|t        j"                        |j%                  d      g      }|	||fS c c}w )a  
        Encodes a single prompt (positive or negative) into text encoder hidden states.

        This method combines embeddings from both Qwen2.5-VL and CLIP text encoders to create comprehensive text
        representations for image generation.

        Args:
            prompt (`str` or `List[str]`):
                Prompt to be encoded.
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                Number of images to generate per prompt.
            max_sequence_length (`int`, *optional*, defaults to 1024):
                Maximum sequence length for text encoding. Must be less than 1024
            device (`torch.device`, *optional*):
                Torch device.
            dtype (`torch.dtype`, *optional*):
                Torch dtype.

        Returns:
            Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
                - Qwen text embeddings of shape (batch_size * num_images_per_prompt, sequence_length, embedding_dim)
                - CLIP pooled embeddings of shape (batch_size * num_images_per_prompt, clip_embedding_dim)
                - Cumulative sequence lengths (`cu_seqlens`) for Qwen embeddings of shape (batch_size *
                  num_images_per_prompt + 1,)
        )rT   rU   rV   rW   rX   )rT   rV   rX   r   ra   r   rV   rX   )rm   r:   rX   rn   ro   rx   r0   r   r   repeatviewrs   diffrepeat_interleaver|   cattensorr   r}   )rR   rT   rU   r   rW   rV   rX   
batch_sizer   r4   prompt_cu_seqlensr5   original_lengthsrepeated_lengthsrepeated_cu_seqlenss                  r'   encode_promptz#Kandinsky5I2IPipeline.encode_prompt'  s   D 14110**00&$'XF[
+12a,q/22 150H0H 3 1I 1
-- "55 6 
 066$a
 044..4F4L4LR4P

 066$a
 044ZBW5WY[\ -113+==!
 $ii\\1#fEKK@BRBYBYZ[B\]
 "#57JJJc 3s   Ec                      ||dkD  rt        d      |t        d      ||f j                  vrTdj                   j                  D cg c]  \  }}d| d| d c}}      }t        j	                  d| d	| d
| d       |Lt         fd|D              s8t        d j                   d|D cg c]  }| j                  vs| c}       |||
|||
t        d      ||	|||	|t        d      ||t        d      |7t        |t              s't        |t              st        dt        |             |9t        |t              s(t        |t              st        dt        |             yyyc c}}w c c}w )a  
        Validate input parameters for the pipeline.

        Args:
            prompt: Input prompt
            negative_prompt: Negative prompt for guidance
            image: Input image for conditioning
            height: Image height
            width: Image width
            prompt_embeds_qwen: Pre-computed Qwen prompt embeddings
            prompt_embeds_clip: Pre-computed CLIP prompt embeddings
            negative_prompt_embeds_qwen: Pre-computed Qwen negative prompt embeddings
            negative_prompt_embeds_clip: Pre-computed CLIP negative prompt embeddings
            prompt_cu_seqlens: Pre-computed cumulative sequence lengths for Qwen positive prompt
            negative_prompt_cu_seqlens: Pre-computed cumulative sequence lengths for Qwen negative prompt
            callback_on_step_end_tensor_inputs: Callback tensor inputs

        Raises:
            ValueError: If inputs are invalid
        NrC   z*max_sequence_length must be less than 1024z6`image` must be provided for image-to-image generation,()z'`height` and `width` have to be one of z
, but are z and z(. Dimensions will be resized accordinglyc              3   :   K   | ]  }|j                   v   y w)N)_callback_tensor_inputs).0krR   s     r'   	<genexpr>z5Kandinsky5I2IPipeline.check_inputs.<locals>.<genexpr>  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zuIf any of `prompt_embeds_qwen`, `prompt_embeds_clip`, or `prompt_cu_seqlens` is provided, all three must be provided.zIf any of `negative_prompt_embeds_qwen`, `negative_prompt_embeds_clip`, or `negative_prompt_cu_seqlens` is provided, all three must be provided.zProvide either `prompt` or `prompt_embeds_qwen` (and corresponding `prompt_embeds_clip` and `prompt_cu_seqlens`). Cannot leave all undefined.z2`prompt` has to be of type `str` or `list` but is z;`negative_prompt` has to be of type `str` or `list` but is )
ValueErrorrQ   joinry   rz   allr   rn   strro   type)rR   rT   negative_promptrU   heightwidthr4   r5   r6   r7   r   negative_prompt_cu_seqlens"callback_on_step_end_tensor_inputsrW   whresolutions_strr   s   `                 r'   check_inputsz"Kandinsky5I2IPipeline.check_inputs  sK   J */BT/IIJJ=UVV6?$"2"22!hhAQAQ'RA!A3as!'RSONN9/9J*U[T\\abgah  iQ  R .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 
 )-?-KO`Ol!)-?-GK\Kd 2  (3*6)5 ,3.6-5 2  >08 ` 
 z&#'>zRXZ^G_QRVW]R^Q_`aa&?C0OUY9ZZ[_`o[pZqrss :[0 '[ (S pHs   F
2FFr   num_channels_latentsr   r   	generatorr3   returnc
                 z   |	|	j                  ||      S |dt        |      | j                  z  t        |      | j                  z  |f}
t        |t              r)t        |      |k7  rt        dt        |       d| d      t        |
|||      }	| j                  j                  |||      j                  ||	      }t        j                         5  | j                  j                  |      j                  j                  |
      }|j!                  d      }t#        | j                  j$                  d      r#|| j                  j$                  j&                  z  }|j)                  ddddd      }t        j*                  |	|t        j,                  |	dddf         gd      }	ddd       |	S # 1 sw Y   |	S xY w)a2  
        Prepare initial latent variables for image-to-image generation.

        This method creates random noise latents with encoded image,

        Args:
            image (PipelineImageInput): Input image to condition the generation on
            batch_size (int): Number of images to generate
            num_channels_latents (int): Number of channels in latent space
            height (int): Height of generated image
            width (int): Width of generated image
            dtype (torch.dtype): Data type for latents
            device (torch.device): Device to create latents on
            generator (torch.Generator): Random number generator
            latents (torch.Tensor): Pre-existing latents to use

        Returns:
            torch.Tensor: Prepared latent tensor with encoded image
        Nr   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   rV   rX   )r   r   rk   )r   r   scaling_factorr   r      .ra   )r{   intrO   rn   ro   rx   r   r   rP   
preprocessr|   no_gradr9   encodelatent_distsample	unsqueezehasattrconfigr   permuter   	ones_like)rR   rU   r   r   r   r   rX   rV   r   r3   rs   image_tensorimage_latentss                r'   prepare_latentsz%Kandinsky5I2IPipeline.prepare_latents  s   > ::V5:99 K4888J$777 
 i&3y>Z+GA#i.AQ R&<'gi  u	&PUV ++66uVSX6Y\\]ckp\q]]_ 
	a HHOOL9EELLW`LaM)33A6M txx(89 -0N0N N *11!Q1a@Mii-QTVXWXVXQXIY9Z []_`G
	a 
	a s   CF00F:c                     | j                   S )z%Get the current guidance scale value.)_guidance_scalerR   s    r'   guidance_scalez$Kandinsky5I2IPipeline.guidance_scale'  s     ###r)   c                     | j                   S )z&Get the number of denoising timesteps.)_num_timestepsr   s    r'   num_timestepsz#Kandinsky5I2IPipeline.num_timesteps,  s     """r)   c                     | j                   S )z)Check if generation has been interrupted.)
_interruptr   s    r'   	interruptzKandinsky5I2IPipeline.interrupt1  s     r)   2   g      @pilTr   num_inference_stepsr   r4   r5   r6   r7   r   r   output_typere   callback_on_step_endr   c                    t        |t        t        f      r|j                  }|0|.t        |t              r|d   j
                  n|j
                  \  }}| j                  |||||||||||||       ||f| j                  vrU| j                  t        j                  | j                  D cg c]  }t        |d   |d   z  ||z  z
         c}         \  }}|| _        d| _        | j                  }| j                  j                  }|t        |t               rd}|g}n-|t        |t              rt#        |      }n|j$                  d   }|| j'                  ||||||      \  }}}| j(                  dkD  r|d}t        |t               r||gt#        |      z  n|g}n;t#        |      t#        |      k7  r$t+        d	t#        |       d
t#        |       d      || j'                  ||||||      \  }}}| j,                  j/                  ||       | j,                  j0                  }| j                  j2                  j4                  }| j7                  |||z  ||||||	|
	      }
t9        j:                  d|      t9        j:                  || j<                  z  dz  |      t9        j:                  || j<                  z  dz  |      g}t9        j:                  |j?                         jA                         jC                         |      }|At9        j:                  |j?                         jA                         jC                         |      nd}g d}d} t#        |      || j,                  jD                  z  z
  }!t#        |      | _#        | jI                  |      5 }"tK        |      D ]E  \  }}#| jL                  r|#jO                  d      jQ                  ||z        }$| j                  |
jS                  |      |jS                  |      |jS                  |      |$jS                  |      |||| d	      jT                  }%| j(                  dkD  rm|k| j                  |
jS                  |      |jS                  |      |jS                  |      |$jS                  |      |||| d	      jT                  }&|&||%|&z
  z  z   }%| j,                  jW                  |%ddddf   |#|
ddddddddd|f   d      d   |
ddddddddd|f<   |~i }'|D ]  }(tY               |(   |'|(<     || ||#|'      })|)j[                  d|
      }
|)j[                  d|      }|)j[                  d|      }|)j[                  d|      }|)j[                  d|      }|t#        |      dz
  k(  s'|dz   |!kD  r/|dz   | j,                  jD                  z  dk(  r|"j]                          t^        s2ta        jb                          H 	 ddd       |
ddddddddd|f   }
|dk7  r|
jS                  | jd                  j                        }
|
jg                  ||d|| j<                  z  || j<                  z  |      }
|
ji                  dddddd      }
|
jg                  ||z  ||| j<                  z  || j<                  z        }
|
| jd                  j2                  jj                  z  }
| jd                  jm                  |
      jT                  }| jn                  jq                  ||      }n|
}| js                          |s|fS tu        |      S c c}w # 1 sw Y   NxY w)a  
        The call function to the pipeline for image-to-image generation.

        Args:
            image (`PipelineImageInput`):
                The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
                instead. Ignored when not using guidance (`guidance_scale` < `1`).
            height (`int`):
                The height in pixels of the generated image.
            width (`int`):
                The width in pixels of the generated image.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps.
            guidance_scale (`float`, defaults to `5.0`):
                Guidance scale as defined in classifier-free guidance.
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                A torch generator to make generation deterministic.
            latents (`torch.Tensor`, *optional*):
                Pre-generated noisy latents.
            prompt_embeds_qwen (`torch.Tensor`, *optional*):
                Pre-generated Qwen text embeddings.
            prompt_embeds_clip (`torch.Tensor`, *optional*):
                Pre-generated CLIP text embeddings.
            negative_prompt_embeds_qwen (`torch.Tensor`, *optional*):
                Pre-generated Qwen negative text embeddings.
            negative_prompt_embeds_clip (`torch.Tensor`, *optional*):
                Pre-generated CLIP negative text embeddings.
            prompt_cu_seqlens (`torch.Tensor`, *optional*):
                Pre-generated cumulative sequence lengths for Qwen positive prompt.
            negative_prompt_cu_seqlens (`torch.Tensor`, *optional*):
                Pre-generated cumulative sequence lengths for Qwen negative prompt.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generated image.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`KandinskyImagePipelineOutput`].
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function that is called at the end of each denoising step.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function.
            max_sequence_length (`int`, defaults to `1024`):
                The maximum sequence length for text and image qwen encoding. Must be less than 1024

        Examples:

        Returns:
            [`~KandinskyImagePipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`KandinskyImagePipelineOutput`] is returned, otherwise a `tuple` is
                returned where the first element is a list with the generated images.
        Nr   )rT   r   rU   r   r   r4   r5   r6   r7   r   r   r   rW   r   F)rT   rU   r   rW   rV   rX         ? z9`negative_prompt` must have same length as `prompt`. Got z vs .)rV   )	rU   r   r   r   r   rX   rV   r   r3   r   )r   r   r   )totalT)	rg   encoder_hidden_statespooled_projectionstimestepvisual_rope_postext_rope_posscale_factorsparse_paramsre   )re   r3   r4   r5   r6   r7   latent   r   r   )r   )rU   );rn   r   r   tensor_inputsro   rq   r   rQ   npargminabsr   r   rm   r8   rX   r   rx   rs   r   r   r   r>   set_timesteps	timestepsr   in_visual_dimr   r|   arangerO   r   maxitemorderr   progress_barrt   r   r   r   r{   r   steplocalspopupdateXLA_AVAILABLExm	mark_stepr9   reshaper   r   rw   rP   postprocessmaybe_free_model_hooksr   )*rR   rU   rT   r   r   r   r   r   r   r   r3   r4   r5   r6   r7   r   r   r   re   r   r   rW   r   rV   rX   r   r   r   r   r   negative_text_rope_posr   r   num_warmup_stepsr   tr   pred_velocityuncond_pred_velocitycallback_kwargsr   callback_outputss*                                             r'   __call__zKandinsky5I2IPipeline.__call__6  s   f *-=?U,VW1E1S1S.>em-7t-DE!HMM%**ME6+11(C(C/'A/Q 3 	 	
 6?$"2"22 ,,		$JZJZ[Q3!qt?@[\ME6  .''  && *VS"9JXFJvt$<VJ+11!4J %HLHZHZ&;$7 I[ IE 24E $&"$/3/EKEW?"3c&k"A^m]n_%V4 OPSTcPdOeeijmntjuivvwx  +2&&.#.C,?%# '  e+-HJd 	$$%8$HNN,,	  $//66DD&&!$99!5 ' 

 LL6*LL4#@#@@AEfULL$"?"??1DVT
 %6%;%;%=%A%A%C%H%H%JSYZ *5 LL388:>>@EEGPVW 	 '  y>,?$..BVBV,VV!)n%89 ;	#\!), :#1>>;;q>00>S1ST !% 0 0")**U"3*<*?*?*F'9'<'<U'C%[[/$3"/!-"/ $ !1 
! &  &&,1L1X+/+;+;&-jj&7.I.L.LU.S+F+I+I%+P!)U!3(7&<%1&3$( ,< 
, f ) %9>]]qMq;r$rM=A^^=P=P!!Q$'GAq!Q@UAU@U4U,Vdi >Q >>1a$9%9$99: (3&(O? 9-3Xa[*9';D!Q'X$.229gFG)9)=)=>RTf)g&)9)=)=>RTf)g&2B2F2F57R3/ 3C2F2F57R3/ I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNu:#;	#| !Q1&;';&;;< ("jj0Goo%$777666$G ooaAq!Q7Goo22$$777666	G  > >>GHHOOG,33E((44U4TEE 	##%8O+%88A \~;	# ;	#s   +!\>
!H<]]])NNrC   N)NN)r   rC   NN)NNNNNNNN)   rC   rC   NNNN)-__name__
__module____qualname____doc__model_cpu_offload_seqr   r   r   r   r   r	   r
   r   rK   r   r   r   r   r|   rV   r   rX   r   r   r   Tensorr   r   	Generatorr   propertyr   r   r   r   r   EXAMPLE_DOC_STRINGfloatboolr   r   r   r   r  __classcell__)rS   s   @r'   r2   r2   x   s   4 Mx1x x 9	x
 $x &x #x 3x> /3)-#''+I,S	I, *+I, &	I,
 !I, $I,\ *.'+	"&c49n%"& &"& $	"&P &'#')-'+[Kc49n%[K ||[K  #	[K
 ![K &[K $[KH  $($(#'+/ \tD %''+)-MQ*.C!C C "	C
 C C $C &C E%//43H"HIJC %,,'C 
CJ $ $ # #   U]]_12 )-;? $##% #/0MQ*.5959>B>B48=A%*  9B#'1g9!g9 c49n%g9 "%T#Y"78	g9
 g9 }g9 !g9 g9  (}g9 E%//43H"HIJg9 %,,'g9 %U\\2g9 %U\\2g9 &.ell%;g9 &.ell%;g9  $ELL1!g9" %-U\\$:#g9$ c]%g9& 'g9( '(Cd+T124DF\\]
)g9. -1I/g90 !1g9 3 g9r)   r2   );r"   typingr   r   r   r   r   numpyr   regexr,   r|   torch.nnr   r~   transformersr	   r
   r   r   	callbacksr   r   rP   r   r   loadersr   modelsr   models.transformersr   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr	  ry   r    r  r(   r.   r0   r2   rl   r)   r'   <module>r'     s     8 8    $ k k A D / # ? 9  . . 9 ))MM			H	% 
		H	% :	g9-/G g9r)   