
    
3j%                    h   S SK Jr  S SKrS SKJrJr  S SKrS SKrS SK	J
r
Jr  SSKJr  SSKJrJr  SSKJrJr  SS	KJr  SS
KJrJrJr  SSKJr  SSKJr  SSKJr  \" 5       (       a  S SK J!s  J"r#  Sr$OSr$\RJ                  " \&5      r'Sr(    S       SS jjr) S     SS jjr* " S S\5      r+g)    )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")
        ```
c                   Ub  Ub  [        S5      eUb  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
X2S.UD6  U R                  n[        U5      nX14$ Ub  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
XBS.UD6  U R                  n[        U5      nX14$ U R                  " U4S	U0UD6  U R                  nX14$ )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 values	timestepszThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r   devicesigmaszv'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)	schedulernum_inference_stepsr   r   r   kwargsaccepts_timestepsaccept_sigmass           y/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/pipelines/hunyuan_image/pipeline_hunyuanimage_refiner.pyretrieve_timestepsr+   A   s}   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	M)MfM''	!)n )) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	GvGG''	!)n )) 	 3MFMfM''	))    c                   [        U S5      (       a!  US:X  a  U R                  R                  U5      $ [        U S5      (       a   US:X  a  U R                  R                  5       $ [        U S5      (       a  U R                  $ [        S5      e)Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrr.   r/   moder1   AttributeError)encoder_output	generatorsample_modes      r*   retrieve_latentsr8   }   s}     ~}--+2I))00;;		/	/K84K))..00		+	+%%%RSSr,   c                    ^  \ rS rSrSrSrSS/rS/r S           SU 4S jjjr       S                 SS	 jjr	      S           S S jjr
      S!S jr  S"S jr\S 5       r\S 5       rS#S jr\S 5       r\S 5       r\S 5       r\S 5       r\R.                  " 5       \" \5      SSSSSSSSS
SSSSSSSSSSS/4                                       S$S jj5       5       rSrU =r$ )%HunyuanImageRefinerPipeline   aE  
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->vaer1   prompt_embedsguiderNc           	       > [         TU ]  5         U R                  UUUUUUS9  [        U SS 5      (       a   U R                  R
                  R                  OSU l        [        U R                  S9U l	        SU l
        SU l        SU l        SU l        [        U S	S 5      (       a)  U R                  R
                  R                  S
-  U l        g SU l        g )N)vaetext_encoder	tokenizertransformerr%   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_ratiorD   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#   s          r*   rI   $HunyuanImageRefinerPipeline.__init__   s     	%# 	 	
 NUUY[`bfMgMg I Imo0$BWBWX$'! '^#02-#% KRSWYfhlKmKmt//66BBaGsur,   c
                   U=(       d    U R                   nU=(       d    UR                  n[        U[        5      (       a  U/OUnU V
s/ s H  oR	                  U
5      PM     nn
U" XU-   SSSS9R                  U5      nU" UR                  UR                  SS9nUR                  U	S-   *    nUS S 2US 24   nUR                  S S 2US 24   nUR                  XTS9nUR                  US9nX4$ s  sn
f )	N
max_lengthTpt)rX   padding
truncationreturn_tensors)	input_idsattention_maskoutput_hidden_statesr   dtyper   )r   )	_execution_devicera   
isinstancestrformattor]   r^   hidden_states)rU   rA   r@   promptr   ra   rO   templatedrop_idxhidden_state_skip_layeretxt
txt_tokensencoder_hidden_statesr<   encoder_attention_masks                   r*   _get_qwen_prompt_embeds3HunyuanImageRefinerPipeline._get_qwen_prompt_embeds   s    1411+++'44&&+126aq!628;\^bsw

