
    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
Z
d dlmZmZmZmZmZmZ ddlmZmZ ddlmZmZmZmZ ddlmZmZ ddlmZ dd	lm Z m!Z!m"Z"m#Z#m$Z$m%Z% dd
l&m'Z' ddl(m)Z) ddl*m+Z+  e!       rd dl,m-c m.Z/ dZ0ndZ0 e"jb                  e2      Z3dZ4g dZ5	 	 	 	 d#de6de6de7de7fdZ8	 	 	 	 d$dee6   deee9e
jt                  f      deee6      deee7      fdZ;	 d%de
jx                  dee
jz                     de9fd Z> G d! d"e)eeee      Z?y)&    N)AnyCallableDictListOptionalUnion)CLIPImageProcessorCLIPTextModelCLIPTokenizerCLIPVisionModelWithProjectionT5EncoderModelT5TokenizerFast   )PipelineImageInputVaeImageProcessor)FluxIPAdapterMixinFluxLoraLoaderMixinFromSingleFileMixinTextualInversionLoaderMixin)AutoencoderKLFluxTransformer2DModel)FlowMatchEulerDiscreteScheduler)USE_PEFT_BACKENDis_torch_xla_availableloggingreplace_example_docstringscale_lora_layersunscale_lora_layers)randn_tensor   )DiffusionPipeline   )FluxPipelineOutputTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import FluxKontextPipeline
        >>> from diffusers.utils import load_image

        >>> pipe = FluxKontextPipeline.from_pretrained(
        ...     "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png"
        ... ).convert("RGB")
        >>> prompt = "Make Pikachu hold a sign that says 'Black Forest Labs is awesome', yarn art style, detailed, vibrant colors"
        >>> image = pipe(
        ...     image=image,
        ...     prompt=prompt,
        ...     guidance_scale=2.5,
        ...     generator=torch.Generator().manual_seed(42),
        ... ).images[0]
        >>> image.save("output.png")
        ```
))     )    )    )  p  )   0  )@    )p    )  P  )   r4   )r3   r2   )r1   r0   )r/   r.   )r-   r,   )r+   r*   )r)   r(   )r'   r&   )r%   r$   base_seq_lenmax_seq_len
base_shift	max_shiftc                 <    ||z
  ||z
  z  }|||z  z
  }| |z  |z   }|S N )image_seq_lenr5   r6   r7   r8   mbmus           i/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/flux/pipeline_flux_kontext.pycalculate_shiftrA   g   s;     
Z	K,$>?AQ%%A		Q	B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 valuesrE   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)rE   rD   rF   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)rF   rD   rD   r;   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__rE   len)	schedulerrC   rD   rE   rF   kwargsaccepts_timestepsaccept_sigmass           r@   retrieve_timestepsrU   u   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''	)))rB   encoder_output	generatorsample_modec                     t        | d      r |dk(  r| j                  j                  |      S t        | d      r|dk(  r| j                  j                         S t        | d      r| j                  S t        d      )Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrrZ   r[   moder]   AttributeError)rV   rW   rX   s      r@   retrieve_latentsra      st     ~}-+2I))00;;		/K84K))..00		+%%%RSSrB   c            ?       0    e Zd ZdZdZddgZddgZ	 	 dNded	ed
e	de
dededededef fdZ	 	 	 	 	 dOdeeee   f   dededeej.                     deej0                     f
dZ	 	 dPdeeee   f   dedeej.                     fdZ	 	 	 	 	 	 	 dQdeeee   f   deeeee   f      deej.                     dedeej6                     deej6                     dedee   fdZd Zd Z	 	 	 	 	 	 	 	 dRdZ e!d         Z"e!d!        Z#e!d"        Z$d#ejJ                  d$ejL                  fd%Z'd& Z(d' Z)d( Z*d) Z+	 	 dNd#eejJ                     d*ed+ed,ed-edej0                  dej.                  d$eeejL                  eejL                     f      deejJ                     fd.Z,e-d/        Z.e-d0        Z/e-d1        Z0e-d2        Z1e-d3        Z2 ejf                          e4e5      dddddd4ddd5dd6dddddddddddd7d8dddgdd9d8fd#ee6   deeee   f   deeeee   f      d:eeee   f   d;eeeee   f      d<ed,ee   d-ee   d=ed>eee      d?edee   d$eeejL                  eejL                     f      deej6                     deej6                     deej6                     d@ee6   dAeeejJ                        dBee6   dCeeejJ                        dDeej6                     dEeej6                     dFee   dGe7dHee8ee9f      dIee:eee8gdf      dJee   dedKedLe7f<dM              Z; xZ<S )SFluxKontextPipelinea  
    The Flux Kontext pipeline for image-to-image and text-to-image generation.

    Reference: https://bfl.ai/announcements/flux-1-kontext-dev

    Args:
        transformer ([`FluxTransformer2DModel`]):
            Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
        scheduler ([`FlowMatchEulerDiscreteScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKL`]):
            Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
        text_encoder ([`CLIPTextModel`]):
            [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.
        text_encoder_2 ([`T5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
        tokenizer (`CLIPTokenizer`):
            Tokenizer of class
            [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
        tokenizer_2 (`T5TokenizerFast`):
            Second Tokenizer of class
            [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
    z=text_encoder->text_encoder_2->image_encoder->transformer->vaeimage_encoderfeature_extractorr]   prompt_embedsNrQ   vaetext_encoder	tokenizertext_encoder_2tokenizer_2transformerc
                    t         
|           | j                  |||||||||		       t        | dd       r/dt	        | j
                  j                  j                        dz
  z  nd| _        t        | dd       r | j
                  j                  j                  nd| _	        t        | j                  dz        | _        t        | d      r"| j                  | j                  j                  nd	| _        d
| _        y )N)	rg   rh   rj   ri   rk   rl   rQ   rd   re   rg   r    r"         )vae_scale_factorri   M      )super__init__register_modulesgetattrrP   rg   configblock_out_channelsrp   latent_channelsr   image_processorr^   ri   model_max_lengthtokenizer_max_lengthdefault_sample_size)selfrQ   rg   rh   ri   rj   rk   rl   rd   re   rO   s             r@   rt   zFluxKontextPipeline.__init__   s     	%)##'/ 	 
	
 W^^bdikoVpc$((//*L*L&MPQ&Q Rvw CJ$PUW[B\txx>>bd0$BWBWZ[B[\/6t[/IdnnNhDNN++np 	! $' rB   r"      promptnum_images_per_promptmax_sequence_lengthrD   dtypec           	         |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}t        |      }t        | t              r| j                  || j                        }| j                  |d|dddd      }|j                  }| j                  |dd      j                  }	|	j                  d   |j                  d   k\  rbt        j                  ||	      sL| j                  j                  |	d d | j                  d	z
  df         }
t        j!                  d
| d|
        | j#                  |j%                  |      d      d   }| j"                  j                  }|j%                  ||      }|j                  \  }}}|j'                  d	|d	      }|j)                  ||z  |d      }|S )N
max_lengthTFpt)paddingr   
truncationreturn_lengthreturn_overflowing_tokensreturn_tensorslongestr   r   r"   zXThe following part of your input was truncated because `max_sequence_length` is set to  	 tokens: output_hidden_statesr   r   rD   )_execution_devicerh   r   
isinstancestrrP   r   maybe_convert_promptrk   	input_idsshapetorchequalbatch_decoder|   loggerwarningrj   torepeatview)r~   r   r   r   rD   r   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textrf   _seq_lens                 r@   _get_t5_prompt_embedsz)FluxKontextPipeline._get_t5_prompt_embeds  s    14110**00'4&&[
d78..vt7G7GHF&& *&+ ' 
 %..**69UY*Zdd  $(<(<R(@@UcetIu++88DLeLehiLilnLnIn9opLNN'(	,A
 ++N,=,=f,E\a+bcde##))%((uV(D%++7A &,,Q0EqI%**:8M+MwXZ[rB   c           	      d   |xs | j                   }t        |t              r|gn|}t        |      }t        | t              r| j                  || j                        }| j                  |d| j                  dddd      }|j                  }| j                  |dd      j                  }|j                  d   |j                  d   k\  rlt        j                  ||      sV| j                  j                  |d d | j                  d	z
  df         }t        j                  d
| j                   d|        | j                  |j!                  |      d      }	|	j"                  }	|	j!                  | j                  j$                  |      }	|	j'                  d	|      }	|	j)                  ||z  d      }	|	S )Nr   TFr   )r   r   r   r   r   r   r   r   r   r"   z\The following part of your input was truncated because CLIP can only handle sequences up to r   r   r   )r   r   r   rP   r   r   ri   r|   r   r   r   r   r   r   r   rh   r   pooler_outputr   r   r   )
r~   r   r   rD   r   r   r   r   r   rf   s
             r@   _get_clip_prompt_embedsz+FluxKontextPipeline._get_clip_prompt_embeds9  s    1411'4&&[
