
    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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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e      Z9y)     N)AnyCallableDictListOptionalUnion)CLIPImageProcessorCLIPVisionModelWithProjectionT5EncoderModelT5TokenizerFast   )PipelineImageInputVaeImageProcessor)FluxIPAdapterMixinFluxLoraLoaderMixinFromSingleFileMixinTextualInversionLoaderMixin)AutoencoderKLChromaTransformer2DModel)FlowMatchEulerDiscreteScheduler)USE_PEFT_BACKENDis_torch_xla_availableloggingreplace_example_docstringscale_lora_layersunscale_lora_layers)randn_tensor   )DiffusionPipeline   )ChromaPipelineOutputTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import ChromaPipeline

        >>> model_id = "lodestones/Chroma"
        >>> ckpt_path = "https://huggingface.co/lodestones/Chroma/blob/main/chroma-unlocked-v37.safetensors"
        >>> transformer = ChromaTransformer2DModel.from_single_file(ckpt_path, torch_dtype=torch.bfloat16)
        >>> pipe = ChromaPipeline.from_pretrained(
        ...     model_id,
        ...     transformer=transformer,
        ...     torch_dtype=torch.bfloat16,
        ... )
        >>> pipe.enable_model_cpu_offload()
        >>> prompt = [
        ...     "A high-fashion close-up portrait of a blonde woman in clear sunglasses. The image uses a bold teal and red color split for dramatic lighting. The background is a simple teal-green. The photo is sharp and well-composed, and is designed for viewing with anaglyph 3D glasses for optimal effect. It looks professionally done."
        ... ]
        >>> negative_prompt = [
        ...     "low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors"
        ... ]
        >>> image = pipe(prompt, negative_prompt=negative_prompt).images[0]
        >>> image.save("chroma.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           e/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/chroma/pipeline_chroma.pycalculate_shiftr.   M   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 valuesr2   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r2   r1   r3   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r3   r1   r1   r(   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r2   len)	schedulerr0   r1   r2   r3   kwargsaccepts_timestepsaccept_sigmass           r-   retrieve_timestepsrB   [   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            3           e Zd ZdZdZddgZddgZ	 	 dCded	ed
e	de
dededef fdZ	 	 	 	 	 dDdeeee   f   dededeej*                     deej,                     f
dZ	 	 	 	 	 	 	 	 	 	 dEdeeee   f   deeee   f   deej*                     dedeej0                     deej0                     deej0                     deej0                     dededee   fdZd Zd Z	 	 	 	 	 	 	 dFd Zed!        Z ed"        Z!ed#        Z"d$ Z#d% Z$d& Z%d' Z&	 dGd(Z'	 dGd)Z(e)d*        Z*e)d+        Z+e)d,        Z,e)d-        Z-e)d.        Z.e)d/        Z/ ej`                          e1e2      ddddd0dd1dddddddddddd2ddddgdfdeeee   f   deeee   f   d3ee   d4ee   d5ed6eee      d7edee   d8eeejf                  eejf                     f      deej0                     deej0                     d9ee4   d:eeej0                        d;ee4   d<eeej0                        deej0                     deej0                     deej0                     d=ee   d>ed?ee5ee6f      d@ee7eee5gdf      dAee   def0dB              Z8 xZ9S )HChromaPipelinea  
    The Chroma pipeline for text-to-image generation.

    Reference: https://huggingface.co/lodestones/Chroma/

    Args:
        transformer ([`ChromaTransformer2DModel`]):
            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 representation
        text_encoder ([`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 (`T5TokenizerFast`):
            Second Tokenizer of class
            [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
    z-text_encoder->image_encoder->transformer->vaeimage_encoderfeature_extractorlatentsprompt_embedsNr>   vaetext_encoder	tokenizertransformerc           	      "   t         |           | j                  |||||||       t        | dd       r/dt	        | j
                  j                  j                        dz
  z  nd| _        t        | j                  dz        | _
        d| _        y )N)rI   rJ   rK   rL   r>   rE   rF   rI   r   r       )vae_scale_factor   )super__init__register_modulesgetattrr=   rI   configblock_out_channelsrO   r   image_processordefault_sample_size)	selfr>   rI   rJ   rK   rL   rE   rF   r<   s	           r-   rR   zChromaPipeline.__init__   s     	%#'/ 	 	
 W^^bdikoVpc$((//*L*L&MPQ&Q Rvw  1$BWBWZ[B[\#& r/   r       promptnum_images_per_promptmax_sequence_lengthr1   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                  j                         }	|	j                  d      }
t        j                  |	j                  d            j!                  d      j#                  |d	      }||
j!                  d      k  j%                         }	| j                  |j'                  |      d|	j'                  |      
      d   }| j                  j                  }|j'                  ||      }|	j'                  ||      }	|j(                  \  }}}|j+                  d|d      }|j-                  ||z  |d	      }|	j+                  d|      }	|	j-                  ||z  |      }	||	fS )N
max_lengthTFpt)paddingr`   
truncationreturn_lengthreturn_overflowing_tokensreturn_tensorsr    dimr   )output_hidden_statesattention_mask)r^   r1   )_execution_devicerJ   r^   
isinstancestrr=   r   maybe_convert_promptrK   	input_idsrk   clonesumtorcharangesize	unsqueezeexpandlongtoshaperepeatview)rY   r[   r\   r]   r1   r^   
batch_sizetext_inputstext_input_idsrk   seq_lengthsmask_indicesrH   _seq_lens                  r-   _get_t5_prompt_embedsz$ChromaPipeline._get_t5_prompt_embeds   s    14110**00'4&&[
d78..vt~~FFnn *&+ % 
 %..$3399; %((Q(/||N$7$7$:;EEaHOOPZ\^_&+*?*?*BBHHJ))f%ER`RcRcdjRk * 

 !!''%((uV(D'**v*F%++7A &,,Q0EqI%**:8M+MwXZ['..q2GH',,Z:O-OQXYn,,r/   Tnegative_promptnegative_prompt_embedsprompt_attention_masknegative_prompt_attention_maskdo_classifier_free_guidance
lora_scalec                 J   |xs | j                   }|?t        | t              r/|| _        | j                  t
        rt        | j                  |       t        |t              r|gn|}|t        |      }n|j                  d   }|| j                  |||
|      \  }}| j                  | j                  j                  n| j                  j                  }t        j                  |j                  d   d      j                  ||      }d}|	r||xs d}t        |t              r||gz  n|}|:t!        |      t!        |      ur$t#        dt!        |       d	t!        |       d
      |t        |      k7  r!t%        d| dt        |       d| d| d	      | j                  |||
|      \  }}t        j                  |j                  d   d      j                  ||      }| j                  ,t        | t              rt
        rt'        | j                  |       ||||||fS )a  

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
                instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
            device: (`torch.device`):
                torch device
            num_images_per_prompt (`int`):
                number of images that should be generated per prompt
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            lora_scale (`float`, *optional*):
                A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
        Nr   )r[   r\   r]   r1   r    r   r1   r^    z?`negative_prompt` should be the same type to `prompt`, but got z != .z`negative_prompt`: z has batch size z, but `prompt`: zT. Please make sure that passed `negative_prompt` matches the batch size of `prompt`.)rl   rm   r   _lora_scalerJ   r   r   rn   r=   rz   r   r^   rL   rs   zerosry   type	TypeErrorr5   r   )rY   r[   r   r1   r\   rH   r   r   r   r   r]   r   r}   r^   text_idsnegative_text_idss                   r-   encode_promptzChromaPipeline.encode_prompt  s~   @ 1411 !j7J&K)D   ,1A!$"3"3Z@'4&&VJ&,,Q/J 373M3M&;$7	 4N 40M0 ,0+<+<+H!!''dN^N^NdNd;;}2215q9<<FRW<X &%-"1"7R6@RU6VJ/!22\k   %$v,d?>S*S#YZ^_nZoYp q L>,   3#77$-o->>NsSbOcNd e"8#3J< @77  JNIcIc**?(;!	 Jd JF&(F !&,B,H,H,KQ O R RZ`hm R n($ 349I#D$5$5zB !"*
 	
r/   c                 P   t        | j                  j                               j                  }t	        |t
        j                        s| j                  |d      j                  }|j                  ||      }| j                  |      j                  }|j                  |d      }|S )Nra   )rf   r   r   rg   )nextrE   r:   r^   rm   rs   TensorrF   pixel_valuesry   image_embedsrepeat_interleave)rY   imager1   r\   r^   r   s         r-   encode_imagezChromaPipeline.encode_imagen  s    T''2245;;%.**5*FSSEe4))%0==#556KQR5Sr/   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   rg   r1   )rm   listr=   rL   encoder_hid_projnum_ip_adaptersr5   r   appendrs   catry   )rY   ip_adapter_imageip_adapter_image_embedsr1   r\   r   single_ip_adapter_imagesingle_image_embedss           r-   prepare_ip_adapter_image_embedsz.ChromaPipeline.prepare_ip_adapter_image_embedsz  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#**+>?	@
 '&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      |7t        |t              s't        |t              st	        dt        |             ||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krY   s     r-   	<genexpr>z.ChromaPipeline.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.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: zLCannot provide `prompt_embeds` without also providing `prompt_attention_maskz^Cannot provide `negative_prompt_embeds` without also providing `negative_prompt_attention_maskrZ   z8`max_sequence_length` cannot be greater than 512 but is )
