
    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
jl                  dee
jn                     de8fdZ9	 	 	 	 d$dee3   deee8e
jt                  f      deee3      deee4      fdZ; G d  d!e'eeee      Z<y)%    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   )ChromaPipelineOutputTFav  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import ChromaTransformer2DModel, ChromaImg2ImgPipeline

        >>> model_id = "lodestones/Chroma"
        >>> ckpt_path = "https://huggingface.co/lodestones/Chroma/blob/main/chroma-unlocked-v37.safetensors"
        >>> pipe = ChromaImg2ImgPipeline.from_pretrained(
        ...     model_id,
        ...     transformer=transformer,
        ...     torch_dtype=torch.bfloat16,
        ... )
        >>> pipe.enable_model_cpu_offload()
        >>> init_image = load_image(
        ...     "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
        ... )
        >>> prompt = "a scenic fastasy landscape with a river and mountains in the background, vibrant colors, detailed, high resolution"
        >>> negative_prompt = "low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors"
        >>> image = pipe(prompt, image=init_image, negative_prompt=negative_prompt).images[0]
        >>> image.save("chroma-img2img.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           m/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/chroma/pipeline_chroma_img2img.pycalculate_shiftr.   K   s;     
Z	K,$>?AQ%%A		Q	BI    encoder_output	generatorsample_modec                     t        | d      r |dk(  r| j                  j                  |      S t        | d      r|dk(  r| j                  j                         S t        | d      r| j                  S t        d      )Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrr4   r5   moder7   AttributeError)r0   r1   r2   s      r-   retrieve_latentsr;   Y   st     ~}-+2I))00;;		/K84K))..00		+%%%RSSr/   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 valuesr>   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r>   r=   r?   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r?   r=   r=   r(   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r>   len)	schedulerr<   r=   r>   r?   kwargsaccepts_timestepsaccept_sigmass           r-   retrieve_timestepsrN   g   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            7       6    e Zd ZdZdZddgZddgZ	 	 dHded	ed
e	de
dededef fdZ	 	 	 	 	 dIdeeee   f   dededeej*                     deej,                     f
dZdej0                  dej2                  fdZ	 	 	 	 	 	 	 	 	 	 dJd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	 	 	 	 	 	 	 dKd#Z e!d$        Z"e!d%        Z#e!d&        Z$d' Z%d( Z&d) Z'd* Z(d+ Z)	 dLd,Z*	 dLd-Z+e,d.        Z-e,d/        Z.e,d0        Z/e,d1        Z0e,d2        Z1e,d3        Z2 ejf                          e4e5      dddddd4dd5d6dddddddddddd7ddddgdfdeeee   f   deeee   f   de6d8ee   d9ee   d:ed;eee      d<ed=edee   deeej2                  eej2                     f      deej0                     deej0                     d>ee6   d?eeej0                        d@ee6   dAeeej0                        deej0                     deej0                     deejn                     dBee   dCedDee8ee9f      dEee:eee8gdf      dFee   def4dG              Z; xZ<S )MChromaImg2ImgPipelinea  
    The Chroma pipeline for image-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_extractorr7   prompt_embedsNrJ   vaetext_encoder	tokenizer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        | _        d| _        y )	N)rT   rU   rV   rW   rJ   rQ   rR   rT   r   r          )vae_scale_factor   )super__init__register_modulesgetattrrI   rT   configblock_out_channelsr[   latent_channelsr   image_processordefault_sample_size)	selfrJ   rT   rU   rV   rW   rQ   rR   rH   s	           r-   r^   zChromaImg2ImgPipeline.__init__   s     	%#'/ 	 	
 W^^bdikoVpc$((//*L*L&MPQ&Q RvwBI$PUW[B\txx>>bd  1$BWBWZ[B[\#& r/   r       promptnum_images_per_promptmax_sequence_lengthr=   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)paddingrm   
truncationreturn_lengthreturn_overflowing_tokensreturn_tensorsr    dimr   )output_hidden_statesattention_mask)rk   r=   )_execution_devicerU   rk   
isinstancestrrI   r   maybe_convert_promptrV   	input_idsrx   clonesumtorcharangesize	unsqueezeexpandlongtoshaperepeatview)rf   rh   ri   rj   r=   rk   
batch_sizetext_inputstext_input_idsrx   seq_lengthsmask_indicesrS   _seq_lens                  r-   _get_t5_prompt_embedsz+ChromaImg2ImgPipeline._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/   imager1   c                    t        |t              rjt        |j                  d         D cg c]1  }t	        | j
                  j                  |||dz          ||         3 }}t        j                  |d      }n&t	        | j
                  j                  |      |      }|| j
                  j                  j                  z
  | j
                  j                  j                  z  }|S c c}w )Nr   r    )r1   rt   )rz   listranger   r;   rT   encoder   catra   shift_factorscaling_factor)rf   r   r1   iimage_latentss        r-   _encode_vae_imagez'ChromaImg2ImgPipeline._encode_vae_image  s    i& u{{1~. !q1q51A!BiXYl[M  "IIm;M,TXX__U-CyYM&)E)EEIgIggs   6C'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   )rh   ri   rj   r=   r    r   r=   rk    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`.)ry   rz   r   _lora_scalerU   r   r   r{   rI   r   r   rk   rW   r   zerosr   type	TypeErrorrA   r   )rf   rh   r   r=   ri   rS   r   r   r   r   rj   r   r   rk   text_idsnegative_text_idss                   r-   encode_promptz#ChromaImg2ImgPipeline.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 )Nrn   )rs   r   r   rt   )nextrQ   rF   rk   rz   r   TensorrR   pixel_valuesr   image_embedsrepeat_interleave)rf   r   r=   ri   rk   r   s         r-   encode_imagez"ChromaImg2ImgPipeline.encode_image  s    T''2245;;%.**5*FSSEe4))%0==#556KQR5Sr/   c                 2   |xs | j                   }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   rt   r=   )ry   rz   r   rI   rW   encoder_hid_projnum_ip_adaptersrA   r   appendr   r   r   )rf   ip_adapter_imageip_adapter_image_embedsr=   ri   r   single_ip_adapter_imagesingle_image_embedss           r-   prepare_ip_adapter_image_embedsz5ChromaImg2ImgPipeline.prepare_ip_adapter_image_embeds  s+    1411"*.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           
          |dk  s|dkD  rt        d|       | 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    z2The value of strength should in [0.0, 1.0] but is 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krf   s     r-   	<genexpr>z5ChromaImg2ImgPipeline.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_maskrg   z8`max_sequence_length` cannot be greater than 512 but is )
rA   r[   loggerwarningallr   rz   r{   r   r   )rf   rh   heightwidthstrengthr   rS   r   r   r   "callback_on_step_end_tensor_inputsrj   r   s   `            r-   check_inputsz"ChromaImg2ImgPipeline.check_inputs  sI    a<8a<QRZQ[\]]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'1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   )r   r   r   r   reshaper   )r   r   r=   rk   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelss           r-   _prepare_latent_image_idsz/ChromaImg2ImgPipeline._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   )r7   r   num_channels_latentsr   r   s        r-   _pack_latentsz#ChromaImg2ImgPipeline._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   )r   intr   r   r   )r7   r   r   r[   r   num_patcheschannelss          r-   _unpack_latentsz%ChromaImg2ImgPipeline._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)rT   enable_slicingrf   s    r-   enable_vae_slicingz(ChromaImg2ImgPipeline.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)rT   disable_slicingr   s    r-   disable_vae_slicingz)ChromaImg2ImgPipeline.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)rT   enable_tilingr   s    r-   enable_vae_tilingz'ChromaImg2ImgPipeline.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)rT   disable_tilingr   s    r-   disable_vae_tilingz(ChromaImg2ImgPipeline.disable_vae_tiling2  r   r/   c                 N   t        ||z  |      }t        t        ||z
  d            }| j                  j                  || j                  j
                  z  d  }t        | j                  d      r2| j                  j                  || j                  j
                  z         |||z
  fS )Nr   set_begin_index)minr   maxrJ   r>   orderr8   r   )rf   r<   r   r=   init_timestept_startr>   s          r-   get_timestepsz#ChromaImg2ImgPipeline.get_timesteps:  s    /(:<OPc-=qABNN,,Wt~~7K7K-K-MN	4>>#45NN**7T^^5I5I+IJ-777r/   c                    t        |	t              r)t        |	      |k7  rt        dt        |	       d| d      dt	        |      | j
                  dz  z  z  }dt	        |      | j
                  dz  z  z  }||||f}| j                  |dz  |dz  ||      }|