d78..vt~~FFnn 00&+ % 
 %....SW.Xbb  $(<(<R(@@UcetIu>>66q$JcJcfgJgjlJlGl7mnLNN--.i~G )).*;*;F*CZ_)` &33%((t/@/@/F/Fv(V &,,Q0EF%**:8M+MrRrB   prompt_2pooled_prompt_embeds
lora_scalec	                 l   |xs | j                   }|gt        | t              rW|| _        | j                  t
        rt        | j                  |       | j                  t
        rt        | j                  |       t        |t              r|gn|}|D|xs |}t        |t              r|gn|}| j                  |||      }| j                  ||||      }| j                  ,t        | t              rt
        rt        | j                  |       | j                  ,t        | t              rt
        rt        | j                  |       | j                  | j                  j                  n| j                  j                  }	t        j                  |j                   d   d      j#                  ||	      }
|||
fS )a  

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            prompt_2 (`str` or `List[str]`, *optional*):
                The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
                used in all text-encoders
            device: (`torch.device`):
                torch device
            num_images_per_prompt (`int`):
                number of images that should be generated per prompt
            prompt_embeds (`torch.FloatTensor`, *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.
            pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
                Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
                If not provided, pooled text embeddings will be generated from `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.
        )r   rD   r   )r   r   r   rD   r"   r   rD   r   )r   r   r   _lora_scalerh   r   r   rj   r   r   r   r   r   rl   r   zerosr   r   )r~   r   r   rD   r   rf   r   r   r   r   text_idss              r@   encode_promptz!FluxKontextPipeline.encode_promptf  s   @ 1411 !j7J&K)D   ,1A!$"3"3Z@"".3C!$"5"5zB'4&& )6H%/#%>zHH $(#?#?&; $@ $ 
 !66&;$7	 7 M ($ 349I#D$5$5zB*$ 349I#D$7$7D+/+<+<+H!!''dN^N^NdNd;;}2215q9<<FRW<X2H<<rB   c                 P   t        | j                  j                               j                  }t	        |t
        j                        s| j                  |d      j                  }|j                  ||      }| j                  |      j                  }|j                  |d      }|S )Nr   )r   r   r   dim)nextrd   rM   r   r   r   Tensorre   pixel_valuesr   image_embedsrepeat_interleave)r~   imagerD   r   r   r   s         r@   encode_imagez FluxKontextPipeline.encode_image  s    T''2245;;%.**5*FSSEe4))%0==#556KQR5SrB   c                    g }|t        |t              s|g}t        |      | j                  j                  j
                  k7  r9t        dt        |       d| j                  j                  j
                   d      |D ]-  }| j                  ||d      }|j                  |d d d f          / nt        |t              s|g}t        |      | j                  j                  j
                  k7  r9t        dt        |       d| j                  j                  j
                   d      |D ]  }|j                  |        g }|D ]@  }t        j                  |g|z  d      }|j                  |	      }|j                  |       B |S )
