
    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Z4	 	 	 	 dde5de5de6de6fdZ7	 	 	 	 ddee5   deee8e
jr                  f      deee5      deee6      f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   )FluxPipelineOutputTFaV  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import FluxPipeline

        >>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
        >>> pipe.to("cuda")
        >>> prompt = "A cat holding a sign that says hello world"
        >>> # Depending on the variant being used, the pipeline call will slightly vary.
        >>> # Refer to the pipeline documentation for more details.
        >>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
        >>> image.save("flux.png")
        ```
base_seq_lenmax_seq_len
base_shift	max_shiftc                 <    ||z
  ||z
  z  }|||z  z
  }| |z  |z   }|S N )image_seq_lenr$   r%   r&   r'   mbmus           a/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/flux/pipeline_flux.pycalculate_shiftr0   I   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 valuesr4   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r4   r3   r5   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r5   r3   r3   r*   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r4   len)	schedulerr2   r3   r4   r5   kwargsaccepts_timestepsaccept_sigmass           r/   retrieve_timestepsrD   W   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''	)))r1   c            9           e Zd ZdZdZddgZddgZ	 	 dGded	ed
e	de
dededededef fdZ	 	 	 	 	 dHdeeee   f   dededeej.                     deej0                     f
dZ	 	 dIdeeee   f   dedeej.                     fdZ	 	 	 	 	 	 	 dJd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	 	 	 	 	 	 	 	 dKdZ e!d         Z"e!d!        Z#e!d"        Z$d# Z%d$ Z&d% Z'd& Z(	 dLd'Z)e*d(        Z+e*d)        Z,e*d*        Z-e*d+        Z.e*d,        Z/ ej`                          e1e2      ddddd-ddd.dd/dddddddddddd0d1dddgdfdeeee   f   deeeee   f      d2eeee   f   d3eeeee   f      d4ed5ee   d6ee   d7ed8eee      d9edee   d:eeejf                  eejf                     f      deej6                     deej6                     deej6                     d;ee4   d<eeejj                        d=ee4   d>eeejj                        d?eej6                     d@eej6                     dAee   dBe6dCee7ee8f      dDee9eee7gdf      dEee   def6dF              Z: xZ;S )MFluxPipelinea  
    The Flux pipeline for text-to-image generation.

    Reference: https://blackforestlabs.ai/announcing-black-forest-labs/

    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_extractorlatentsprompt_embedsNr@   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        | j                  dz        | _
        t        | d      r"| j                  | j                  j                  nd| _        d	| _        y )
