o
    Gi%                     @  s  d dl mZ d dlZd dlmZmZ d dlZd dlZd dl	m
Z
mZ ddlmZ ddl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 ddlmZ ddlmZ ddlmZ e rid dl m!  m"Z# dZ$ndZ$e%e&Z'dZ(				d(d)ddZ)	d*d+d$d%Z*G d&d' d'eZ+dS ),    )annotationsN)AnyCallable)"Qwen2_5_VLForConditionalGenerationQwen2Tokenizer   )AdaptiveProjectedMixGuidance)PipelineImageInputVaeImageProcessor) AutoencoderKLHunyuanImageRefinerHunyuanImageTransformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipeline   )HunyuanImagePipelineOutputTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import HunyuanImageRefinerPipeline

        >>> pipe = HunyuanImageRefinerPipeline.from_pretrained(
        ...     "hunyuanvideo-community/HunyuanImage-2.1-Refiner-Diffusers", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")
        >>> prompt = "A cat holding a sign that says hello world"
        >>> image = load_image("path/to/image.png")
        >>> # Depending on the variant being used, the pipeline call will slightly vary.
        >>> # Refer to the pipeline documentation for more details.
        >>> image = pipe(prompt, image=image, num_inference_steps=4).images[0]
        >>> image.save("hunyuanimage.png")
        ```
num_inference_steps
int | Nonedevicestr | torch.device | None	timestepslist[int] | Nonesigmaslist[float] | Nonec                 K  s  |dur|durt d|dur>dtt| jj v }|s(t d| j d| jd||d| | j}t	|}||fS |durpdtt| jj v }|sZt 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.
    NzYOnly 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_sigmasr   r   s/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/pipelines/hunyuan_image/pipeline_hunyuanimage_refiner.pyretrieve_timestepsA   s2   r-   sampleencoder_outputtorch.Tensor	generatortorch.Generator | Nonesample_modestrc                 C  sR   t | dr|dkr| j|S t | dr|dkr| j S t | dr%| jS td)Nlatent_distr.   argmaxlatentsz3Could not access latents of provided encoder_output)hasattrr5   r.   moder7   AttributeError)r/   r1   r3   r   r   r,   retrieve_latents}   s   

r;   c                      s&  e Zd ZdZdZddgZdgZ	dbdc fddZ							ddded$d%Z			&	&		dfdgd,d-Z							dhd.d/Z
		0did1d2Zed3d4 Zed5d6 Zdjd;d<Zed=d> Zed?d@ ZedAdB ZedCdD Ze eedddEddddFdd&dddddddGdHdddgfdkd`daZ  ZS )lHunyuanImageRefinerPipelineay  
    The HunyuanImage pipeline for text-to-image generation.

    Args:
        transformer ([`HunyuanImageTransformer2DModel`]):
            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 ([`AutoencoderKLHunyuanImageRefiner`]):
            Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
        text_encoder ([`Qwen2.5-VL-7B-Instruct`]):
            [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct), specifically the
            [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) variant.
        tokenizer (`Qwen2Tokenizer`): Tokenizer of class [Qwen2Tokenizer].
    ztext_encoder->transformer->vaer7   prompt_embedsguiderNr(   r   vaer   text_encoderr   	tokenizerr   transformerr   #AdaptiveProjectedMixGuidance | Nonec                   s   t    | j||||||d t| dd r| jjjnd| _t| jd| _	d| _
d| _d| _d| _t| d	d rA| jjjd
 | _d S d| _d S )N)r?   r@   rA   rB   r(   r>   r?      )vae_scale_factor   z<|start_header_id|>system<|end_header_id|>

Describe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|eot_id|><|start_header_id|>user<|end_header_id|>

{}<|eot_id|>$   @   rB   r   )super__init__register_modulesgetattrr?   configspatial_compression_ratiorE   r
   image_processortokenizer_max_lengthprompt_template_encode prompt_template_encode_start_idxdefault_sample_sizerB   in_channelslatent_channels)selfr(   r?   r@   rA   rB   r>   r&   r   r,   rJ      s    
		*z$HunyuanImageRefinerPipeline.__init__  <|im_start|>system
Describe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>
<|im_start|>user
{}<|im_end|>"   r   promptstr | list[str]r   torch.device | Nonedtypetorch.dtype | NonerP   inttemplater4   drop_idxhidden_state_skip_layerc
                   s   |p| j }|p	|j}t|tr|gn|} fdd|D }