rO   loggerwarningallr5   r   rm   rn   r   r   )rY   r[   heightwidthr   rH   r   r   r   "callback_on_step_end_tensor_inputsr]   r   s   `           r-   check_inputszChromaPipeline.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  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa&+A+M9/9J K*++]_ 
 $)>)Fkll!-2P2Xp  */BS/HWXkWlmnn 0I*; pHs   EE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   )rs   r   rt   rz   reshapery   )	r}   r   r   r1   r^   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelss	            r-   _prepare_latent_image_idsz(ChromaPipeline._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   )rG   r}   num_channels_latentsr   r   s        r-   _pack_latentszChromaPipeline._pack_latents  sj    ,,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   )rz   intr|   r   r   )rG   r   r   rO   r}   num_patcheschannelss          r-   _unpack_latentszChromaPipeline._unpack_latents  s    ,3MM)
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)rI   enable_slicingrY   s    r-   enable_vae_slicingz!ChromaPipeline.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)rI   disable_slicingr   s    r-   disable_vae_slicingz"ChromaPipeline.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)rI   enable_tilingr   s    r-   enable_vae_tilingz ChromaPipeline.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)rI   disable_tilingr   s    r-   disable_vae_tilingz!ChromaPipeline.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.)	generatorr1   r^   )
r   rO   r   ry   rm   r   r=   r5   r   r   )rY   r}   r   r   r   r^   r1   r   rG   rz   r   s              r-   prepare_latentszChromaPipeline.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                     ||S t        j                  |t        j                  |||j                        gd      }|j	                  |      }|S )Nr   r    rg   )rs   r   onesr1   ry   )rY   r}   sequence_lengthr^   rk   s        r-   _prepare_attention_maskz&ChromaPipeline._prepare_attention_mask;  sV     !!! UZZ
ONLaLabc
 (**51r/   c                     | j                   S r'   _guidance_scaler   s    r-   guidance_scalezChromaPipeline.guidance_scaleN  s    ###r/   c                     | j                   S r'   )_joint_attention_kwargsr   s    r-   joint_attention_kwargsz%ChromaPipeline.joint_attention_kwargsR  s    +++r/   c                      | j                   dkD  S )Nr    r   r   s    r-   r   z*ChromaPipeline.do_classifier_free_guidanceV  s    ##a''r/   c                     | j                   S r'   )_num_timestepsr   s    r-   num_timestepszChromaPipeline.num_timestepsZ  s    """r/   c                     | j                   S r'   )_current_timestepr   s    r-   current_timestepzChromaPipeline.current_timestep^  s    %%%r/   c                     | j                   S r'   )
