
    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 ddlmZ ddl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       rd dl!m"c m#Z$ dZ%ndZ% ejL                  e'      Z(dZ)	 	 	 	 dde*de*de+de+fdZ,	 	 	 	 ddee*   deee-e
j\                  f      deee*      deee+      fdZ/ G d dee      Z0y)     N)AnyCallableDictListOptionalUnion)"Qwen2_5_VLForConditionalGenerationQwen2Tokenizer   )VaeImageProcessor)QwenImageLoraLoaderMixin)AutoencoderKLQwenImageQwenImageTransformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipeline   )QwenImagePipelineOutputTFaA  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import QwenImagePipeline

        >>> pipe = QwenImagePipeline.from_pretrained("Qwen/Qwen-Image", 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).images[0]
        >>> image.save("qwenimage.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           k/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/qwenimage/pipeline_qwenimage.pycalculate_shiftr%   ;   s;     
Z	K,$>?AQ%%A		Q	BI    num_inference_stepsdevice	timestepssigmasc                    ||t        d      |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS  | j                  |fd	|i| | j                  }||fS )a  
    Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
    custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

    Args:
        scheduler (`SchedulerMixin`):
            The scheduler to get timesteps from.
        num_inference_steps (`int`):
            The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
            must be `None`.
        device (`str` or `torch.device`, *optional*):
            The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
        timesteps (`List[int]`, *optional*):
            Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
            `num_inference_steps` and `sigmas` must be `None`.
        sigmas (`List[float]`, *optional*):
            Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
            `num_inference_steps` and `timesteps` must be `None`.

    Returns:
        `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
        second element is the number of inference steps.
    zYOnly one of `timesteps` or `sigmas` can be passed. Please choose one to set custom 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_timestepsr9   I   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            -            e Zd ZdZdZddgZdededede	d	e
f
 fd
Zdej                  dej                  fdZ	 	 	 d;deeee   f   deej&                     deej(                     fdZ	 	 	 	 	 d<deeee   f   deej&                     dedeej                     deej                     defdZ	 	 	 	 	 	 	 d=dZed        Zed        Zd Zd Zd Zd Z	 d>dZ e!d         Z"e!d!        Z#e!d"        Z$e!d#        Z%e!d$        Z& ejN                          e(e)      ddd%ddd&dd'dddddddd(d)dddgd*fdeeee   f   d+eeee   f   d,e*d-ee   d.ee   d/ed0eee*      d1e*ded2eeejV                  eejV                     f      deej                     deej                     deej                     d3eej                     d4eej                     d5ee   d6e,d7ee-ee.f      d8ee/eee-gdf      d9ee   def*d:              Z0 xZ1S )?QwenImagePipelinea  
    The QwenImage pipeline for text-to-image generation.

    Args:
        transformer ([`QwenImageTransformer2DModel`]):
            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 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 (`QwenTokenizer`):
            Tokenizer of class
            [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
    ztext_encoder->transformer->vaelatentsprompt_embedsr5   vaetext_encoder	tokenizertransformerc                 .   t         |           | j                  |||||       t        | dd       r"dt	        | j
                  j                        z  nd| _        t        | j                  dz        | _	        d| _
        d| _        d| _        d	| _        y )
N)r>   r?   r@   rA   r5   r>   r      )vae_scale_factor   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|>
<|im_start|>assistant
"      )super__init__register_modulesgetattrr4   r>   temperal_downsamplerD   r   image_processortokenizer_max_lengthprompt_template_encode prompt_template_encode_start_idxdefault_sample_size)selfr5   r>   r?   r@   rA   r3   s         r$   rI   zQwenImagePipeline.__init__   s     	%# 	 	
 KRRVX]_cJdS)E)E%F Fjk  1$BWBWZ[B[\$(! 'E#02-#& r&   hidden_statesmaskc                     |j                         }|j                  d      }||   }t        j                  ||j	                         d      }|S )Nr   dimr   )boolsumtorchsplittolist)rR   rS   rT   	bool_maskvalid_lengthsselectedsplit_results          r$   _extract_masked_hiddenz(QwenImagePipeline._extract_masked_hidden   sH    IIK	!!, +{{8]-A-A-CKr&   Npromptr(   dtypec                    |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}| j
                  }| j                  }|D cg c]  }|j                  |       }}| j                  || j                  |z   ddd      j                  |      }| j                  |j                  |j                  d      }	|	j                  d   }
| j                  |
|j                        }|D cg c]  }||d  	 }}|D cg c]A  }t        j                   |j#                  d      t        j$                  |j&                        C }}t)        |D cg c]  }|j#                  d       c}      }t        j*                  |D cg c]J  }t        j,                  ||j/                  ||j#                  d      z
  |j#                  d            g      L c}      }t        j*                  |D cg c]:  }t        j,                  ||j/                  ||j#                  d      z
        g      < c}      }|j                  ||      }||fS c c}w c c}w c c}w c c}w c c}w c c}w )	NTpt)
max_lengthpadding
truncationreturn_tensors)	input_idsattention_maskoutput_hidden_statesr   )rc   r(   r   )_execution_devicer?   rc   
isinstancestrrO   rP   formatr@   rN   torj   rk   rS   ra   rZ   onessizelongr(   maxstackcat	new_zeros)rR   rb   r(   rc   templatedrop_idxetxt
txt_tokensencoder_hidden_statesrS   split_hidden_statesattn_mask_listr   ur=   encoder_attention_masks                    r$   _get_qwen_prompt_embedsz)QwenImagePipeline._get_qwen_prompt_embeds   s1    14110**00'4&&..88+12axq!22^^D55@$[_pt $ 

"V* 	 !% 1 1 **%44!% !2 !

 .;;B?"99-IbIbc5HIq|II\opWX%**QVVAYejjRpp.AB166!9BCVijQRUYY1;;{QVVAY'>q	JKLj
 "'KYZaUYY1;;{QVVAY'>?@AZ"
 &((uV(D444/ 3 JpBj [s&   I?IAI$"I)AI.=?I3r   num_images_per_promptprompt_embeds_maskmax_sequence_lengthc                    |xs | j                   }t        |t              r|gn|}|t        |      n|j                  d   }|| j                  ||      \  }}|ddd|f   }|ddd|f   }|j                  \  }}	}|j                  d|d      }|j                  ||z  |	d      }|j                  d|d      }|j                  ||z  |	      }||fS )a1  

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            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.
        Nr   r   rm   )rn   ro   rp   r4   shaper   repeatview)
rR   rb   r(   r   r=   r   r   
batch_size_seq_lens
             r$   encode_promptzQwenImagePipeline.encode_prompt   s   , 1411'4&&$1$9S[}?R?RST?U
 040L0LVU[0\-M-%a)=*=)=&=>/3G4G3G0GH%++7A%,,Q0EqI%**:8M+MwXZ[/66q:OQRS/44ZBW5WY`a000r&   c           
          | j                   dz  z  dk7  s| j                   dz  z  dk7  r,t        j                  d j                   dz   d| d| d       |	Lt         fd|	D              s8t	        d j
                   d	|	D cg c]  }| j
                  vs| c}       ||t	        d