|
j                  ||      |fS |j                  ||      }|j                  d   | j                  k7  r| j                  ||	      }n|}||j                  d   kD  rC||j                  d   z  dk(  r.||j                  d   z  }t        j                  |g|z  d	      }n^||j                  d   kD  r4||j                  d   z  dk7  rt        d
|j                  d    d| d      t        j                  |gd	      }t        ||	||      }| j                  j                  |||      }
| j!                  |
||||      }
|
|fS )Nz/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.r   r   r    )r   r1   r   rt   z'Cannot duplicate `image` of batch size z to z text prompts.)r1   r=   rk   )rz   r   rI   rA   r   r[   r   r   r   rc   r   r   r   r   rJ   scale_noiser   )rf   r   timestepr   r   r   r   rk   r=   r1   r7   r   r   r   additional_image_per_promptnoises                   r-   prepare_latentsz%ChromaImg2ImgPipeline.prepare_latentsE  s/    i&3y>Z+GA#i.AQ R&<'gi  c&kd&;&;a&?@ASZD$9$9A$=>?165A99&A+uPQzSY[`a::V5:9;KKKe4;;q>T111 22)2TM!M++A..:@S@STU@V3VZ[3[*48K8KA8N*N'!II}o8S&SYZ[M---a00Z-BUBUVWBX5X\]5]9-:M:Ma:P9QQUV`Uaaop  "II}o1=MUieT..,,]HeL$$Wj:NPVX]^(((r/   c                     ||S t        j                  |t        j                  |||j                        gd      }|j	                  |      }|S )Nr   r    rt   )r   r   onesr=   r   )rf   r   sequence_lengthrk   rx   s        r-   _prepare_attention_maskz-ChromaImg2ImgPipeline._prepare_attention_maskw  sV     !!! UZZ
ONLaLabc
 (**51r/   c                     | j                   S r'   _guidance_scaler   s    r-   guidance_scalez$ChromaImg2ImgPipeline.guidance_scale  s    ###r/   c                     | j                   S r'   )_joint_attention_kwargsr   s    r-   joint_attention_kwargsz,ChromaImg2ImgPipeline.joint_attention_kwargs  s    +++r/   c                      | j                   dkD  S )Nr    r   r   s    r-   r   z1ChromaImg2ImgPipeline.do_classifier_free_guidance  s    ##a''r/   c                     | j                   S r'   )_num_timestepsr   s    r-   num_timestepsz#ChromaImg2ImgPipeline.num_timesteps  s    """r/   c                     | j                   S r'   )_current_timestepr   s    r-   current_timestepz&ChromaImg2ImgPipeline.current_timestep  s    %%%r/   c                     | j                   S r'   )