_interruptr   s    r-   	interruptzChromaPipeline.interruptb  s    r/   #   g      @pilr   r   r0   r3   r   r   r   r   negative_ip_adapter_image negative_ip_adapter_image_embeds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}| j                  ||||||| j                   ||||      \  }}}}}}| j"                  j$                  j&                  dz  }| j)                  ||z  ||||j*                  ||	|
      \  }
}|t-        j.                  d	d|z  |      n|}|
j                  d   } t1        | | j2                  j$                  j                  d
d      | j2                  j$                  j                  dd      | j2                  j$                  j                  dd      | j2                  j$                  j                  dd            }!| j5                  |
j                  d   | |
j*                  |      }"| j5                  |
j                  d   | |
j*                  |      }#t7        | j2                  ||||!      \  }$}t9        t        |$      || j2                  j:                  z  z
  d      }%t        |$      | _        ||Q|O|Mt-        j>                  ||dft,        j@                        }|g| j"                  jB                  jD                  z  }nT|R|P||Lt-        j>                  ||dft,        j@                        }|g| j"                  jB                  jD                  z  }| j                  i | _        d}&d}'||| jG                  |||||z        }&||| jG                  |||||z        }'| jI                  |      5 }(tK        |$      D ]   \  })}*| jL                  r|*| _        |&|&| j                  d<   |*jO                  |