| d| d      ||t	        d      |7t        |t              s't        |t              st	        dt        |             ||t	        d| d| d      ||t	        d      ||t	        d      |
|
dkD  rt	        d|
       y y c c}w )Nr   r   z-`height` and `width` have to be divisible by z	 but are z and z(. Dimensions will be resized accordinglyc              3   :   K   | ]  }|j                   v   y wr   )_callback_tensor_inputs).0krR   s     r$   	<genexpr>z1QwenImagePipeline.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`: 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   z9`max_sequence_length` cannot be greater than 1024 but is )
rD   loggerwarningallr,   r   ro   rp   listtype)rR   rb   heightwidthnegative_promptr=   negative_prompt_embedsr   negative_prompt_embeds_mask"callback_on_step_end_tensor_inputsr   r   s   `           r$   check_inputszQwenImagePipeline.check_inputs  s3    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*++]_ 
 $);)C Q  "-2M2U u  */BT/IXYlXmnoo 0J*= pHs   EE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   permutereshape)r<   r   num_channels_latentsr   r   s        r$   _pack_latentszQwenImagePipeline._pack_latentsB  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  d||      } | S )Nr   r   r   r   r   r   )r   intr   r   r   )r<   r   r   rD   r   num_patcheschannelss          r$   _unpack_latentsz!QwenImagePipeline._unpack_latentsJ  s    ,3MM)
K c&k&6&:;<SZ$4q$89:,,z6Q;
HPQMSTVWX//!Q1a3//*h5.A1feT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)r>   enable_slicingrR   s    r$   enable_vae_slicingz$QwenImagePipeline.enable_vae_slicingZ      
 	!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)r>   disable_slicingr   s    r$   disable_vae_slicingz%QwenImagePipeline.disable_vae_slicinga  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)r>   enable_tilingr   s    r$   enable_vae_tilingz#QwenImagePipeline.enable_vae_tilingh  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)r>   disable_tilingr   s    r$   disable_vae_tilingz$QwenImagePipeline.disable_vae_tilingp  r   r&   c	                 p   dt        |      | j                  dz  z  z  }dt        |      | j                  dz  z  z  }|d|||f}	||j                  ||      S t        |t              r)t        |      |k7  rt        dt        |       d| d      t        |	|||      }| j                  |||||      }|S )Nr   r   r(   rc   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(   rc   )	r   rD   rr   ro   r   r4   r,   r   r   )
