
    bi\                        d dl Z d dlmZmZmZmZmZ d dlZd dl	Z	d dl
mZ ddl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 dd
lmZ ddlmZmZ  e       rddlm Z   e       rdZ!ndZ! ejD                  e#      Z$dZ%	 	 	 	 ddee&   deee'e	jP                  f      deee&      deee)      fdZ* G d de      Z+y)    N)CallableDictListOptionalUnion)LlamaTokenizer   )PipelineImageInputVaeImageProcessor)AutoencoderKL)OmniGenTransformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableis_torchvision_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipelineImagePipelineOutput   )OmniGenMultiModalProcessorTFa[  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import OmniGenPipeline

        >>> pipe = OmniGenPipeline.from_pretrained("Shitao/OmniGen-v1-diffusers", torch_dtype=torch.bfloat16)
        >>> pipe.to("cuda")

        >>> prompt = "A cat holding a sign that says hello world"
        >>> # Depending on the variant being used, the pipeline call will slightly vary.
        >>> # Refer to the pipeline documentation for more details.
        >>> image = pipe(prompt, num_inference_steps=50, guidance_scale=2.5).images[0]
        >>> image.save("output.png")
        ```
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    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r   len)	schedulerr   r   r   r   kwargsaccepts_timestepsaccept_sigmass           g/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/omnigen/pipeline_omnigen.pyretrieve_timestepsr-   <   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''	)))    c            '       f    e Zd ZdZdZg ZdgZdedede	de
f fdZ	 	 d0d
eej                     deej                      deej"                     fdZ	 d1dZd Zd Zd Zd Z	 d1dZed        Zed        Zed        Z ej:                          ee      d	d	d	ddd	ddddd	d	ddd	dgfde e!ee!   f   d e e"ee"   f   d!ee#   d"ee#   d#e#d$e#d%ee#   d&e$d'e$d(e%d)ee#   d*ee ejL                  eejL                     f      deej                     d+ee!   d,e%d-ee'e#e#e(gd	f      d.ee!   f"d/              Z) xZ*S )2OmniGenPipelinea  
    The OmniGen pipeline for multimodal-to-image generation.

    Reference: https://huggingface.co/papers/2409.11340

    Args:
        transformer ([`OmniGenTransformer2DModel`]):
            Autoregressive Transformer architecture for OmniGen.
        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.
        tokenizer (`LlamaTokenizer`):
            Text tokenizer of class.
            [LlamaTokenizer](https://huggingface.co/docs/transformers/main/model_doc/llama#transformers.LlamaTokenizer).
    ztransformer->vaelatentstransformerr(   vae	tokenizerc                    t         |           | j                  ||||       t        | dd       /dt	        | j
                  j                  j                        dz
  z  nd| _        t        | j                  dz        | _
        t        |d      | _        t        | d	      r"| j                  | j                  j                  nd
| _        d| _        y )N)r3   r4   r2   r(   r3   r   r      )vae_scale_factor   max_image_sizer4   i    )super__init__register_modulesgetattrr'   r3   configblock_out_channelsr7   r   image_processorr   multimodal_processorhasattrr4   model_max_lengthtokenizer_max_lengthdefault_sample_size)selfr2   r(   r3   r4   r&   s        r,   r=   zOmniGenPipeline.__init__   s     	#	 	 	
 CJ$PUW[B\BhA#dhhoo889A=>no 	
  1$BWBWZ[B[\$>yY]$^!/6t[/IdnnNhDNN++nt 	! $' r.   Ninput_pixel_valuesr   dtypec                 n   |xs | j                   }|xs | j                  j                  }g }|D ]  }| j                  j                  |j	                  ||            j
                  j                         j                  | j                  j                  j                        }|j                  |        |S )z
        get the continue embedding of input images by VAE

        Args:
            input_pixel_values: normalized pixel of input images
            device:
        Returns: torch.Tensor
        )_execution_devicer3   rJ   encodetolatent_distsamplemul_r@   scaling_factorappend)rH   rI   r   rJ   input_img_latentsimgs         r,   encode_input_imagesz#OmniGenPipeline.encode_input_images   s     1411'% 	*C((//#&&"78DDKKMRRSWS[S[SbSbSqSqrC$$S)	* ! r.   c           
          |t        |      t              k7  r$t        dt               dt        |       d      t        t        |            D ]J  |   	t        fdt        t        |               D              r4t        d    d|    d       | j                  dz  z  d	k7  s| j                  dz  z  d	k7  r,t
        j                  d
 j                  dz   d| d| d       |r||d	   t        d      |Mt         fd|D              s8t        d j                   d|D cg c]  }| j                  vs| c}       y y c c}w )NzThe number of prompts: z, does not match the number of input images: .c              3   :   K   | ]  }d |dz    d   v   yw)z<img><|image_r   z|></img>Nr   ).0kiprompts     r,   	<genexpr>z/OmniGenPipeline.check_inputs.<locals>.<genexpr>   s(     qPQq1ugX>&)Kq   zprompt `z9` doesn't have enough placeholders for the input images ``r   r   z-`height` and `width` have to be divisible by z	 but are z and z(. Dimensions will be resized accordinglyz`use_input_image_size_as_output` is set to True, but no input image was found. If you are performing a text-to-image task, please set it to False.c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs)rZ   r[   rH   s     r,   r^   z/OmniGenPipeline.check_inputs.<locals>.<genexpr>   s#      F
23A---F
r_   z2`callback_on_step_end_tensor_inputs` has to be in z, but found )r'   r   rangeallr7   loggerwarningrc   )	rH   r]   input_imagesheightwidthuse_input_image_size_as_output"callback_on_step_end_tensor_inputsr[   r\   s	   ``      @r,   check_inputszOmniGenPipeline.check_inputs   s    #< CK/ -c&k]:fgjkwgxfyyz{  3|,- ?.qUZ[^_klm_n[oUpqq(&vayk1jkwxykzj{{|}  T**Q./14AVAVYZAZ8[_`8`NN?@U@UXY@Y?ZZcdjckkpqvpw  x`  a *#|A'>  i  .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 C
9 pHs   9EE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)r3   enable_slicingrH   s    r,   enable_vae_slicingz"OmniGenPipeline.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)r3   disable_slicingrp   s    r,   disable_vae_slicingz#OmniGenPipeline.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)r3   enable_tilingrp   s    r,   enable_vae_tilingz!OmniGenPipeline.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)r3   disable_tilingrp   s    r,   disable_vae_tilingz"OmniGenPipeline.disable_vae_tiling   rr   r.   c	                 $   ||j                  ||      S ||t        |      | j                  z  t        |      | j                  z  f}	t        |t              r)t        |      |k7  rt        dt        |       d| d      t        |	|||      }|S )N)r   rJ   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.)	generatorr   rJ   )rN   intr7   
isinstancelistr'   r   r   )
rH   
batch_sizenum_channels_latentsri   rj   rJ   r   r}   r1   shapes
             r,   prepare_latentszOmniGenPipeline.prepare_latents  s     ::V5:99  K4000J$///	
 i&3y>Z+GA#i.AQ R&<'gi 
 u	&PUVr.   c                     | j                   S rb   )_guidance_scalerp   s    r,   guidance_scalezOmniGenPipeline.guidance_scale&  s    ###r.   c                     | j                   S rb   )_num_timestepsrp   s    r,   num_timestepszOmniGenPipeline.num_timesteps*  s    """r.   c                     | j                   S rb   )