||
|| dddd|}||j|jdd}|j|	d   }|d d |d f }|jd d |d f }|j||d	}|j|d
}||fS )Nc                   s   g | ]}  |qS r   )format).0era   r   r,   
<listcomp>   s    zGHunyuanImageRefinerPipeline._get_qwen_prompt_embeds.<locals>.<listcomp>
max_lengthTpt)ri   padding
truncationreturn_tensors)	input_idsattention_maskoutput_hidden_statesr   r^   r   )r   )_execution_devicer^   
isinstancer4   torn   ro   hidden_states)rV   rA   r@   r[   r   r^   rP   ra   rb   rc   txt
txt_tokensencoder_hidden_statesr=   encoder_attention_maskr   rg   r,   _get_qwen_prompt_embeds   s(   

z3HunyuanImageRefinerPipeline._get_qwen_prompt_embedsr   str | list[str] | None
batch_sizenum_images_per_prompttorch.Tensor | Noneprompt_embeds_maskc           	   	   C  s   |p| j }|du rdg| }t|tr|gn|}|du r/| j| j| j||| j| j| jd\}}|j	\}}}|
d|d}||| |d}|
d|d}||| |}||fS )a  

        Args:
            prompt (`str` or `list[str]`, *optional*):
                prompt to be encoded
            device: (`torch.device`):
                torch device
            batch_size (`int`):
                batch size of prompts, defaults to 1
            num_images_per_prompt (`int`):
                number of images that should be generated per prompt
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. If not provided, text embeddings will be generated from `prompt` input
                argument.
            prompt_embeds_mask (`torch.Tensor`, *optional*):
                Pre-generated text mask. If not provided, text mask will be generated from `prompt` input argument.
            prompt_embeds_2 (`torch.Tensor`, *optional*):
                Pre-generated glyph text embeddings from ByT5. If not provided, will be generated from `prompt` input
                argument using self.tokenizer_2 and self.text_encoder_2.
            prompt_embeds_mask_2 (`torch.Tensor`, *optional*):
                Pre-generated glyph text mask from ByT5. If not provided, will be generated from `prompt` input
                argument using self.tokenizer_2 and self.text_encoder_2.
        N )rA   r@   r[   r   rP   ra   rb   r   )rr   rs   r4   rz   rA   r@   rP   rQ   rR   shaperepeatview)	rV   r[   r   r|   r}   r=   r   _seq_lenr   r   r,   encode_prompt   s(   
 


z)HunyuanImageRefinerPipeline.encode_promptc
           
   	     sT  | j d  dks| j d  dkr$td j d  d| d| d |	d urEt fdd|	D sEtd	 j d
 fdd|	D  |d urX|d urXtd| d| d|d u rd|d u rdtd|d ur{t|ts{t|ts{tdt	| |d ur|d urtd| d| d|d ur|d u rtd|d ur|d u rtdd S d S )Nr   r   z-`height` and `width` have to be divisible by z	 but are z and z(. Dimensions will be resized accordinglyc                 3  s    | ]}| j v V  qd S N_callback_tensor_inputsre   krV   r   r,   	<genexpr>,  s    

z;HunyuanImageRefinerPipeline.check_inputs.<locals>.<genexpr>z2`callback_on_step_end_tensor_inputs` has to be in z, but found c                   s   g | ]	}| j vr|qS r   r   r   r   r   r,   rh   0  s    z<HunyuanImageRefinerPipeline.check_inputs.<locals>.<listcomp>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`: zIf `prompt_embeds` are provided, `prompt_embeds_mask` also have to be passed. Make sure to generate `prompt_embeds_mask` from the same text encoder that was used to generate `prompt_embeds`.zIf `negative_prompt_embeds` are provided, `negative_prompt_embeds_mask` also have to be passed. Make sure to generate `negative_prompt_embeds_mask` from the same text encoder that was used to generate `negative_prompt_embeds`.)
rE   loggerwarningallr   r   rs   r4   listtype)
rV   r[   heightwidthnegative_promptr=   negative_prompt_embedsr   negative_prompt_embeds_mask"callback_on_step_end_tensor_inputsr   r   r,   check_inputs  sF   $z(HunyuanImageRefinerPipeline.check_inputs      ?c                 C  s.  t || j }t || j }||d||f}|	d u r"t||||d}	n|	j||d}	||jd krK||jd  dkrK||jd  }tj|g| dd}n||jd kri||jd  dkritd|jd  d| dt|t	rt
||krtd	t
| d
| dt||||d}|
| d|
 |  }|	|fS )Nr   )r1   r   r^   )r   r^   r   dimz'Cannot duplicate `image` of batch size z to z text prompts.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.)r`   rE   r   rt   r   torchcatr   rs   r   r'   )rV   image_latentsr|   num_channels_latentsr   r   r^   r   r1   r7   strengthr   additional_image_per_promptnoisecond_latentsr   r   r,   prepare_latentsN  s,     z+HunyuanImageRefinerPipeline.prepare_latentsc                 C  s~   t j| d d d d d df | fdd} | j\}}}}}| ddddd} | ||d |d ||} | ddddd } | S )Nr   r   r   r   r      )r   r   r   permutereshape