rR   r   r   r   r   rc   r(   r   r<   r   s
             r$   prepare_latentsz!QwenImagePipeline.prepare_latentsw  s     c&kd&;&;a&?@ASZD$9$9A$=>?Q 4feD::V5:99i&3y>Z+GA#i.AQ R&<'gi 
 u	&PUV$$Wj:NPVX]^r&   c                     | j                   S r   )_guidance_scaler   s    r$   guidance_scalez QwenImagePipeline.guidance_scale  s    ###r&   c                     | j                   S r   )_attention_kwargsr   s    r$   attention_kwargsz"QwenImagePipeline.attention_kwargs      %%%r&   c                     | j                   S r   )_num_timestepsr   s    r$   num_timestepszQwenImagePipeline.num_timesteps  s    """r&   c                     | j                   S r   )_current_timestepr   s    r$   current_timestepz"QwenImagePipeline.current_timestep  r   r&   c                     | j                   S r   )
_interruptr   s    r$   	interruptzQwenImagePipeline.interrupt  s    r&   g      @2         ?pilTi   r   true_cfg_scaler   r   r'   r*   r   r   r   r   output_typereturn_dictr   callback_on_step_endr   c                    |xs | j                   | j                  z  }|xs | j                   | j                  z  }| j                  ||||||||||
       || _        || _        d| _        d| _        |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                  }|duxs
 |duxr |du}|dkD  xr |}| j                  |||||	|      \  }}|r| j                  |||||	|      \  }}| j                  j                  j                   dz  }| j#                  ||	z  ||||j$                  ||
|      }d|| j                  z  dz  || j                  z  dz  fgg|z  }|t'        j(                  d	d|z  |      n|}|j                  d   }t+        || j,                  j                  j/                  d
d      | j,                  j                  j/                  dd      | j,                  j                  j/                  dd      | j,                  j                  j/                  dd            }t1        | j,                  ||||      \  }}t3        t        |      || j,                  j4                  z  z
  d      }t        |      | _        | j                  j                  j8                  rGt;        j<                  dg||t:        j>                        } | jA                  |j                  d         } nd} | jB                  i | _        | |jE                  d      jG                         nd}!| |jE                  d      jG                         nd}"| j,                  jI                  d       | jK                  |      5 }#tM        |      D ]V  \  }$}%| jN                  r|%| _        |%jA                  |j                  d         jQ                  |j$                        }&| j                  jS                  d      5  | j                  ||&dz  | ||||!| jB                  d	      d   }'ddd       |r| j                  jS                  d      5  | j                  ||&dz  | ||||"| jB                  d	      d   }(ddd       (|'|(z
  z  z   })t;        jT                  |'dd      }*t;        jT                  |)dd      }+|)|*|+z  z  }'|j$                  },| j,                  jW                  '|%|d      d   }|j$                  |,k7  r9t:        jX                  jZ                  j]                         r|jQ                  |,      }|Hi }-|D ]  }.t_               |.   |-|.<     || |$|%|-      }/|/ja                  d|      }|/ja                  d|      }|$t        |      dz
  k(  s'|$dz   |kD  r/|$dz   | j,                  j4                  z  dk(  r|#jc                          td        sCtg        jh                          Y 	 ddd       d| _        |d k(  r|}0n| jk                  |||| j                        }|jQ                  | jl                  j$                        }t;        jn                  | jl                  j                  jp                        js                  d| jl                  j                  jt                  ddd      jQ                  |jv                  |j$                        }1d	t;        jn                  | jl                  j                  jx                        js                  d| jl                  j                  jt                  ddd      jQ                  |jv                  |j$                        z  }2||2z  |1z   }| jl                  j{                  |d      d   dddddf   }0| j|                  j                  |0|!      }0| j                          |s|0fS t        |0"      S # 1 sw Y   xY w# 1 sw Y   `xY w# 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 `true_cfg_scale` is
                not greater than `1`).
            true_cfg_scale (`float`, *optional*, defaults to 1.0):
                When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
            height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
                The height in pixels of the generated image. This is set to 1024 by default for the best results.
            width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
                The width in pixels of the generated image. This is set to 1024 by default for the best results.
            num_inference_steps (`int`, *optional*, defaults to 50):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            sigmas (`List[float]`, *optional*):
                Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
                their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
                will be used.
            guidance_scale (`float`, *optional*, defaults to 3.5):
                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.

                This parameter in the pipeline is there to support future guidance-distilled models when they come up.
                Note that passing `guidance_scale` to the pipeline is ineffective. To enable classifier-free guidance,
                please pass `true_cfg_scale` and `negative_prompt` (even an empty negative prompt like " ") should
                enable classifier-free guidance computations.
            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.
            max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.

        Examples:

        Returns:
            [`~pipelines.qwenimage.QwenImagePipelineOutput`] or `tuple`:
            [`~pipelines.qwenimage.QwenImagePipelineOutput`] 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   r   NFr   r   )rb   r=   r   r(   r   r   r   r   r   base_image_seq_len   max_image_seq_len   r         ?r   ffffff?)r*   r#   r   rV   )totalcondi  )	rS   timestepguidanceencoder_hidden_states_maskr   