N)	rK   rL   rN   rM   rO   rP   r@   rG   rH   rK   r    r"      )vae_scale_factorrM   M      )super__init__register_modulesgetattrr?   rK   configblock_out_channelsrS   r   image_processorhasattrrM   model_max_lengthtokenizer_max_lengthdefault_sample_size)selfr@   rK   rL   rM   rN   rO   rP   rG   rH   r>   s             r/   rW   zFluxPipeline.__init__   s     	%)##'/ 	 
	
 W^^bdikoVpc$((//*L*L&MPQ&Q Rvw  1$BWBWZ[B[\/6t[/IdnnNhDNN++np 	! $' r1   r"      promptnum_images_per_promptmax_sequence_lengthr3   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)paddingrh   
truncationreturn_lengthreturn_overflowing_tokensreturn_tensorslongestrj   rn   r"   zXThe following part of your input was truncated because `max_sequence_length` is set to  	 tokens: output_hidden_statesr   rf   r3   )_execution_devicerL   rf   
isinstancestrr?   r   maybe_convert_promptrO   	input_idsshapetorchequalbatch_decoder_   loggerwarningrN   torepeatview)ra   rc   rd   re   r3   rf   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textrJ   _seq_lens                 r/   _get_t5_prompt_embedsz"FluxPipeline._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[r1   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 )Nrh   TFri   )rj   rh   rk   rm   rl   rn   ro   rp   rq   r"   z\The following part of your input was truncated because CLIP can only handle sequences up to rr   rs   ru   )rv   rw   rx   r?   r   ry   rM   r_   rz   r{   r|   r}   r~   r   r   rL   r   pooler_outputrf   r   r   )
ra   rc   rd   r3   r   r   r   r   r   rJ   s
             r/   _get_clip_prompt_embedsz$FluxPipeline._get_clip_prompt_embeds
  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r1   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.
        )rc   r3   rd   )rc   rd   re   r3   r"   r   r3   rf   )rv   rw   r   _lora_scalerL   r   r   rN   rx   r   r   r   rf   rP   r|   zerosr{   r   )ra   rc   r   r3   rd   rJ   r   re   r   rf   text_idss              r/   encode_promptzFluxPipeline.encode_prompt6  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<<r1   c                 P   t        | j                  j                               j                  }t	        |t
        j                        s| j                  |d      j                  }|j                  ||      }| j                  |      j                  }|j                  |d      }|S )Nri   )rn   r   r   dim)nextrG   r<   rf   rw   r|   TensorrH   pixel_valuesr   image_embedsrepeat_interleave)ra   imager3   rd   rf   r   s         r/   encode_imagezFluxPipeline.encode_image  s    T''2245;;%.**5*FSSEe4))%0==#556KQR5Sr1   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   )r3   )rw   listr?   rP   encoder_hid_projnum_ip_adaptersr7   r   appendr|   catr   )ra   ip_adapter_imageip_adapter_image_embedsr3   rd   r   single_ip_adapter_imagesingle_image_embedss           r/   prepare_ip_adapter_image_embedsz,FluxPipeline.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#**+>?	@
 '&r1   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 z and z(. Dimensions will be resized accordinglyc              3   :   K   | ]  }|j                   v   y wr)   )_callback_tensor_inputs).0kra   s     r/   	<genexpr>z,FluxPipeline.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`.rb   z8`max_sequence_length` cannot be greater than 512 but is )
rS   r   r   allr7   r   rw   rx   r   type)ra   rc   r   heightwidthnegative_promptnegative_prompt_2rJ   negative_prompt_embedsr   negative_pooled_prompt_embeds"callback_on_step_end_tensor_inputsre   r   s   `             r/   check_inputszFluxPipeline.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   r3   rf   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelss	            r/   _prepare_latent_image_idsz&FluxPipeline._prepare_latent_image_ids  s     ;;vua8#3F#;ell6>RSTVZSZ>[#[ #3F#;ell5>QRVXYRY>Z#Z RbRhRhO 57O+33"%::<T
  ""&">>r1   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   )rI   r   num_channels_latentsr   r   s        r/   _pack_latentszFluxPipeline._pack_latents  sj    ,,z+?1aQVZ[Q[]^_//!Q1a3//*v{uz.JL`cdLder1   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   )rI   r   r   rS   r   num_patcheschannelss          r/   _unpack_latentszFluxPipeline._unpack_latents  s    ,3MM)
K c&k&6&:;<SZ$4q$89:,,z6Q;
HPQMSTVWX//!Q1a3//*h5.A65Qr1   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)rK   enable_slicingra   s    r/   enable_vae_slicingzFluxPipeline.enable_vae_slicing      
 	!r1   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)rK   disable_slicingr   s    r/   disable_vae_slicingz FluxPipeline.disable_vae_slicing&  s    
 	  "r1   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)rK   enable_tilingr   s    r/   enable_vae_tilingzFluxPipeline.enable_vae_tiling-  s     	 r1   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)rK   disable_tilingr   s    r/   disable_vae_tilingzFluxPipeline.disable_vae_tiling5  r   r1   c	                    dt        |      | j                  dz  z  z  }dt        |      | j                  dz  z  z  }||||f}	|0| j                  ||dz  |dz  ||      }
|j                  ||      |
fS t	        |t
              r)t        |      |k7  rt        dt        |       d| d      t        |	|||      }| j                  |||||      }| j                  ||dz  |dz  ||      }