_interruptrp   s    r,   	interruptzOmniGenPipeline.interrupt.  s    r.   2   r8   g      @g?Fr   pilTr]   rh   ri   rj   r   max_input_image_sizer   r   img_guidance_scalerk   num_images_per_promptr}   output_typereturn_dictcallback_on_step_endrl   c                    |xs | j                   | j                  z  }|xs | j                   | j                  z  }|dnd}|dnd}t        |t              r|g}|g}| j	                  |||||
|       || _        d| _        t        |      }| j                  }|| j                  j                  k7  r| j                  j                  |       | j                  ||||||
|      }|d	   j                  |      |d	<   |d
   j                  |      |d
<   |d   j                  |      |d<   | j                  |d   |      }t        j                  dd|dz         d| }t!        | j"                  ||||      \  }}t        |      | _        | j&                  j(                  }|
r|d   d   j*                  dd \  }}| j&                  j,                  j.                  }| j1                  ||z  |||t2        j4                  |||      }| j7                  |      5 }t9        |      D ]W  \  }}t3        j:                  |g|dz   z        }|j                  |      }|j=                  |j*                  d         }| j'                  |||d	   ||d   |d
   |d   d      d   } |dk(  r=t3        j>                  | t        |       dz  d      \  }!}"}#|"|	|#|"z
  z  z   ||!|#z
  z  z   } n2t3        j>                  | t        |       dz  d      \  }!}"|"||!|"z
  z  z   } | j"                  jA                  | ||d      d   }|6i }$|D ]  }%tC               |%   |$|%<     || |||$      }&|&jE                  d|      }|jG                          Z 	 ddd       |dk(  s|j                  | jH                  j(                        }|| jH                  j,                  jJ                  z  }| jH                  jM                  |d      d   }'| jN                  jQ                  |'|      }'n|}'| jS                          |s|'fS tU        |'      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 the input includes images, need to add
                placeholders `<img><|image_i|></img>` in the prompt to indicate the position of the i-th images.
            input_images (`PipelineImageInput` or `List[PipelineImageInput]`, *optional*):
                The list of input images. We will replace the "<|image_i|>" in prompt with the i-th image in list.
            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.
            max_input_image_size (`int`, *optional*, defaults to 1024):
                the maximum size of input image, which will be used to crop the input image to the maximum size
            timesteps (`List[int]`, *optional*):
                Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
                in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
                passed will be used. Must be in descending order.
            guidance_scale (`float`, *optional*, defaults to 2.5):
                Guidance scale as defined in [Classifier-Free Diffusion
                Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
                of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
                `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
                the text `prompt`, usually at the expense of lower image quality.
            img_guidance_scale (`float`, *optional*, defaults to 1.6):
                Defined as equation 3 in [Instrucpix2pix](https://huggingface.co/papers/2211.09800).
            use_input_image_size_as_output (bool, defaults to False):
                whether to use the input image size as the output image size, which can be used for single-image input,
                e.g., image editing task
            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`.
            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.
            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.

        Examples:

        Returns: [`~pipelines.ImagePipelineOutput`] or `tuple`:
            If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is returned
            where the first element is a list with the generated images.
        Nr   r   TF)rl   r9   )ri   rj   use_img_cfgrk   r   	input_idsattention_maskposition_idsrI   )r   r   )r   )totalinput_image_sizes)hidden_statestimestepr   rT   r   r   r   r   r	   )dim)r   r1   latent)r   )images)+rG   r7   r   strrm   r   r   r'   rL   rC   r:   reset_max_image_sizerN   rV   nplinspacer-   r(   r   r2   rJ   r   r@   in_channelsr   torchfloat32progress_bar	enumeratecatexpandsplitsteplocalspopupdater3   rR   decoderB   postprocessmaybe_free_model_hooksr   )(rH   r]   rh   ri   rj   r   r   r   r   r   rk   r   r}   r1   r   r   r   rl   num_cfgr   r   r   processed_datarT   r   transformer_dtypelatent_channelsr   r\   tlatent_model_inputr   