"V* 	 !- **%44!%!

 .;;>UXY>Y<Z[%al3!+!:!:1hi<!H%((u(D!7!:!:&!:!I44% 3s   	C0r   c           
        U=(       d    U R                   nUc  S/U-  n[        U[        5      (       a  U/OUnUcI  U R                  U R                  U R
                  UUU R                  U R                  U R                  S9u  pVUR                  u  pxnUR                  SUS5      nUR                  X4-  US5      nUR                  SUS5      nUR                  X4-  U5      nXV4$ )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.
 )rA   r@   rh   r   rO   ri   rj   r   )rb   rc   rd   rq   rA   r@   rO   rP   rQ   shaperepeatview)	rU   rh   r   
batch_sizenum_images_per_promptr<   prompt_embeds_mask_seq_lens	            r*   encode_prompt)HunyuanImageRefinerPipeline.encode_prompt   s    @ 1411>TJ&F'44&& 040L0L..!..%)%>%>44>> 1M 1-M &++A%,,Q0EqI%**:+MwXZ[/66q:OQRS/44Z5WY`a00r,   c
           
       ^  UT R                   S-  -  S:w  d  UT R                   S-  -  S:w  a,  [        R                  ST R                   S-   SU SU S35        U	bW  [        U 4S jU	 5       5      (       d=  [	        ST R
                   S	U	 V
s/ s H  oT R
                  ;  d  M  U
PM     sn
 35      eUb  Ub  [	        S
U SU S35      eUc  Uc  [	        S5      eUbA  [        U[        5      (       d,  [        U[        5      (       d  [	        S[        U5       35      eUb  Ub  [	        SU SU S35      eUb  Uc  [	        S5      eUb  Uc  [	        S5      eg g s  sn
f )Nr   r   z-`height` and `width` have to be divisible by z	 but are z and z(. Dimensions will be resized accordinglyc              3  @   >#    U  H  oTR                   ;   v   M     g 7fN)_callback_tensor_inputs).0krU   s     r*   	<genexpr>;HunyuanImageRefinerPipeline.check_inputs.<locals>.<genexpr>,  s      F
7Y!---7Ys   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`: 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`.)
rD   loggerwarningallr   r   rc   rd   listtype)rU   rh   heightwidthnegative_promptr<   negative_prompt_embedsr{   negative_prompt_embeds_mask"callback_on_step_end_tensor_inputsr   s   `          r*   check_inputs(HunyuanImageRefinerPipeline.check_inputs  s!    T**Q./14AVAVYZAZ8[_`8`NN?@U@UXY@Y?ZZcdjckkpqvpw  x`  a .9# F
7YF
 C
 C
 DTEaEaDbbn  |^  pH  |^vw  ko  kG  kG  bGpq  |^  pH  oI  J  -";08N}o ^0 0  ^ 5w  FC)@)@TZ\`IaIaQRVW]R^Q_`aa&+A+M9/9J K*++]_ 
 $);)C Q  "-2M2U u  3V-3 pHs   E%Ec                   [        U5      U R                  -  n[        U5      U R                  -  nX#SXE4nU	c  [        XXvS9n	OU	R                  XvS9n	X!R                  S   :  a@  X!R                  S   -  S:X  a+  X!R                  S   -  n[
        R                  " U/U-  SS9nOFX!R                  S   :  a4  X!R                  S   -  S:w  a  [        SUR                  S    SU S35      e[        U[        5      (       a*  [        U5      U:w  a  [        S	[        U5       S
U S35      e[        XXvS9nX-  SU
-
  U-  -   nX4$ )Nr   )r6   r   ra   )r   ra   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.)intrD   r   rf   rv   torchcatr   rc   r   r$   )rU   image_latentsry   num_channels_latentsr   r   ra   r   r6   r1   strengthrv   additional_image_per_promptnoisecond_latentss                  r*   prepare_latents+HunyuanImageRefinerPipeline.prepare_latentsN  sy    V 5 55E
d3331fD?"5fZGjjj<G++A..:@S@STU@V3VZ[3[*48K8KA8N*N'!II}o8S&SYZ[M--a00ZBUBUVWBX5X\]5]9-:M:Ma:P9QQUV`Uaaop  i&&3y>Z+GA#i.AQ R&<'gi 
 UT'1x<=*HH$$r,   c                   [         R                  " U S S 2S S 2S S24   U 4SS9n U R                  u  pp4nU R                  SSSSS5      n U R	                  XS-  US-  XE5      n U R                  SSSSS5      R                  5       n U $ )Nr   r   r   r   r      )r   r   rv   permutereshape
contiguous)r   ry   num_latent_channelsnum_latent_frameslatent_heightlatent_widths         r*   _reorder_image_tokens1HunyuanImageRefinerPipeline._reorder_image_tokensy  s    		=Arr#:M"JPQRZgZmZmW
):<%--aAq!<%--Q.0Ca0G
 &--aAq!<GGIr,   c                    U R                   u  pp4nU R                  SSSSS5      n U R                  XS-  US-  XE5      n U R                  SSSSS5      n U SS2SS2SS24   n U $ )zPRestore image tokens order by splitting channels and removing first frame slice.r   r   r   r   r   N)rv   r   r   )r1   ry   r   r   r   r   s         r*   _restore_image_tokens_order7HunyuanImageRefinerPipeline._restore_image_tokens_order  s~     [bZgZgW
):<//!Q1a0//A-/Ba/G
 //!Q1a0!Q(#r,   c                   [        U[        5      (       ag  [        UR                  S   5       Vs/ s H.  n[	        U R
                  R                  XUS-    5      X#   SS9PM0     nn[        R                  " USS9nO$[	        U R
                  R                  U5      USS9nU R                  U5      nX@R
                  R                  R                  -  nU$ s  snf )Nr   r   r/   )r6   r7   r   )rc   r   rangerv   r8   r?   encoder   r   r   rL   scaling_factor)rU   imager6   ir   s        r*   _encode_vae_image-HunyuanImageRefinerPipeline._encode_vae_image  s    i&& u{{1~..A !1q51A!Bilhpq.   "IIm;M,TXX__U-CyfnoM22=A%(F(FFs   5Cc                    U R                   $ r   )_attention_kwargsrU   s    r*   attention_kwargs,HunyuanImageRefinerPipeline.attention_kwargs      %%%r,   c                    U R                   $ r   )_num_timestepsr   s    r*   num_timesteps)HunyuanImageRefinerPipeline.num_timesteps  s    """r,   c                    U R                   $ r   )_current_timestepr   s    r*   current_timestep,HunyuanImageRefinerPipeline.current_timestep  r   r,   c                    U R                   $ r   )
_interruptr   s    r*   	interrupt%HunyuanImageRefinerPipeline.interrupt  s    r,   g      
@r   pilTc                x   U=(       d    U R                   U R                  -  nU=(       d    U R                   U R                  -  nU R                  UUUUUUUUUS9	  UU l        SU l        SU l        Ub  [        U[        5      (       a  SnO3Ub!  [        U[        5      (       a  [        U5      nOUR                  S   nU R                  nUb?  [        U[        R                  5      (       a   UR                  S   U R                  :X  a  UnO^U R                  R!                  XEU5      nUR#                  S5      R%                  UU R&                  R(                  S9nU R+                  XJS9nU R,                  b  U R,                  nO	[/        SS	9nUR0                  =(       a    UR2                  S:  nU R5                  UUUUUU	S
9u  pUR%                  U R6                  R(                  5      nU(       a<  U R5                  UUUUUU	S
9u  nnUR%                  U R6                  R(                  5      nU R9                  UUU	-  U R                  UUUR(                  UU
US9	u  nnUc  [:        R<                  " SSUS-   5      SS OUn[?        U R@                  UUUS9u  nn[C        [        U5      XpR@                  RD                  -  -
  S5      n[        U5      U l#        Uc  [I        S5      e[        RJ                  " U/UR                  S   -  U R6                  R(                  US9S-  nU RL                  c  0 U l        U R@                  RO                  S5        U RQ                  US9 n[S        U5       GH  u  nn U RT                  (       a  M  U U l        [        RV                  " UU/SS9R%                  U R6                  R(                  5      n!U RY                  UR                  S   5      R%                  UR(                  5      n"X4X4S.n#UR[                  UUU S9  UR]                  U#5      n$U$ H  n%UR_                  U R6                  5        U#Ra                  5        V&s0 s H  n&U&[c        U%U&5      _M     n'n&[c        U%URd                  5      n(U R6                  Rg                  U(5         U R6                  " SU!U"UU RL                  SS.U'D6S   U%l4        SSS5        URk                  U R6                  5        M     U" U$5      S   n)UR(                  n*U R@                  Rm                  U)U USS9S   nUR(                  U*:w  a>  [        Rn                  Rp                  Rs                  5       (       a  UR%                  U*5      nUbJ  0 n+U H  n,[u        5       U,   U+U,'   M     U" U UU U+5      n-U-Rw                  SU5      nU-Rw                  SU5      nU[        U5      S-
  :X  d)  US-   U:  a0  US-   U R@                  RD                  -  S:X  a  URy                  5         [z        (       d  GM  [|        R~                  " 5         GM     SSS5        SU l        US:X  a  UnOUR%                  U R&                  R(                  5      U R&                  R                  R                  -  nU R                  U5      nU R&                  R                  USS9S   nU R                  R                  UR                  S5      US9nU R                  5         U(       d  U4$ [        US9$ s  sn&f ! , (       d  f       GNO= f! , (       d  f       N= f)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   )ra   )r   r6   )enabled)rh   r<   r{   r   ry   rz   )	r   ry   r   r   r   ra   r   r6   r1   g      ?g        ru   )r   zD`distilled_guidance_scale` is required for guidance-distilled model.r`   g     @@)totalr   )ro   rp   )stepr&   timestep)rg   r   guidancer   return_dict)r   r1   r<   latent)output_type)imagesr   )HrR   rD   r   r   r   r   rc   rd   r   r$   rv   rb   r   TensorrT   rN   
preprocess	unsqueezerf   r?   ra   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"   rK   _identifier_keycache_context
noise_predcleanup_modelsr   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_steprL   r   r   decodepostprocesssqueezemaybe_free_model_hooksr   ).rU   rh   r   distilled_guidance_scaler   r   r   r&   r   rz   r6   r1   r<   r{   r   r   r   r   r   callback_on_step_endr   ry   r   r   r=   requires_unconditional_embedsr   r   num_warmup_stepsr   r   r   tlatent_model_inputr   guider_inputsguider_stateguider_state_batch
input_namecond_kwargscontext_namer   latents_dtypecallback_kwargsr   callback_outputss.                                                 r*   __call__$HunyuanImageRefinerPipeline.__call__  s   D K433d6K6KKI11D4I4II 	+'#91(C/Q 	 
	
 "2!% *VS"9"9JJvt$<$<VJ&,,Q/J'' E5<<!@!@U[[QR^W[WkWkEk!M((33E5IEOOA&))&)GE 222TM ;;"[[F 2%@F(.(UF<Q<QTU<U%,0,>,>'1!"7 -? -
) &(()9)9)?)?@( ""&4#>%&; # &+ &<%>%>t?O?O?U?U%V" !% 4 4'!$99!%!5!5%% !5 
!
 IOS#':Q'>?D\b);DNNL_agpv)w&	&s9~0CnnFZFZ0ZZ\]^!)n $+cddLL23gmmA6FFdN^N^NdNdmst 	
   (%'D" 	&&q)%89\!),1>>)*&%*YY/FA%N%Q%QRVRbRbRhRh%i"88GMM!$4588G
 /<-T/A._!   a=P[\ ]  &44]C
 +7&))$*:*:; _l^p^p^r#^rPZ
G,>
$KK^r   #
 $++=v?U?U#VL))77E8<8H8H 9*<%-%--1-B-B(-9 *9 9*5 F ))$*:*:;- +7J $L1!4
 !(..--j!WRW-XYZ[==M1~~))6688")**]";'3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLN - :D "&("Ejj0488??3Q3QQG66w?GHHOOGO?BE((44U]]15ES^4_E 	##%8O)77Y# FEY :9s>   #C9\+\
33\+&+\	E\+"\+\+
\(#\++
\9)r   r   r   r   rR   rN   rT   rP   rQ   rO   rD   r   )r%   r   r?   r   r@   r   rA   r   rB   r   r=   z#AdaptiveProjectedMixGuidance | None)NNNi  z<|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   )rA   r   r@   r   rh   str | list[str]r   torch.device | Nonera   ztorch.dtype | NonerO   r   ri   rd   rj   r   rk   r   )NNr   r   NN)rh   zstr | list[str] | Noner   r  ry   r   rz   r   r<   torch.Tensor | Noner{   r  )NNNNNN)Ng      ?)r   torch.Tensorr6   ztorch.Generator)(rh   r
  r   r
  r   zfloat | Noner   zPipelineImageInput | Noner   
int | Noner   r  r&   r   r   list[float] | Nonerz   r   r6   z.torch.Generator | list[torch.Generator] | Noner1   r  r<   r  r{   r  r   r  r   r  r   z
str | Noner   boolr   zdict[str, Any] | Noner   z!Callable[[int, int], None] | Noner   z	list[str])__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seqr   _optional_componentsrI   rq   r~   r   r   staticmethodr   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr  __static_attributes____classcell__)r#   s   @r*   r:   r:      s,     =(/:$: 7;v2v .v 9	v
 "v 4v 4v vB #'&*$($( ^'(#5!#5 9#5  	#5
 $#5 "#5 "#5 #5 #5 "%#5N *.&*%&-12681&81 $81 	81
  #81 +81 081~ #$(+/1z )%V 	 	   & & # # & &   ]]_12 #'+/15+/! #$%)%&DH'+-1266:;?"' 26BF9B+|8|8 )|8 #/	|8
 )|8 |8 |8 !|8 #|8  #|8 B|8 %|8 +|8 0|8 !4|8  &9!|8"  #|8$ %|8& 0'|8( @)|8* -6+|8 3 |8r,   r:   )NNNN)r&   r  r   zstr | torch.device | Noner   zlist[int] | Noner   r  )Nr/   )r5   r  r6   ztorch.Generator | Noner7   rd   ),
__future__r   r   typingr   r   numpyr   r   transformersr   r   guidersr	   rN   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+   r8   r:   r   r,   r*   <module>r-     s    #      K 3 D V 9 O O - . 7 ))MM 
		H	% . '+(,"&!%8*#8* &8*  	8*
 8*z `h
T 
T-C
TY\
Th	8"3 h	8r,   