_interruptr   s    r-   	interruptzChromaImg2ImgPipeline.interrupt  s    r/   #   g      @g?pilr   r   r<   r?   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| _        | j                  j                  |||      }|j                  t        j                        }|t        |t              rd}n-|t        |t              rt        |      }n|j                   d   }| j"                  }| j$                  | j$                  j'                  dd      nd}| j)                  ||||||| j*                  ||
||	      \  }}}}} }|t-        j.                  d
d|z  |      n|}t1        |      | j                  z  dz  t1        |      | j                  z  dz  z  }!t3        |!| j4                  j6                  j'                  dd      | j4                  j6                  j'                  dd      | j4                  j6                  j'                  dd      | j4                  j6                  j'                  dd            }"t9        | j4                  ||||"      \  }#}| j;                  ||	|      \  }#}t=        t        |#      || j4                  j>                  z  z
  d      }$t        |#      | _         |dk  rtC        d|	 d| d      |#dd jE                  ||
z        }%| jF                  j6                  jH                  dz  }&| jK                  ||%||
z  |&|||jL                  |||
      \  }}'| jO                  |j                   d   |!|jL                  |      }(| jO                  |j                   d   |!|jL                  |      })||Q|O|Mt-        jP                  ||dft,        jR                        }|g| jF                  jT                  jV                  z  }nT|R|P||Lt-        jP                  ||dft,        jR                        }|g| jF                  jT                  jV                  z  }| j$                  i | _        d}*d}+||| jY                  |||||