j                  d         jQ                  |
j*                        }+| j#                  |
|+dz  ||||"| j                  d      d   },| j                   rE|'|'| j                  d<   | j#                  |
|+dz  ||||#| j                  d      d   }-|-||,|-z
  z  z   },|
j*                  }.| j2                  jS                  |,|*|
d      d   }
|
j*                  |.k7  r9tT        jV                  jX                  j[                         r|
jQ                  |.      }
|Hi }/|D ]  }0t]               |0   |/|0<     || |)|*|/      }1|1j_                  d|
      }
|1j_                  d|      }|)t        |$      dz
  k(  s'|)dz   |%kD  r/|)dz   | j2                  j:                  z  dk(  r|(ja                          tb        ste        jf                           	 ddd       d| _        |dk(  r|
}2n| ji                  |
||| j                        }
|
| jj                  j$                  jl                  z  | jj                  j$                  jn                  z   }
| jj                  jq                  |
d      d   }2| jr                  ju                  |2|      }2| jw                          |s|2fS ty        |2      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.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                not greater than `1`).
            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.Tensor`, *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.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            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.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            prompt_attention_mask (torch.Tensor, *optional*):
                Attention mask for the prompt embeddings. Used to mask out padding tokens in the prompt sequence.
                Chroma requires a single padding token remain unmasked. Please refer to
                https://huggingface.co/lodestones/Chroma#tldr-masking-t5-padding-tokens-enhanced-fidelity-and-increased-stability-during-training
            negative_prompt_attention_mask (torch.Tensor, *optional*):
                Attention mask for the negative prompt embeddings. Used to mask out padding tokens in the negative
                prompt sequence. Chroma requires a single padding token remain unmasked. PLease refer to
                https://huggingface.co/lodestones/Chroma#tldr-masking-t5-padding-tokens-enhanced-fidelity-and-increased-stability-during-training
            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.ChromaPipelineOutput`] 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.chroma.ChromaPipelineOutput`] or `tuple`: [`~pipelines.chroma.ChromaPipelineOutput`] if
            `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
            generated images.
        )r   rH   r   r   r   r   r]   NFr    r   scale)r[   r   rH   r   r   r   r   r1   r\   r]   r   r   g      ?base_image_seq_len   max_image_seq_len   r$         ?r%   ffffff?)r}   r   r^   rk   )r3   r,   r   )r^   )totalr   i  )hidden_statestimestepencoder_hidden_statestxt_idsimg_idsrk   r   r   )r   rG   rH   latent)r   )images)=rX   rO   r   r   r   r   r   rm   rn   r   r=   rz   rl   r   getr   r   rL   rU   in_channelsr   r^   nplinspacer.   r>   r   rB   maxorderr   r   uint8r   r   r   progress_bar	enumerater   rw   ry   steprs   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   rI   scaling_factorshift_factordecoderW   postprocessmaybe_free_model_hooksr!   )3rY   r[   r   r   r   r0   r3   r   r\   r   rG   rH   r   r   r   r   r   r   r   r   r   r   r   r   r]   r}   r1   r   r   r   r   r   r)   r,   rk   negative_attention_maskr2   num_warmup_stepsr   negative_image_embedsr  itr   