NzK`ip_adapter_image` must have same length as the number of IP Adapters. Got z images and z IP Adapters.r"   zR`ip_adapter_image_embeds` must have same length as the number of IP Adapters. Got z image embeds and r   r   )rD   )r   listrP   rl   encoder_hid_projnum_ip_adaptersrH   r   appendr   catr   )r~   ip_adapter_imageip_adapter_image_embedsrD   r   r   single_ip_adapter_imagesingle_image_embedss           r@   prepare_ip_adapter_image_embedsz3FluxKontextPipeline.prepare_ip_adapter_image_embeds  s    "*.5$4#5 #$(8(8(I(I(Y(YY abefvbwax  yE  FJ  FV  FV  Fg  Fg  Fw  Fw  Ex  xE  F  ,< B'&*&7&78OQWYZ&[###$7a$@AB 5t<+B*C'*+t/?/?/P/P/`/`` hil  nE  jF  iG  GY  Z^  Zj  Zj  Z{  Z{  ZK  ZK  YL  LY  Z  (? 9###$789 #%#/ 	@"'))-@,ADY,Y_`"a"5"8"8"8"G#**+>?	@
 '&rB   c           
      r    | j                   dz  z  dk7  s| j                   dz  z  dk7  r,t        j                  d j                   dz   d| d| d       |Lt         fd|D              s8t	        d j
                   d	|D cg c]  }| j
                  vs| c}       ||t	        d