img_shapestxt_seq_lensr   r   uncondrm   T)rW   keepdim)r   r<   r=   latent)r   )images)BrQ   rD   r   r   r   r   r   ro   rp   r   r4   r   rn   r   rA   configin_channelsr   rc   nplinspacer%   r5   getr9   rv   orderr   guidance_embedsrZ   fullfloat32expandr   rY   r\   set_begin_indexprogress_bar	enumerater   rr   cache_contextnormstepbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   r>   tensorlatents_meanr   z_dimr(   latents_stddecoderM   postprocessmaybe_free_model_hooksr   )3rR   rb   r   r   r   r   r'   r*   r   r   r   r<   r=   r   r   r   r   r   r   r   r   r   r   r(   has_neg_promptdo_true_cfgr   r   r    r#   r)   num_warmup_stepsr   r   negative_txt_seq_lensr   itr   
noise_predneg_noise_pred	comb_pred	cond_norm
noise_normlatents_dtypecallback_kwargsr   callback_outputsimager  r  s3                                                      r$   __call__zQwenImagePipeline.__call__  s   R K433d6K6KKI11D4I4II 	+'#91(C/Q 3 	 	
  .!1!% *VS"9JJvt$<VJ&,,Q/J''(4 
"$.Z3NVZ3Z 	 %q(;^,0,>,>'1"7 3 -? -
)) BFBTBT&4#>&;$7 CU C?"$?  $//66BBaG&&.. 	
 6T%:%::a?$J_J_A_cdAdefgjtt
 TZSaS!&9"9;NOgma(NN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 *<NN*
&	& s9~0CdnnFZFZ0ZZ\]^!)n ""22zz1#~fEMMZHw}}Q'78HH  (%'D"ASA_)--!-4;;=ei?Z?f'+++299;lp 	
 	&&q)%89 ?	#\!), >#1>>)*&88GMM!$4588G%%33F; !%!1!1&-!)D!)3E.;#-%1)-)>)>$) "2 
" 
"J ))77A )-)9)9*1%-_%-7R2H'1)>-1-B-B(- *: 
* 
* !/:P^C^1_ _I %

:2t LI!&I2t!LJ!*i*.D!EJ !(..--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}>#?	#B "&("E**7FE4CXCXYGjj0GTXX__99:a..1a8GNNGMM2 
 TXX__-H-H I N NqRVRZRZRaRaRgRgijlmop q t t! K +l:GHHOOGO?B1a7KE((44U4TE 	##%8O&e44c  -?	# ?	#sD   A9_9+_>%_9#+_,E_9)_9_)$_9,_61_99`)NNN)Nr   NNrE   )NNNNNNNr   )2__name__
__module____qualname____doc__model_cpu_offload_seqr   r   r   r	   r
   r   rI   rZ   Tensorra   r   rp   r   r   r(   rc   r   r   r   r   staticmethodr   r   r   r   r   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGfloat	GeneratorrX   r   r   r   r  __classcell__)r3   s   @r$   r;   r;      s   $ =(/:'2' $' 9	'
 "' 1'4ELL   )-)-'+	$5c49n%$5 &$5 $	$5R *.%&0459#''1c49n%'1 &'1  #	'1
  -'1 %U\\2'1 !'1\ #$(+/ 5pn    "#!"  @ $ $ & & # # & &   U]]_12 )-15 # $##%(, #%&MQ*.04599=>B%* 59KO9B#&-i5c49n%i5 sDI~.i5 	i5
 i5 }i5 !i5 e%i5 i5  #i5 E%//43H"HIJi5 %,,'i5  -i5 %U\\2i5 !) 6i5  &.ell%;!i5" c]#i5$ %i5& #4S>2'i5( 'xc40@$0F'GH)i5* -1I+i5, !-i5 3 i5r&   r;   )r   r   r   r   )NNNN)1r.   typingr   r   r   r   r   r   numpyr   rZ   transformersr	   r
   rM   r   loadersr   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%   rp   r(   r9   r;   r   r&   r$   <module>r4     s    = =   K 0 / I 9 O O - . 4 ))MM 
		H	% & 

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vR	5)+C R	5r&   