noise_predneg_noise_predlatents_dtypecallback_kwargsr   callback_outputsr   s3                                                      r-   __call__zChromaPipeline.__call__f  sX   p K433d6K6KKI11D4I4II 	+'"7#9+I/Q 3 	 	
  .'=$!% *VS"9JJvt$<VJ&,,Q/J'' ?C>Y>Y>eD''++GT:ko 	 +'#9"7+I(,(H(H"7 3!  
	
!"*   $//66BBaG$($8$8.. 	%
!! TZSaS!&9"9;NOgma(NN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 55}}Q')--0	 6 
 #'">">}}Q')--9	 #? #
 *<NN*
&	& s9~0CdnnFZFZ0ZZ\]^!)n(,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	%! %89 =	#\!), <#1>>)*&+NZD001JK 88GMM!$4588G!--")%_*7$,#1+/+F+F % . 	 	
 33,8Rg445NO%)%5%5&-!)D.D 1 0'>/3/J/J$) &6 	& 	&N "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 '') LLNy<#=	#~ "&("E**7FE4CXCXYG!?!??488??C_C__GHHOOGO?BE((44U4TE 	##%8O#511_=	# =	#s   *G7[#[[)NN)Nr    rZ   NN)
NNr    NNNNTrZ   N)NNNNNNNr'   ):__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr   r   r   r   r   r   r
   r	   rR   r   rn   r   r   r   rs   r1   r^   r   r   boolfloatr   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   no_gradr   EXAMPLE_DOC_STRING	Generatorr   r   r   r   r(  __classcell__)r<   s   @r-   rD   rD      s   ( L+-@A(/: 8<04'2' ' %	'
 #' .' 5' .': )-%&#&)-'+3-c49n%3-  #3- !	3-
 &3- $3-p 26)-%&049=8<AE,0#&&*f
c49n%f
 sDI~.f
 &	f

  #f
  -f
 !) 6f
  (5f
 )1(>f
 &*f
 !f
 UOf
R	"'R "#'++/ 4ol ? ?    "#!"" !)P & $ $ , , ( ( # # & &   U]]_12 )-15 $##%(, #/0MQ*.049=@DBFIM9=8<AE%* ;?KO9B#&3M2c49n%M2 sDI~.M2 	M2
 }M2 !M2 e%M2 M2  (}M2 E%//43H"HIJM2 %,,'M2  -M2 ##56M2 "*$u||*<!=M2 $,,>#?M2  +343E*F!M2" !) 6#M2$  (5%M2& )1(>'M2( c])M2* +M2, !)c3h 8-M2. 'xc40@$0F'GH/M20 -1I1M22 !3M2 3 M2r/   rD   )r   r   r   r   )NNNN):r7   typingr   r   r   r   r   r   numpyr  rs   transformersr	   r
   r   r   rW   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_loggerr)  r   r4  r   r0  r.   rn   r1   rB   rD   r(   r/   r-   <module>rE     s+    = =   k k D p p = 9  . . 1 ))MM 
		H	% < 

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*v_2_2r/   