| d| d      ||t	        d| d| d      ||t	        d      |7t        |t              s't        |t              st	        dt        |             |7t        |t              s't        |t              st	        dt        |             ||t	        d| d| d      ||t	        d| d| d      ||	t	        d      ||
t	        d      ||dkD  rt	        d|       y y c c}w )Nr    r   z-`height` and `width` have to be divisible by z	 but are  and z(. Dimensions will be resized accordinglyc              3   :   K   | ]  }|j                   v   y wr:   )_callback_tensor_inputs).0kr~   s     r@   	<genexpr>z3FluxKontextPipeline.check_inputs.<locals>.<genexpr>  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.z Cannot forward both `prompt_2`: 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 z4`prompt_2` has to be of type `str` or `list` but is z'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: z)Cannot forward both `negative_prompt_2`: zIf `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`.zIf `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`.r   z8`max_sequence_length` cannot be greater than 512 but is )
rp   r   r   allrH   r   r   r   r   type)r~   r   r   heightwidthnegative_promptnegative_prompt_2rf   negative_prompt_embedsr   negative_pooled_prompt_embeds"callback_on_step_end_tensor_inputsr   r   s   `             r@   check_inputsz FluxKontextPipeline.check_inputs  s    T**Q./14AVAVYZAZ8[_`8`NN?@U@UXY@Y?ZZcdjckkpqvpw  x`  a .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  !m&?28*<RS`Ra b0 0  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa!:h+DZX`bfMgSTXYaTbScdee&+A+M9/9J K*++]_  */E/Q;<M;N O*++]_ 
 $)=)E U  "-2O2W y  */BS/HWXkWlmnn 0I*U pHs   F4F4c                 4   t        j                  ||d      }|d   t        j                  |      d d d f   z   |d<   |d   t        j                  |      d d d f   z   |d<   |j                  \  }}}|j	                  ||z  |      }|j                  ||      S )Nr   ).r"   ).r    r   )r   r   aranger   reshaper   )	r   r   r   rD   r   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelss	            r@   _prepare_latent_image_idsz-FluxKontextPipeline._prepare_latent_image_ids,  s     !;;vua8#3F#;ell6>RSTVZSZ>[#[ #3F#;ell5>QRVXYRY>Z#Z RbRhRhO 57O+33"%::<T
  ""&">>rB   c                     | j                  |||dz  d|dz  d      } | j                  dddddd      } | j                  ||dz  |dz  z  |dz        } | S )Nr    r      r"   r      )r   permuter   )r]   r   num_channels_latentsr   r   s        r@   _pack_latentsz!FluxKontextPipeline._pack_latents;  sl     ,,z+?1aQVZ[Q[]^_//!Q1a3//*v{uz.JL`cdLderB   c                    | j                   \  }}}dt        |      |dz  z  z  }dt        |      |dz  z  z  }| j                  ||dz  |dz  |dz  dd      } | j                  dddddd      } | j	                  ||dz  ||      } | S )Nr    r   r   r   r"   r   )r   intr   r   r   )r]   r   r   rp   r   num_patcheschannelss          r@   _unpack_latentsz#FluxKontextPipeline._unpack_latentsD  s     -4MM)
K c&k&6&:;<SZ$4q$89:,,z6Q;
HPQMSTVWX//!Q1a3//*h5.A65QrB   r   rW   c                    t        |t              rkt        |j                  d         D cg c]2  }t	        | j
                  j                  |||dz          ||   d      4 }}t        j                  |d      }n't	        | j
                  j                  |      |d      }|| j
                  j                  j                  z
  | j
                  j                  j                  z  }|S c c}w )Nr   r"   r\   )rW   rX   r   )r   r   ranger   ra   rg   encoder   r   rw   shift_factorscaling_factor)r~   r   rW   iimage_latentss        r@   _encode_vae_imagez%FluxKontextPipeline._encode_vae_imageU  s    i& u{{1~. !q1q51A!BiXYlhpqM  "IIm;M,TXX__U-CyfnoM&)E)EEIgIggs   7C)c                 8    | j                   j                          y)z
        Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
        compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
        N)rg   enable_slicingr~   s    r@   enable_vae_slicingz&FluxKontextPipeline.enable_vae_slicingd      
 	!rB   c                 8    | j                   j                          y)z
        Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rg   disable_slicingr   s    r@   disable_vae_slicingz'FluxKontextPipeline.disable_vae_slicingl  s    
 	  "rB   c                 8    | j                   j                          y)a  
        Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
        compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
        processing larger images.
        N)rg   enable_tilingr   s    r@   enable_vae_tilingz%FluxKontextPipeline.enable_vae_tilingt  s     	 rB   c                 8    | j                   j                          y)z
        Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rg   disable_tilingr   s    r@   disable_vae_tilingz&FluxKontextPipeline.disable_vae_tiling}  r   rB   r   r   r   r   c
                 :   t        |t              r)t        |      |k7  rt        dt        |       d| d      dt	        |      | j
                  dz  z  z  }dt	        |      | j
                  dz  z  z  }||||f}