||
fS )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.)	generatorr3   rf   )
r   rS   r   r   rw   r   r?   r7   r   r   )ra   r   r   r   r   rf   r3   r   rI   r{   r   s              r/   prepare_latentszFluxPipeline.prepare_latents<  s8    c&kd&;&;a&?@ASZD$9$9A$=>?165A#==j&TU+W\`aWacikpq::V5:9;KKKi&3y>Z+GA#i.AQ R&<'gi 
 u	&PUV$$Wj:NPVX]^99*fPQkSX\]S]_eglm(((r1   c                     | j                   S r)   )_guidance_scaler   s    r/   guidance_scalezFluxPipeline.guidance_scale_  s    ###r1   c                     | j                   S r)   )_joint_attention_kwargsr   s    r/   joint_attention_kwargsz#FluxPipeline.joint_attention_kwargsc  s    +++r1   c                     | j                   S r)   )_num_timestepsr   s    r/   num_timestepszFluxPipeline.num_timestepsg  s    """r1   c                     | j                   S r)   )_current_timestepr   s    r/   current_timestepzFluxPipeline.current_timestepk  s    %%%r1   c                     | j                   S r)   )
_interruptr   s    r/   	interruptzFluxPipeline.interrupto  s    r1         ?   g      @pilTr   r   true_cfg_scaler   r   r2   r5   r   r   r   r   negative_ip_adapter_image negative_ip_adapter_image_embedsr   r   output_typereturn_dictr   callback_on_step_endr   c                    |xs | j                   | j                  z  }|xs | j                   | j                  z  }| j                  ||||||||||||       |
| _        || _        d| _        d| _        |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                  }| j                  | j                  j                  dd      nd}|duxs
 |duxr |du}|dkD  xr |} | j                  ||||||||      \  }}}!| r| j                  ||||||||      \  }}}"| j                   j"                  j$                  dz  }#| j'                  ||z  |#|||j(                  |||      \  }}$|	t+        j,                  d	d|z  |      n|	}	t/        | j0                  j"                  d
      r"| j0                  j"                  j2                  rd}	|j                  d   }%t5        |%| j0                  j"                  j                  dd      | j0                  j"                  j                  dd      | j0                  j"                  j                  dd      | j0                  j"                  j                  dd            }&t7        | j0                  |||	|&      \  }'}t9        t        |'      || j0                  j:                  z  z
  d      }(t        |'      | _        | j                   j"                  j>                  rGtA        jB                  dg|
|t@        jD                        })|)jG                  |j                  d         })nd})||Q|O|Mt+        jH                  ||dft*        jJ                        }|g| j                   jL                  jN                  z  }nT|R|P||Lt+        jH                  ||dft*        jJ                        }|g| j                   jL                  jN                  z  }| j                  i | _        d}*d}+||| jQ                  |||||z        }*||| jQ                  |||||z        }+| j0                  jS                  d       | jU                  |      5 },tW        |'      D ]@  \  }-}.| jX                  r|.| _        |*|*| j                  d<   |.jG                  |j                  d         j[                  |j(                        }/| j                   j]                  d      5  | j!                  ||/dz  |)|||!|$| j                  d	      d   }0ddd       | rj|+|+| j                  d<   | j                   j]                  d      5  | j!                  ||/dz  |)||"|$| j                  d	      d   }1ddd       1|0|1z
  z  z   }0|j(                  }2| j0                  j_                  0|.|d      d   }|j(                  |2k7  r9t@        j`                  jb                  je                         r|j[                  |2      }|Hi }3|D ]  }4tg               |4   |3|4<     || |-|.|3      }5|5ji                  d|      }|5ji                  d|      }|-t        |'      dz
  k(  s'|-dz   |(kD  r/|-dz   | j0                  j:                  z  dk(  r|,jk                          tl        s-to        jp                          C 	 ddd       d| _        |d k(  r|}6n| js                  |||| j                        }|| jt                  j"                  jv                  z  | jt                  j"                  jx                  z   }| jt                  j{                  |d      d   }6| j|                  j                  |6|!      }6| j                          |s|6fS t        |6"      S # 1 sw Y   uxY w# 1 sw Y   !xY w# 1 sw Y   xY w)#a  
        Function invoked when calling the pipeline for generation.

        Args:
            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):
                True classifier-free guidance (guidance scale) is enabled when `true_cfg_scale` > 1 and
                `negative_prompt` is provided.
            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 guiddance 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 classifer-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 be 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`.

        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   r   rJ   r   r   r   r   re   NFr"   r   scale)rc   r   rJ   r   r3   rd   re   r   r   r   use_flow_sigmasbase_image_seq_len   max_image_seq_len   r&         ?r'   ffffff?)r5   r.   r   r   )rf   )totalr   condi  )	hidden_statestimestepguidancepooled_projectionsencoder_hidden_statestxt_idsimg_idsr   r   uncond)r   rI   rJ   latent)r   )images)Br`   rS   r   r   r   r   r   rw   rx   r   r?   r{   rv   r   getr   rP   rZ   in_channelsr   rf   nplinspacer]   r@   r   r0   rD   maxorderr   guidance_embedsr|   fullfloat32expandr   uint8r   r   r   set_begin_indexprogress_bar	enumerater   r   cache_contextstepbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   rK   scaling_factorshift_factordecoder\   postprocessmaybe_free_model_hooksr#   )7ra   rc   r   r   r   r   r   r   r2   r5   r   rd   r   rI   rJ   r   r   r   r   r   r   r   r   r   r   r   r   re   r   r3   r   has_neg_promptdo_true_cfgr   negative_text_idsr   r   r+   r.   r4   num_warmup_stepsr  r   negative_image_embedsr  itr  
noise_predneg_noise_predlatents_dtypecallback_kwargsr   callback_outputsr   s7                                                          r/   __call__zFluxPipeline.__call__s  s?   F K433d6K6KKI11D4I4II 	+/'#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% # 		&-!  $//66BBaG$($8$8.. 	%
!! TZSaS!&9"9;NOgm4>>((*;<AVAVAfAfF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 A	#\!), @#1>>)*&+NZD001JK88GMM!$4588G%%33F; !%!1!1&-!)D!)+?.; ( 0/3/J/J$) "2 
" 
"J ,8Rg445NO))77A )-)9)9*1%-_%-/L2H$5$4373N3N(- *: 
* 
* "0.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 '') LLNA@#A	#F "&("E**7FE4CXCXYG!?!??488??C_C__GHHOOGO?BE((44U4TE 	##%8O!//Q " 9A	# A	#sD   B
_+^*76_-+^7D!_;_*^4/_7_<__)NN)Nr"   rb   NN)r"   N)NNr"   NNrb   N)NNNNNNNNr)   )<__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr   r   r   r
   r   r   r   r   r   r	   rW   r   rx   r   r   r   r|   r3   rf   r   r   FloatTensorfloatr   r   r   r   staticmethodr   r   r   r   r   r   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRING	Generatorr   r   boolr   r   r   r8  __classcell__)r>   s   @r/   rF   rF      sw   4 \+-@A(/: 8<04 '2 '  ' $	 '
 ! ' ' ' % ' , ' 5 ' . 'H )-%&#&)-'+/c49n%/  #/ !	/
 &/ $/h &')-	*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=^	"'T #!&*+/ CoJ ? ?    "#!"  !)F $ $ , , # # & &   U]]_12 )-4815=A # $##%(, #/0MQ/359<@9=@DBFIM>BEI%* ;?KO9B#&9i0c49n%i0 5d3i01i0 sDI~.	i0
 $E#tCy.$9:i0 i0 i0 }i0 !i0 e%i0 i0  (}i0 E%//43H"HIJi0 %++,i0   1 12i0  'u'8'89!i0" ##56#i0$ "*$u||*<!=%i0& $,,>#?'i0( +343E*F)i0* !)):): ;+i0, (00A0A'B-i0. c]/i00 1i02 !)c3h 83i04 'xc40@$0F'GH5i06 -1I7i08 !9i0 3 i0r1   rF   )r   r   r   r  )NNNN)<r9   typingr   r   r   r   r   r   numpyr  r|   transformersr	   r
   r   r   r   r   r\   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_modelr%  r$  
get_loggerr9  r   rD  r   r@  r0   rx   r3   rD   rF   r*   r1   r/   <module>rV     s2    = =    E p p ; 9  . . / ))MM 
		H	% & 

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vL0L0r1   