
    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 ddlmZmZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZ 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Z.ndZ. e j^                  e0      Z1dZ2	 	 	 	 dde3de3de4de4fdZ5	 	 	 	 d dee3   deee6e
jn                  f      deee3      deee4      fdZ8 G d de'eee      Z9y)!    N)AnyCallableDictListOptionalUnion)CLIPTextModelCLIPTokenizerT5EncoderModelT5TokenizerFast   )PipelineImageInputVaeImageProcessor)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 controlnet_aux import CannyDetector
        >>> from diffusers import FluxControlPipeline
        >>> from diffusers.utils import load_image

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

        >>> prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts."
        >>> control_image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png"
        ... )

        >>> processor = CannyDetector()
        >>> control_image = processor(
        ...     control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024
        ... )

        >>> image = pipe(
        ...     prompt=prompt,
        ...     control_image=control_image,
        ...     height=1024,
        ...     width=1024,
        ...     num_inference_steps=50,
        ...     guidance_scale=30.0,
        ... ).images[0]
        >>> image.save("output.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           i/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/flux/pipeline_flux_control.pycalculate_shiftr-   V   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 valuesr1   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r1   r0   r2   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r2   r0   r0   r'   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r1   len)	schedulerr/   r0   r1   r2   kwargsaccepts_timestepsaccept_sigmass           r,   retrieve_timestepsrA   d   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''	)))r.   c            )           e Zd ZdZdZg ZddgZdedede	de
d	ed
edef fdZ	 	 	 	 	 d:deeee   f   dededeej*                     deej,                     f
dZ	 	 d;deeee   f   dedeej*                     fdZ	 	 	 	 	 	 	 d<deeee   f   deeeee   f      deej*                     dedeej2                     deej2                     dedee   fdZ	 	 	 	 d=dZed        Zed        Zed        Z d Z!d  Z"d! Z#d" Z$	 d>d#Z%	 	 d?d$Z&e'd%        Z(e'd&        Z)e'd'        Z*e'd(        Z+ ejX                          e-e.      dddddd)dd*dddddd+d,dddgdfdeeee   f   deeeee   f      d-e/d.ee   d/ee   d0ed1eee      d2edee   d3eeej`                  eej`                     f      deej2                     deej2                     deej2                     d4ee   d5e1d6ee2ee3f      d7ee4eee2gdf      d8ee   def&d9              Z5 xZ6S )@FluxControlPipelinea  
    The Flux pipeline for controllable text-to-image generation with image conditions.

    Reference: https://bfl.ai/flux-1-tools

    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->transformer->vaelatentsprompt_embedsr=   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  | j                        | _        t        | d      r"| j                  | j                  j                  nd	| _        d
| _        y )N)rF   rG   rI   rH   rJ   rK   r=   rF   r   r         )vae_scale_factorvae_latent_channelsrH   M      )super__init__register_modulesgetattrr<   rF   configblock_out_channelsrO   latent_channelsrP   r   image_processorhasattrrH   model_max_lengthtokenizer_max_lengthdefault_sample_size)	selfr=   rF   rG   rH   rI   rJ   rK   r;   s	           r,   rT   zFluxControlPipeline.__init__   s     	%)## 	 	
 W^^bdikoVpc$((//*L*L&MPQ&Q RvwFMdTY[_F`488??#B#Bfh   1!22Q6DLdLd 
 07t[/IdnnNhDNN++np 	! $' r.   Nr      promptnum_images_per_promptmax_sequence_lengthr0   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)paddingrf   
truncationreturn_lengthreturn_overflowing_tokensreturn_tensorslongestrh   rl   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  	 tokens: output_hidden_statesr   rd   r0   )_execution_devicerG   rd   
isinstancestrr<   r   maybe_convert_promptrJ   	input_idsshapetorchequalbatch_decoder]   loggerwarningrI   torepeatview)r_   ra   rb   rc   r0   rd   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textrE   _seq_lens                 r,   _get_t5_prompt_embedsz)FluxControlPipeline._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[r.   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 )Nrf   TFrg   )rh   rf   ri   rk   rj   rl   rm   rn   ro   r   z\The following part of your input was truncated because CLIP can only handle sequences up to rp   rq   rs   )rt   ru   rv   r<   r   rw   rH   r]   rx   ry   rz   r{   r|   r}   r~   rG   r   pooler_outputrd   r   r   )
r_   ra   rb   r0   r   r   r   r   r   rE   s
             r,   _get_clip_prompt_embedsz+FluxControlPipeline._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r.   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.
        )ra   r0   rb   )ra   rb   rc   r0   r   r   r0   rd   )rt   ru   r   _lora_scalerG   r   r   rI   rv   r   r   r   rd   rK   rz   zerosry   r   )r_   ra   r   r0   rb   rE   r   rc   r   rd   text_idss              r,   encode_promptz!FluxControlPipeline.encode_promptD  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<<r.   c	           
          | 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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kr_   s     r,   	<genexpr>z3FluxControlPipeline.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 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`.r`   z8`max_sequence_length` cannot be greater than 512 but is )