d x}}|?|j                  ||      }|j                  d   | j                  k7  r| j                  ||      }n|}||j                  d   kD  rC||j                  d   z  dk(  r.||j                  d   z  }t        j                  |g|z  d	      }n^||j                  d   kD  r4||j                  d   z  dk7  rt        d
|j                  d    d| d      t        j                  |gd	      }|j                  dd  \  }}| j                  |||||      }| j                  ||dz  |dz  ||      }d|d<   | j                  ||dz  |dz  ||      }|	%t        |
|||      }	| j                  |	||||      }	n|	j                  ||      }	|	|||f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   rW   r   r   z'Cannot duplicate `image` of batch size z to z text prompts.).r   )rW   rD   r   )r   r   rP   rH   r   rp   r   r   ry   r   r   r   r   r   r   )r~   r   r   r   r   r   r   rD   rW   r]   r   r   	image_idsadditional_image_per_promptimage_latent_heightimage_latent_width
latent_idss                    r@   prepare_latentsz#FluxKontextPipeline.prepare_latents  s    i&3y>Z+GA#i.AQ R&<'gi  c&kd&;&;a&?@ASZD$9$9A$=>?165A$((	HHF%H8E{{1~!5!55 $ 6 6Ui 6 X %M//22zMDWDWXYDZ7Z^_7_.8M<O<OPQ<R.R+ %		=/<W*W]^ _m11!44mFYFYZ[F\9\`a9a =m>Q>QRS>T=UUYZdYeest  !&		=/q A6C6I6I!"6M3!3 ..z+?ATVhM 66/146HA6MvW\I !"If33J!UVWZY_afg
?"5IfTYZG((*>RTZ\abGjjej<Gz9<<rB   c                     | j                   S r:   )_guidance_scaler   s    r@   guidance_scalez"FluxKontextPipeline.guidance_scale  s    ###rB   c                     | j                   S r:   )_joint_attention_kwargsr   s    r@   joint_attention_kwargsz*FluxKontextPipeline.joint_attention_kwargs  s    +++rB   c                     | j                   S r:   )_num_timestepsr   s    r@   num_timestepsz!FluxKontextPipeline.num_timesteps  s    """rB   c                     | j                   S r:   )_current_timestepr   s    r@   current_timestepz$FluxKontextPipeline.current_timestep  s    %%%rB   c                     | j                   S r:   )
_interruptr   s    r@   	interruptzFluxKontextPipeline.interrupt  s    rB         ?   g      @pilTi   r   r   true_cfg_scalerC   rF   r  r   r   negative_ip_adapter_image negative_ip_adapter_image_embedsr   r   output_typereturn_dictr  callback_on_step_endr   max_area_auto_resizec                   C |xs | j                   | j                  z  }|xs | j                   | j                  z  }||} }||z  Ct        |Cz  dz        }t        |Cz  dz        }| j                  dz  }!||!z  |!z  }||!z  |!z  }||k7  s|| k7  rt        j	                  d| d| d       | j                  ||||||||||||       || _        || _        d| _        d| _	        |t        |t              rd	}"n-|t        |t              rt        |      }"n|j                  d
   }"| j                  }#| j                   | j                   j#                  dd      nd}$|duxs
 |duxr |du}%|d	kD  xr |%}&| j%                  |||||#|||$      \  }}}'|&r| j%                  |||||#|||$      \  }}}(|t        |t&        j(                        r|j+                  d	      | j,                  k(  st        |t              r|d
   n|})| j.                  j1                  |)      \  }*}+|+|*z  C|rt3        Cfdt4        D              \  },}+}*|+|!z  |!z  }+|*|!z  |!z  }*| j.                  j7                  ||*|+      }| j.                  j9                  ||*|+      }| j:                  j<                  j>                  dz  }-| jA                  ||"|z  |-|||jB                  |#||	      \  }}.}/}0|0t'        jD                  |/|0gd
      }/|