noise_predconduncondimg_condcallback_kwargsr[   callback_outputsimages(                                           r,   __call__zOmniGenPipeline.__call__2  s   l K433d6K6KKI11D4I4II#/!Q*6dEfc"XF(>L 	*/Q 	 	
  . [
''  4#<#<#K#KK%%::J^:_22#+I"7 3 
 '5[&A&D&DV&L{#+9:J+K+N+Nv+V'()7)G)J)J6)R~& !44^DX5Ybh4i Q#6#:;<P=PQ);NN/6*
&	& ")n !,,22)*+?@CII"#NMFE**11==&&..MM	
 %89 &	&\!), %&1%*YYyGaK/H%I"%7%:%:;L%M" 88$6$<$<Q$?@!--"4%,[9&7&45H&I#12B#C!/!? % . 	 	
 a<-2[[S_XYEY_`-a*D&(!'*<6@Q*R!RUcgknvgvUw!wJ#(;;z3z?a;OUV#WLD&!'.D6M*J!JJ ..--j!WRW-XYZ['3&(O? 9-3Xa[*9';D!Q'X$.229gFG##%K%&&	&P h&jj0G > >>GHHOOGO?BE((44U4TEE 	##%8O"%00m&	& &	&s   E'P44P=)NNrb   )+__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsrc   r   r   r   r   r=   r   r   Tensorr   r   rJ   rV   rm   rq   ru   rx   r{   r   propertyr   r   r   no_gradr   EXAMPLE_DOC_STRINGr   r   r
   r~   floatbool	Generatorr   r   r   __classcell__)r&   s   @r,   r0   r0   w   s~   " /(k'.' 3' 	'
 "'> *.'+	! .! &! $	!< ,0%N"#!"" > $ $ # #   U]]_12 MQ $##%$(# #$'/4/0MQ*.%* KO9B%N1c49n%N1 .5G0HHIN1 	N1
 }N1 !N1 "N1 9N1 N1 "N1 )-N1  (}N1 E%//43H"HIJN1 %,,'N1 c]N1  !N1" 'xc40@$0F'GH#N1$ -1I%N1 3 N1r.   r0   )NNNN),r!   typingr   r   r   r   r   numpyr   r   transformersr   rB   r
   r   models.autoencodersr   models.transformersr   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   pipeline_utilsr   r   processor_omnigenr   XLA_AVAILABLE
get_loggerr   rf   r   r~   r   r   r   r-   r0   r   r.   r,   <module>r      s     8 8   ' D 0 < 9 i i - C =MM			H	% * *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vK1K1r.   