rO   r}   r~   allr4   r   ru   rv   listtype)
r_   ra   r   heightwidthrE   r   "callback_on_step_end_tensor_inputsrc   r   s
   `         r,   check_inputsz FluxControlPipeline.check_inputs  sD    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$)=)E U  */BS/HWXkWlmnn 0I*7 pHs   E9E9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   )rz   r   arangery   reshaper   )	r   r   r   r0   rd   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelss	            r,   _prepare_latent_image_idsz-FluxControlPipeline._prepare_latent_image_ids  s     !;;vua8#3F#;ell6>RSTVZSZ>[#[ #3F#;ell5>QRVXYRY>Z#Z RbRhRhO 57O+33"%::<T
  ""&">>r.   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   )rD   r   num_channels_latentsr   r   s        r,   _pack_latentsz!FluxControlPipeline._pack_latents  sl     ,,z+?1aQVZ[Q[]^_//!Q1a3//*v{uz.JL`cdLder.   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   )ry   intr   r   r   )rD   r   r   rO   r   num_patcheschannelss          r,   _unpack_latentsz#FluxControlPipeline._unpack_latents  s     -4MM)
K c&k&6&:;<SZ$4q$89:,,z6Q;
HPQMSTVWX//!Q1a3//*h5.A65Qr.   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)rF   enable_slicingr_   s    r,   enable_vae_slicingz&FluxControlPipeline.enable_vae_slicing      
 	!r.   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)rF   disable_slicingr   s    r,   disable_vae_slicingz'FluxControlPipeline.disable_vae_slicing  s    
 	  "r.   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)rF   enable_tilingr   s    r,   enable_vae_tilingz%FluxControlPipeline.enable_vae_tiling  s     	 r.   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)rF   disable_tilingr   s    r,   disable_vae_tilingz&FluxControlPipeline.disable_vae_tiling  r   r.   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.)	generatorr0   rd   )
r   rO   r   r   ru   r   r<   r4   r   r   )r_   r   r   r   r   rd   r0   r   rD   ry   r   s              r,   prepare_latentsz#FluxControlPipeline.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(((r.   c
                 0   t        |t        j                        rn| j                  j	                  |||      }|j
                  d   }