tG        jH                  dd	|	z  |	      n|
}
|j                  d	   }1tK        |1| jL                  j<                  j#                  dd      | jL                  j<                  j#                  dd      | jL                  j<                  j#                  dd      | jL                  j<                  j#                  dd            }2tO        | jL                  |	|#|
|2      \  }3}	tQ        t        |3      |	| jL                  jR                  z  z
  d
      }4t        |3      | _*        | j:                  j<                  jV                  rGt'        jX                  d	g||#t&        jZ                        }5|5j]                  |j                  d
         }5nd}5||Q|O|MtG        j^                  ||dftF        j`                        }|g| j:                  jb                  jd                  z  }nT|R|P||LtG        j^                  ||dftF        j`                        }|g| j:                  jb                  jd                  z  }| j                   i | _        d}6d}7||| jg                  |||#|"|z        }6||| jg                  |||#|"|z        }7| jL                  ji                  d
       | jk                  |	      5 }8tm        |3      D ]I  \  }9}:| jn                  r|:| _        |6|6| j                  d<   |};|.t'        jD                  ||.gd	      };|:j]                  |j                  d
         jq                  |jB                        }<| j;                  |;|<dz  |5|||'|/| j                   d	      d
   }=|=ddd|j+                  d	      f   }=|&r`|7|7| j                  d<   | j;                  |;|<dz  |5||(|/| j                   d	      d
   }>|>ddd|j+                  d	      f   }>|>||=|>z
  z  z   }=|jB                  }?| jL                  js                  |=|:|d       d
   }|jB                  |?k7  r9t&        jt                  jv                  jy                         r|jq                  |?      }|Hi }@|D ]  }At{               |A   @|A<     || |9|:@      }B|Bj}                  d!|      }|Bj}                  d"|      }|9t        |3      d	z
  k(  s'|9d	z   |4kD  r/|9d	z   | jL                  jR                  z  d
k(  r|8j                          t        s6t        j                          L 	 ddd       d| _        |d#k(  r|}n| j                  |||| j                        }|| j                  j<                  j                  z  | j                  j<                  j                  z   }| j                  j                  |d       d
   }| j.                  j                  ||$      }| j                          |s|fS t        |%      S # 1 sw Y   xY w)&a+"  
        Function invoked when calling the pipeline for generation.

        Args:
            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.
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            prompt_2 (`str` or `List[str]`, *optional*):
                The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
                will be used instead.
            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 `true_cfg_scale` is
                not greater than `1`).
            negative_prompt_2 (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
                `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
            true_cfg_scale (`float`, *optional*, defaults to 1.0):
                When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
            height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
                The height in pixels of the generated image. This is set to 1024 by default for the best results.
            width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
                The width in pixels of the generated image. This is set to 1024 by default for the best results.
            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.
            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 3.5):
                Embedded guidance scale is enabled by setting `guidance_scale` > 1. Higher `guidance_scale` encourages
                a model to generate images more aligned with prompt at the expense of lower image quality.

                Guidance-distilled models approximates true classifier-free guidance for `guidance_scale` > 1. Refer to
                the [paper](https://huggingface.co/papers/2210.03142) to learn more.
            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*):
                One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
                to make generation deterministic.
            latents (`torch.FloatTensor`, *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 will ge generated by sampling using the supplied random `generator`.
            prompt_embeds (`torch.FloatTensor`, *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.
            pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
                Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
                If not provided, pooled text embeddings will be generated from `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)`. If not
                provided, embeddings are computed from the `ip_adapter_image` input argument.
            negative_ip_adapter_image:
                (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
            negative_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)`. If not
                provided, embeddings are computed from the `ip_adapter_image` input argument.
            negative_prompt_embeds (`torch.FloatTensor`, *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.
            negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
                Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
                input argument.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generate image. Choose between
                [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
            joint_attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, *optional*):
                A function that calls at the end of each denoising steps during the inference. The function is called
                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.
            max_sequence_length (`int` defaults to 512):
                Maximum sequence length to use with the `prompt`.
            max_area (`int`, defaults to `1024 ** 2`):
                The maximum area of the generated image in pixels. The height and width will be adjusted to fit this
                area while maintaining the aspect ratio.

        Examples:

        Returns:
            [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
            is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
            images.
              ?r    z6Generation `height` and `width` have been adjusted to r   z to fit the model requirements.)r   r   rf   r   r   r   r   r   NFr"   r   scale)r   r   rf   r   rD   r   r   r   c              3   L   K   | ]  \  }}t        ||z  z
        ||f  y wr:   )abs)r   whaspect_ratios      r@   r   z/FluxKontextPipeline.__call__.<locals>.<genexpr>  s/      3:>!QSA-.153s   !$r   r   r  base_image_seq_len   max_image_seq_len   r7   r8   ffffff?)rF   r?   r   r   )r   )totalr   i  )	hidden_statestimestepguidancepooled_projectionsencoder_hidden_statestxt_idsimg_idsr  r!  )r!  r]   rf   latent)r   )images)Kr}   rp   roundr   r   r   r  r  r  r  r   r   r   rP   r   r   r  getr   r   r   sizery   rz   get_default_height_widthminPREFERRED_KONTEXT_RESOLUTIONSresize
preprocessrl   rw   in_channelsr
  r   r   nplinspacerA   rQ   rU   maxorderr  guidance_embedsfullfloat32expandr   uint8r   r   r   set_begin_indexprogress_bar	enumerater  r   stepbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   rg   r   r   decodepostprocessmaybe_free_model_hooksr#   )Dr~   r   r   r   r   r   r  r   r   rC   rF   r  r   rW   r]   rf   r   r   r   r  r  r   r   r   r!  r  r"  r   r   r#  r$  original_heightoriginal_widthmultiple_ofr   rD   r   has_neg_promptdo_true_cfgr   negative_text_idsimgimage_heightimage_widthr   r   r   r	  r  r<   r?   rE   num_warmup_stepsr5  r   negative_image_embedsrO  r   tlatent_model_inputr4  
noise_predneg_noise_predlatents_dtypecallback_kwargsr   callback_outputsr,  sD                                                                      @r@   __call__zFluxKontextPipeline.__call__  s	   ` K433d6K6KKI11D4I4II*0%v~x,.367</C78++a/${2;&4_$(?NNHPUV[U\\{|
 	+/'#9!5*G/Q 3 	 	
  .'=$!% *VS"9JJvt$<VJ&,,Q/J'' ?C>Y>Y>eD''++GT:ko 	 )4 
"$.\3PX\3\ 	 %q(;^
 '!5"7 3!  	
		
  
 ""&*4%B&;$7% # 		&-! j&E%**UV-[_[o[oJo(5%(5C(,(<(<(U(UVY(Z%L+&5L/2 3B_3 0,; &4{BK';6DL((//|[QE((33E<UE  $//66BBaG8<8L8L.. 
9
5
I  J	#:BJ TZSaS!&9"9;NOgma(NN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 *<NN*
&	& s9~0CdnnFZFZ0ZZ\]^!)n ""22zz1#~fEMMZHw}}Q'78HH(,C,O%-2R2Z(*%1C288(T%)B(CdFVFVFgFgFwFw(w%&+B+J%15U5a!xx(:"((K 01D4D4D4U4U4e4ee&&.+-D( $'+B+N?? '22	L %04T4`$($H$H)022	%! 	&&q)%89 C	#\!), B#1>>)*&+NZD001JK%," ,).G]3KQR)S&88GMM!$4588G!--"4%_%';*7$&+/+F+F % . 
 

 (+<W\\!_+<(<=
,8Rg445NO%)%5%5&8!)D!)+H.D 1 */3/J/J$) &6 
& 
&N &4A7Ha7H4H%IN!/.JQ_D_2`!`J !(..--j!WRW-XYZ[==M1~~))668")**]";'3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNEB#C	#J "&("E**7FE4CXCXYG!?!??488??C_C__GHHOOGO?BE((44U4TE 	##%8O!//kC	# C	#s   +I c-cc%)NN)Nr"   r   NN)r"   N)NNr"   NNr   N)NNNNNNNN)=__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr   r   r   r
   r   r   r   r   r   r	   rt   r   r   r   r   r   r   rD   r   r   r   FloatTensorfloatr   r   r   r   staticmethodr   r   r   r   	Generatorr   r   r   r   r  r
  propertyr  r  r  r  r  no_gradr   EXAMPLE_DOC_STRINGr   boolr   r   r   rp  __classcell__)rO   s   @r@   rc   rc      sU   4 \+-@A(/: 8<04!'2!' !' $	!'
 !!' '!' %!' ,!' 5!' .!'L )-%&#&)-'+/c49n%/  #/ !	/
 &/ $/j &')-	*c49n%*  #* &	*` 59)-%&59<@#&&*M=c49n%M= 5d3i01M= &	M=
  #M=   1 12M= 'u'8'89M= !M= UOM=`	"'V #!&*+/ CoJ ? ?    u||  "#!"  NR*.<=%<= <= "	<=
 <= <= {{<= <= E%//43H"HIJ<= %,,'<=| $ $ , , # # & &   U]]_12 /3(,4815=A # $##%(, #/0MQ/359<@9=@DBFIM>BEI%* ;?KO9B#&!?V0*+V0 c49n%V0 5d3i01	V0
 sDI~.V0 $E#tCy.$9:V0 V0 V0 }V0 !V0 e%V0 V0  (}V0 E%//43H"HIJV0 %++,V0    1 12!V0" 'u'8'89#V0$ ##56%V0& "*$u||*<!='V0( $,,>#?)V0* +343E*F+V0, !)):): ;-V0. (00A0A'B/V00 c]1V02 3V04 !)c3h 85V06 'xc40@$0F'GH7V08 -1I9V0: !;V0< =V0> ?V0 3 V0rB   rc   )r.  r0  r&  r1  )NNNN)Nr[   )@rJ   typingr   r   r   r   r   r   numpyrE  r   transformersr	   r
   r   r   r   r   rz   r   r   loadersr   r   r   r   modelsr   r   
schedulersr   utilsr   r   r   r   r   r   utils.torch_utilsr   pipeline_utilsr!   pipeline_outputr#   torch_xla.core.xla_modelcore	xla_modelrY  rX  
get_loggerrq  r   r}  rA  r   rx  rA   r   rD   rU   r   rz  ra   rc   r;   rB   r@   <module>r     so    = =    E p p ; 9  . . / ))MM 
		H	% 4! . 

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*z ck
TLL
T-5eoo-F
T\_
Tp0p0rB   