z        }*||| jY                  |||||
z        }+| j[                  |      5 },t]        |#      D ]  \  }-}.| j^                  r|.| _        |.ja                  |j                   d         }/|*|*| j                  d<   | jG                  ||/dz  |||'|(| j$                  d      d   }0| j*                  rE|+|+| j                  d<   | jG                  ||/dz  || |'|)| j$                  d      d   }1|1||0|1z
  z  z   }0|jL                  }2| j4                  jc                  |0|.|d      d   }|jL                  |2k7  r9t        jd                  jf                  ji                         r|j                  |2      }|Hi }3|D ]  }4tk               |4   |3|4<     || |-|.|3      }5|5jm                  d |      }|5jm                  d!|      }|-t        |#      dz
  k(  s'|-dz   |$kD  r/|-dz   | j4                  j>                  z  dk(  r|,jo                          tp        sts        jt                           	 ddd       d| _        |d"k(  r|}n| jw                  |||| j                        }|| jx                  j6                  jz                  z  | jx                  j6                  j|                  z   }| jx                  j                  |d      d   }| j                  j                  ||#      }| j                          |s|fS t        |$      S # 1 sw Y   xY w)%a
  
        Function invoked when calling the pipeline for generation.

        Args:
            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 35):
                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 5.0):
                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.
            strength (`float, *optional*, defaults to 0.9):
                Conceptually, indicates how much to transform the reference image. Must be between 0 and 1. image will
                be used as a starting point, adding more noise to it the larger the strength. The number of denoising
                steps depends on the amount of noise initially added. When strength is 1, added noise will be maximum
                and the denoising process will run for the full number of iterations specified in num_inference_steps.
                A value of 1, therefore, essentially ignores image.
            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   rS   r   r   r   r   rj   NF)r   r   )rk   r    r   scale)rh   r   rS   r   r   r   r   r=   ri   rj   r   g      ?r   base_image_seq_len   max_image_seq_len   r$         ?r%   ffffff?)r?   r,   z?After adjusting the num_inference_steps by strength parameter: z!, the number of pipelinesteps is z4 which is < 1 and not appropriate for this pipeline.r   )r   r   rk   rx   r   )totalr   i  )hidden_statesr   encoder_hidden_statestxt_idsimg_idsrx   r  r  )r  r7   rS   latent)r  )images)Cre   r[   r   r  r  r  r  rd   
preprocessr   r   float32rz   r{   r   rI   r   ry   r  getr   r   nplinspacer   r.   rJ   ra   rN   r   r   r   r  rA   r   rW   in_channelsr   rk   r   r   uint8r   r   r   progress_bar	enumerater  r   stepbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   rT   r   r   decodepostprocessmaybe_free_model_hooksr!   )6rf   rh   r   r   r   r   r<   r?   r  r   ri   r1   r7   rS   r   r   r  r  r   r   r   r  r  r  r  r   rj   
init_imager   r=   r   r   r   r)   r,   r>   num_warmup_stepslatent_timestepr   r   rx   negative_attention_maskr   negative_image_embedsr-  r   tr   
noise_prednoise_pred_uncondlatents_dtypecallback_kwargsr   callback_outputss6                                                         r-   __call__zChromaImg2ImgPipeline.__call__  s   @ K433d6K6KKI11D4I4II 	+'#9"7+I/Q 3 	 	
  .'=$!% ))44U6QV4W
]]]7
 *VS"9JJvt$<VJ&,,Q/J''>B>Y>Y>eD''++GT:ko 	 +'#9"7+I(,(H(H"7 3!  
	
!"*  TZSaS!&9"9;NOgmV(=(==Bs5zUYUjUjGjnoGopNN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 *<NN*
&	& *.););<OQY[a)b&	&s9~0CdnnFZFZ0ZZ\]^!)n"QRZQ[ \/00df  $BQ-..z<Q/QR  $//66BBaG$($8$8.. %
!! 55}}Q')--0	 6 
 #'">">}}Q')--9	 #? #
 (,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>>)*&88GMM!$45+NZD001JK!--")%_*7$,#1+/+F+F % . 	 	
 33,8Rg445NO(,(8(8&-!)D.D 1 0'>/3/J/J$) )9 	) 	)% "3^zTeGe5f!fJ !(..--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 '') LLN{=#>	#@ "&("E**7FE4CXCXYG!?!??488??C_C__GHHOOGO?BE((44U4TE 	##%8O#511a>	# >	#s   G]&7]&&]/)NN)Nr    rg   NN)
NNr    NNNNTrg   N)NNNNNNNr'   )=__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr   r   r   r   r   r   r
   r	   r^   r   r{   r   r   r   r   r=   rk   r   r   	Generatorr   boolfloatr   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   r   propertyr  r  r   r	  r  r  no_gradr   EXAMPLE_DOC_STRINGr   tensorr   r   r   rG  __classcell__)rH   s   @r-   rP   rP      sS   ( L+-@A(/: 8<04'2' ' %	'
 #' .' 5' .'> )-%&#&)-'+3-c49n%3-  #3- !	3-
 &3- $3-lu||  " 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	$'X #"'++/ 8ot ? ?    "#!"	8, 0)n & $ $ , , ( ( # # & &   U]]_12 )-15$( $##%(, #/0MQ*.049=@DBFIM9=8<AE%* ;?KO9B#&7f2c49n%f2 sDI~.f2 "	f2
 f2 }f2 !f2 e%f2 f2 f2  (}f2 E%//43H"HIJf2 %,,'f2  -f2 ##56f2  "*$u||*<!=!f2" $,,>#?#f2$ +343E*F%f2& !) 6'f2(  (5)f2* )1(>+f2, c]-f2. /f20 !)c3h 81f22 'xc40@$0F'GH3f24 -1I5f26 !7f2 3 f2r/   rP   )r  r  r  r  )Nr5   )NNNN)=rC   typingr   r   r   r   r   r   numpyr)  r   transformersr	   r
   r   r   rd   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_modelr7  r6  
get_loggerrH  r   rT  r   rP  r.   r   rN  r{   r;   r=   rN   rP   r(   r/   r-   <module>re     s`    = =   k k D p p = 9  . . 1 ))MM 
		H	% 8 

 
 	

 
 ck
TLL
T-5eoo-F
T\_
T  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vh2h2r/   