|
dk(  r|}n|}|j                  |d      }|j                  ||      }|r|	st        j                  |gdz        }|S )N)r   r   r   r   dimr   r   )	ru   rz   TensorrZ   
preprocessry   repeat_interleaver   cat)r_   imager   r   r   rb   r0   rd   do_classifier_free_guidance
guess_modeimage_batch_size	repeat_bys               r,   prepare_imagez!FluxControlPipeline.prepare_image0  s     eU\\*((33E&PU3VE ;;q>q "I .I''	q'9e4&zIIugk*Er.   c                     | j                   S r&   )_guidance_scaler   s    r,   guidance_scalez"FluxControlPipeline.guidance_scaleR  s    ###r.   c                     | j                   S r&   )_joint_attention_kwargsr   s    r,   joint_attention_kwargsz*FluxControlPipeline.joint_attention_kwargsV  s    +++r.   c                     | j                   S r&   )_num_timestepsr   s    r,   num_timestepsz!FluxControlPipeline.num_timestepsZ  s    """r.   c                     | j                   S r&   )
_interruptr   s    r,   	interruptzFluxControlPipeline.interrupt^  s    r.      g      @pilTcontrol_imager   r   r/   r2   r   r   output_typereturn_dictr   callback_on_step_endr   c                    |xs | j                   | j                  z  }|xs | j                   | j                  z  }| j                  ||||||||       || _        || _        d| _        |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                  }| j                  | j                  j                  dd      nd}| j                  ||||||	||      \  }}}| j                  j                   j"                  dz  }| j%                  |||||	z  |	|| j&                  j(                  	      }|j*                  d
k(  r| j&                  j-                  |      j.                  j1                  |
      }|| j&                  j                   j2                  z
  | j&                  j                   j4                  z  }|j                  dd \  }}| j7                  |||	z  |||      }| j9                  ||	z  ||||j(                  ||
|      \  }}|t;        j<                  dd|z  |      n|}|j                  d   }t?        || j@                  j                   j                  dd      | j@                  j                   j                  dd      | j@                  j                   j                  dd      | j@                  j                   j                  dd            }tC        | j@                  ||||      \  }}tE        t        |      || j@                  jF                  z  z
  d      }t        |      | _$        | j                  j                   jJ                  rGtM        jN                  dg||tL        jP                        } | jS                  |j                  d         } nd} | jU                  |      5 }!tW        |      D ]  \  }"}#| jX                  rtM        jZ                  ||gd      }$|#jS                  |j                  d         j]                  |j(                        }%| j                  |$|%dz  | ||||| j                  d	      d   }&|j(                  }'| j@                  j_                  |&|#|d      d   }|j(                  |'k7  r9tL        j`                  jb                  je                         r|j]                  |'      }|Hi }(|D ]  })tg               |)   |(|)<     || |"|#|(      }*|*ji                  d|      }|*ji                  d|      }|"t        |      dz
  k(  s'|"dz   |kD  r/|"dz   | j@                  jF                  z  dk(  r|!jk                          tl        sto        jp                           	 ddd       |dk(  r|}+n| js                  |||| j                        }|| j&                  j                   j4                  z  | j&                  j                   j2                  z   }| j&                  ju                  |d      d   }+| jv                  jy                  |+|       }+| j{                          |s|+fS t}        |+!      S # 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
            control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
                    `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
                The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
                specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
                as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
                width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
                images must be passed as a list such that each element of the list can be correctly batched for input
                to a single ControlNet.
            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.
            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.
        )rE   r   r   rc   FNr   r   scale)ra   r   rE   r   r0   rb   rc   r   rM   )r   r   r   r   rb   r0   rd   r   )r   r   g      ?base_image_seq_len   max_image_seq_len   r#         ?r$   ffffff?)r2   r+   r   )totalr   i  )	hidden_statestimestepguidancepooled_projectionsencoder_hidden_statestxt_idsimg_idsr   r   )r   rD   rE   latent)r   )images)?r^   rO   r   r   r   r   ru   rv   r   r<   ry   rt   r   getr   rK   rW   in_channelsr   rF   rd   ndimencodelatent_distsampleshift_factorscaling_factorr   r   nplinspacer-   r=   rA   maxorderr   guidance_embedsrz   fullfloat32expandprogress_bar	enumerater   r   r   stepbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   decoderZ   postprocessmaybe_free_model_hooksr    ),r_   ra   r   r   r   r   r/   r2   r   rb   r   rD   rE   r   r   r   r   r   r   rc   r   r0   r   r   r   height_control_imagewidth_control_imager   r(   r+   r1   num_warmup_stepsr   r  itlatent_model_inputr   
noise_predlatents_dtypecallback_kwargsr   callback_outputsr   s,                                               r,   __call__zFluxControlPipeline.__call__b  sJ   L K433d6K6KKI11D4I4II 	'!5/Q 3 	 		
  .'=$ *VS"9JJvt$<VJ&,,Q/J'' ?C>Y>Y>eD''++GT:ko 	 '!5"7 3!  	
		
   $//66BBaG**!$99"7((.. + 
 " HHOOM:FFMMXaMbM*TXX__-I-IITXX__MkMkkM8E8K8KAB8O5 "5 ..22$$#M %)$8$8.. 	%
!! 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 %89 -	#\!), ,#1>>%*YY/GQ%O" 88GMM!$4588G!--"4%_%';*7$,+/+F+F % . 
 

 !(..--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 '') LLNY,#-	#^ ("E**7FE4CXCXYG!?!??488??C_C__GHHOOGO?BE((44U4TE 	##%8O!//{-	# -	#s   F(Y7YY()Nr   r`   NN)r   N)NNr   NNr`   NNNNNr&   )FF)7__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr   r   r   r	   r
   r   r   r   rT   r   rv   r   r   r   rz   r0   rd   r   r   FloatTensorfloatr   r   staticmethodr   r   r   r   r   r   r   r   r   propertyr   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   	Generatorboolr   r   r   r!  __classcell__)r;   s   @r,   rC   rC      sj   4 M(/:'2' ' $	'
 !' '' %' ,'H )-%&#&)-'+/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=j !+/ 0od ? ?    "#!"" !)Z %* D $ $ , , # #   U]]_12 )-48,0 $##%(, #/0MQ/359<@%* ;?KO9B#&)R0c49n%R0 5d3i01R0 *	R0
 R0 }R0 !R0 e%R0 R0  (}R0 E%//43H"HIJR0 %++,R0   1 12R0 'u'8'89R0 c]R0  !R0" !)c3h 8#R0$ 'xc40@$0F'GH%R0& -1I'R0( !)R0 3 R0r.   rC   )r   r   r   r   r"  ):r6   typingr   r   r   r   r   r   numpyr   rz   transformersr	   r
   r   r   rZ   r   r   loadersr   r   r   models.autoencodersr   models.transformersr   
schedulersr   utilsr   r   r   r   r   r   utils.torch_utilsr   pipeline_utilsr   pipeline_outputr    torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr#  r}   r.  r   r*  r-   rv   r0   rA   rC   r'   r.   r,   <module>rA     s,    = =   V V D \ \ 0 9 9  . . / ))MM 
		H	%  L 

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vW0	W0r.   