contiguous)r   r|   num_latent_channelsnum_latent_frameslatent_heightlatent_widthr   r   r,   _reorder_image_tokensy  s   (z1HunyuanImageRefinerPipeline._reorder_image_tokensc                 C  sl   | j \}}}}}| ddddd} | ||d |d ||} | ddddd} | ddddddf } | S )zPRestore image tokens order by splitting channels and removing first frame slice.r   r   r   r   r   N)r   r   r   )r7   r|   r   r   r   r   r   r   r,   _restore_image_tokens_order  s   z7HunyuanImageRefinerPipeline._restore_image_tokens_orderimager0   r1   torch.Generatorc                   sl   t  tr fddtjd D }tj|dd}ntj dd}	|}|jj
j }|S )Nc              	     s2   g | ]}t j||d    | ddqS )r   r.   r1   r3   )r;   r?   encode)re   ir1   r   rV   r   r,   rh     s    $zAHunyuanImageRefinerPipeline._encode_vae_image.<locals>.<listcomp>r   r   r.   r   )rs   r   ranger   r   r   r;   r?   r   r   rM   scaling_factor)rV   r   r1   r   r   r   r,   _encode_vae_image  s   

z-HunyuanImageRefinerPipeline._encode_vae_imagec                 C     | j S r   )_attention_kwargsr   r   r   r,   attention_kwargs     z,HunyuanImageRefinerPipeline.attention_kwargsc                 C  r   r   )_num_timestepsr   r   r   r,   num_timesteps  r   z)HunyuanImageRefinerPipeline.num_timestepsc                 C  r   r   )_current_timestepr   r   r   r,   current_timestep  r   z,HunyuanImageRefinerPipeline.current_timestepc                 C  r   r   )
_interruptr   r   r   r,   	interrupt  r   z%HunyuanImageRefinerPipeline.interruptg      
@r   pilTr   distilled_guidance_scalefloat | NonePipelineImageInput | Noner   r   r   r   r   r   .torch.Generator | list[torch.Generator] | Noner   r   output_type
str | Nonereturn_dictboolr   dict[str, Any] | Nonecallback_on_step_end!Callable[[int, int], None] | Noner   	list[str]c           ,        s  |p| j | j }|p| j | j }| j|||||||||d	 || _d| _d| _|dur3t|tr3d}n|durAt|trAt	|}n|j
d }| j}|dur^t|tjr^|j
d | jkr^|}n| j|||}|dj|| jjd}| j||
d}| jdur| j}ntdd	}|jo|jdk}| j||||||	d
\}}|| jj}|r| j||||||	d
\}}|| jj}| j|||	 | j|||j||
|d	\}}|du rtdd|d dd n|}t| j |||d\}}t!t	||| j j"  d}t	|| _#|du rt$dtj%|g|j
d  | jj|dd }| j&du r!i | _| j 'd | j(|d}t)|D ]\}} | j*r=q3| | _tj+||gdd| jj}!| ,|j
d |j}"||f||fd}#|j-||| d |.|#}$|$D ]I |/| j  fdd|#0 D }%t1 |j2}&| j3|& | jd |!|"|| j&dd|%d  _4W d   n	1 sw   Y  |5| j qr||$d }'|j}(| j j6|'| |ddd }|j|(krtj7j89 r||(}|dur
i })|D ]
}*t: |* |)|*< q|| || |)}+|+;d|}|+;d|}|t	|d ks%|d |kr)|d | j j" dkr)|<  t=r0t>?  q3W d   n	1 s=w   Y  d| _|dkrM|}n&|| jj| jj@jA }| B|}| jjC|ddd }| jjD|Ed|d}| F  |s}|fS tG|dS )!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, will use an empty negative
                prompt. Ignored when not using guidance.
            distilled_guidance_scale (`float`, *optional*, defaults to None):
                A guidance scale value for guidance distilled models. Unlike the traditional classifier-free guidance
                where the guidance scale is applied during inference through noise prediction rescaling, guidance
                distilled models take the guidance scale directly as an input parameter during forward pass. Guidance
                is enabled by setting `distilled_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. For
                guidance distilled models, this parameter is required. For non-distilled models, this parameter will be
                ignored.
            num_images_per_prompt (`int`, *optional*, defaults to 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.
            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 be 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.
            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.
            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.qwenimage.QwenImagePipelineOutput`] instead of a plain tuple.
            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.

        Examples:

        Returns:
            [`~pipelines.hunyuan_image.HunyuanImagePipelineOutput`] or `tuple`:
            [`~pipelines.hunyuan_image.HunyuanImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
            returning a tuple, the first element is a list with the generated images.
        )r   r=   r   r   r   r   NFr   r   r   )r^   )r   r1   )enabled)r[   r=   r   r   r|   r}   )	r   r|   r   r   r   r^   r   r1   r7   g      ?g        r   )r   zD`distilled_guidance_scale` is required for guidance-distilled model.rq   g     @@)totalr   )rx   ry   )stepr   timestepc                   s   i | ]}|t  |qS r   )rL   )re   
input_nameguider_state_batchr   r,   
<dictcomp>  s    z8HunyuanImageRefinerPipeline.__call__.<locals>.<dictcomp>)ru   r   guidancer   r   )r   r7   r=   latent)r   )imagesr   )HrS   rE   r   r   r   r   rs   r4   r   r'   r   rr   r   TensorrU   rO   
preprocess	unsqueezert   r?   r^   r   r>   r   _enablednum_conditionsr   rB   r   nplinspacer-   r(   maxorderr   r   tensorr   set_begin_indexprogress_bar	enumerater   r   expand	set_stateprepare_inputsprepare_modelsr%   rL   _identifier_keycache_context
noise_predcleanup_modelsr   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_steprM   r   r   decodepostprocesssqueezemaybe_free_model_hooksr   ),rV   r[   r   r   r   r   r   r   r   r}   r1   r7   r=   r   r   r   r   r   r   r   r   r|   r   r   r>   requires_unconditional_embedsr   r   num_warmup_stepsr   r   r   tlatent_model_inputr   guider_inputsguider_statecond_kwargscontext_namer   latents_dtypecallback_kwargsr   callback_outputsr   r   r,   __call__  s  b

$


	

&





6b


z$HunyuanImageRefinerPipeline.__call__r   )r(   r   r?   r   r@   r   rA   r   rB   r   r>   rC   )NNNrX   rY   rZ   r   )rA   r   r@   r   r[   r\   r   r]   r^   r_   rP   r`   ra   r4   rb   r`   rc   r`   )NNr   r   NN)r[   r{   r   r]   r|   r`   r}   r`   r=   r~   r   r~   )NNNNNN)Nr   )r   r0   r1   r   )(r[   r\   r   r\   r   r   r   r   r   r   r   r   r   r`   r   r   r}   r`   r1   r   r7   r~   r=   r~   r   r~   r   r~   r   r~   r   r   r   r   r   r   r   r   r   r   )__name__
__module____qualname____doc__model_cpu_offload_seqr   _optional_componentsrJ   rz   r   r   r   staticmethodr   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr	  __classcell__r   r   rW   r,   r<      s    	!'?
=
+






r<   )NNNN)r   r   r   r   r   r   r   r   )Nr.   )r/   r0   r1   r2   r3   r4   ),
__future__r   r!   typingr   r   numpyr   r   transformersr   r   guidersr   rO   r	   r
   modelsr   r   
schedulersr   utilsr   r   r   utils.torch_utilsr   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr
  r   r  r-   r;   r<   r   r   r   r,   <module>   s8   
=