
    bi                        d dl Z d dlZd dlmZmZmZmZmZmZ d dl	Z
d dlZd dlmZmZmZ ddlmZ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jR                  e*      Z+dZ,	 	 	 	 d#de-de-de.de.fdZ/	 	 	 	 d$dee-   deee0ejb                  f      deee-      deee.      fdZ2	 d%dejf                  deejh                     de0fdZ5d  Z6 G d! d"e!e      Z7y)&    N)AnyCallableDictListOptionalUnion)"Qwen2_5_VLForConditionalGenerationQwen2TokenizerQwen2VLProcessor   )PipelineImageInputVaeImageProcessor)QwenImageLoraLoaderMixin)AutoencoderKLQwenImageQwenImageTransformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipeline   )QwenImagePipelineOutputTFa  
    Examples:
        ```py
        >>> import torch
        >>> from PIL import Image
        >>> from diffusers import QwenImageEditPipeline
        >>> from diffusers.utils import load_image

        >>> pipe = QwenImageEditPipeline.from_pretrained("Qwen/Qwen-Image-Edit", torch_dtype=torch.bfloat16)
        >>> pipe.to("cuda")
        >>> image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png"
        ... ).convert("RGB")
        >>> prompt = (
        ...     "Make Pikachu hold a sign that says 'Qwen Edit is awesome', yarn art style, detailed, vibrant colors"
        ... )
        >>> # Depending on the variant being used, the pipeline call will slightly vary.
        >>> # Refer to the pipeline documentation for more details.
        >>> image = pipe(image, prompt, num_inference_steps=50).images[0]
        >>> image.save("qwenimage_edit.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           p/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/qwenimage/pipeline_qwenimage_edit.pycalculate_shiftr'   D   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_timestepsr;   R   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(   encoder_output	generatorsample_modec                     t        | d      r |dk(  r| j                  j                  |      S t        | d      r|dk(  r| j                  j                         S t        | d      r| j                  S t        d      )Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrr@   rA   moderC   AttributeError)r<   r=   r>   s      r&   retrieve_latentsrG      st     ~}-+2I))00;;		/K84K))..00		+%%%RSSr(   c                     t        j                  | |z        }||z  }t        |dz        dz  }t        |dz        dz  }||d fS )N    )mathsqrtround)target_arearatiowidthheights       r&   calculate_dimensionsrQ      sQ    IIkE)*EU]F%"*"E6B;"$F&$r(   c            /           e Zd ZdZdZddgZde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(                     deej*                     fdZ	 	 	 	 	 	 d?deeee   f   deej                     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ej                  dej:                  fdZd Zd  Z d! Z!d" Z"	 dAd#Z#e$d$        Z%e$d%        Z&e$d&        Z'e$d'        Z(e$d(        Z) ejT                          e+e,      d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-   deeee   f   d/eeee   f   d0e.d1ee   d2ee   d3ed4eee.      d5e.dedeeej:                  eej:                     f      deej                     deej                     deej                     d6eej                     d7eej                     d8ee   d9e/d:ee0ee1f      d;ee2eee0gdf      d<ee   def,d=              Z3 xZ4S )BQwenImageEditPipelinea  
    The Qwen-Image-Edit pipeline for image editing.

    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->vaerC   prompt_embedsr7   vaetext_encoder	tokenizer	processortransformerc                    t         |           | j                  ||||||       t        | dd       r"dt	        | j
                  j                        z  nd| _        t        | dd       r | j
                  j                  j                  nd| _
        t        | j                  dz        | _        || _        d| _        d| _        d	| _        d
| _        y )N)rU   rV   rW   rX   rY   r7   rU   r         )vae_scale_factor   a  <|im_start|>system
Describe the key features of the input image (color, shape, size, texture, objects, background), then explain how the user's text instruction should alter or modify the image. Generate a new image that meets the user's requirements while maintaining consistency with the original input where appropriate.<|im_end|>
<|im_start|>user
<|vision_start|><|image_pad|><|vision_end|>{}<|im_end|>
<|im_start|>assistant
@      )super__init__register_modulesgetattrr6   rU   temperal_downsampler]   configz_dimlatent_channelsr   image_processorvl_processortokenizer_max_lengthprompt_template_encode prompt_template_encode_start_idxdefault_sample_size)selfr7   rU   rV   rW   rX   rY   r5   s          r&   rb   zQwenImageEditPipeline.__init__   s     	%# 	 	
 KRRVX]_cJdS)E)E%F Fjk8?eT8Rtxx44XZ  1$BWBWZ[B[\%$(! '[#02-#& r(   hidden_statesmaskc                     |j                         }|j                  d      }||   }t        j                  ||j	                         d      }|S )Nr   dimr   )boolsumtorchsplittolist)ro   rp   rq   	bool_maskvalid_lengthsselectedsplit_results          r&   _extract_masked_hiddenz,QwenImageEditPipeline._extract_masked_hidden   sH    IIK	!!, +{{8]-A-A-CKr(   Npromptimager*   dtypec                     |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}| j
                  }| j                  }|D cg c]  }|j                  |       }}| j                  ||dd      j                  |      }	| j                  |	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.                  ||j1                  ||j%                  d      z
  |j%                  d            g      L c}      }t!        j,                  |D cg c]:  }t!        j.                  ||j1                  ||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)textimagespaddingreturn_tensors)	input_idsattention_maskpixel_valuesimage_grid_thwoutput_hidden_statesr   )r   r*   r   )_execution_devicerV   r   
isinstancestrrl   rm   formatrX   tor   r   r   r   rp   r~   rw   onessizelongr*   maxstackcat	new_zeros)ro   r   r   r*   r   templatedrop_idxetxtmodel_inputsoutputsrp   split_hidden_statesattn_mask_listr   urT   encoder_attention_masks                     r&   _get_qwen_prompt_embedsz-QwenImageEditPipeline._get_qwen_prompt_embeds   s8    14110**00'4&&..88+12axq!22~~	 & 

 "V* 	 ##",,'66%22'66!% $ 
  --b1"99-IdIde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,*I1AI6?I;r   num_images_per_promptprompt_embeds_maskmax_sequence_lengthc                 ~   |xs | j                   }t        |t              r|gn|}|t        |      n|j                  d   }|| j                  |||      \  }}|j                  \  }	}
}	|j                  d|d      }|j                  ||z  |
d      }|j                  d|d      }|j                  ||z  |
      }||fS )a  

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            image (`torch.Tensor`, *optional*):
                image 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.
        r   r   r   )r   r   r   r6   shaper   repeatview)ro   r   r   r*   r   rT   r   r   
batch_size_seq_lens              r&   encode_promptz#QwenImageEditPipeline.encode_prompt  s    2 1411'4&&$1$9S[}?R?RST?U
 040L0LVUZ\b0c-M-%++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kro   s     r&   	<genexpr>z5QwenImageEditPipeline.check_inputs.<locals>.<genexpr>M  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`.r^   z9`max_sequence_length` cannot be greater than 1024 but is )
r]   loggerwarningallr.   r   r   r   listtype)ro   r   rP   rO   negative_promptrT   negative_prompt_embedsr   negative_prompt_embeds_mask"callback_on_step_end_tensor_inputsr   r   s   `           r&   check_inputsz"QwenImageEditPipeline.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)rC   r   num_channels_latentsrP   rO   s        r&   _pack_latentsz#QwenImageEditPipeline._pack_latentsr  sl     ,,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   )rC   rP   rO   r]   r   num_patcheschannelss          r&   _unpack_latentsz%QwenImageEditPipeline._unpack_latents{  s     -4MM)
K c&k&6&:;<SZ$4q$89:,,z6Q;
HPQMSTVWX//!Q1a3//*h5.A1feTr(   r=   c                 4   t        |t              rkt        |j                  d         D cg c]2  }t	        | j
                  j                  |||dz          ||   d      4 }}t        j                  |d      }n't	        | j
                  j                  |      |d      }t        j                  | j
                  j                  j                        j                  d| j                  ddd      j                  |j                  |j                         }t        j                  | j
                  j                  j"                        j                  d| j                  ddd      j                  |j                  |j                         }||z
  |z  }|S c c}w )Nr   r   rB   )r=   r>   rs   )r   r   ranger   rG   rU   encoderw   r   tensorrf   latents_meanr   rh   r   r*   r   latents_std)ro   r   r=   iimage_latentsr   r   s          r&   _encode_vae_imagez'QwenImageEditPipeline._encode_vae_image  sI   i& u{{1~. !q1q51A!BiXYlhpqM  "IIm;M,TXX__U-CyfnoMLL556T!T))1a3R$$m&9&9: 	 LL445T!T))1a3R$$m&9&9: 	
 '5D's   7F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)rU   enable_slicingro   s    r&   enable_vae_slicingz(QwenImageEditPipeline.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)rU   disable_slicingr   s    r&   disable_vae_slicingz)QwenImageEditPipeline.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)rU   enable_tilingr   s    r&   enable_vae_tilingz'QwenImageEditPipeline.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)rU   disable_tilingr   s    r&   disable_vae_tilingz(QwenImageEditPipeline.disable_vae_tiling  r   r(   c
                    dt        |      | j                  dz  z  z  }dt        |      | j                  dz  z  z  }|d|||f}
d }||j                  ||      }|j                  d   | j                  k7  r| j                  ||      }n|}||j                  d   kD  rC||j                  d   z  dk(  r.||j                  d   z  }t        j                  |g|z  d      }n^||j                  d   kD  r4||j                  d   z  dk7  rt        d|j                  d    d| d	      t        j                  |gd      }|j                  d
d  \  }}| j                  |||||      }t        |t              r)t        |      |k7  rt        dt        |       d| d      |	(t        |
|||      }	| j                  |	||||      }	|	|fS |	j                  ||      }	|	|fS )Nr   r   r*   r   )r   r=   r   rs   z'Cannot duplicate `image` of batch size z to z text prompts.r   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=   r*   r   )r   r]   r   r   rh   r   rw   r   r.   r   r   r   r6   r   )ro   r   r   r   rP   rO   r   r*   r=   rC   r   r   additional_image_per_promptimage_latent_heightimage_latent_widths                  r&   prepare_latentsz%QwenImageEditPipeline.prepare_latents  sD    c&kd&;&;a&?@ASZD$9$9A$=>?Q 4feDHHF%H8E{{1~!5!55 $ 6 6Ui 6 X %M//22zMDWDWXYDZ7Z^_7_.8M<O<OPQ<R.R+ %		=/<W*W]^ _m11!44mFYFYZ[F\9\`a9a =m>Q>QRS>T=UUYZdYeest  !&		=/q A6C6I6I!"6M3!3 ..z+?ATVhM i&3y>Z+GA#i.AQ R&<'gi  ?"5IfTYZG((*>RTZ\abG %% jjej<G%%r(   c                     | j                   S r    )_guidance_scaler   s    r&   guidance_scalez$QwenImageEditPipeline.guidance_scale  s    ###r(   c                     | j                   S r    )_attention_kwargsr   s    r&   attention_kwargsz&QwenImageEditPipeline.attention_kwargs      %%%r(   c                     | j                   S r    )_num_timestepsr   s    r&   num_timestepsz#QwenImageEditPipeline.num_timesteps  s    """r(   c                     | j                   S r    )_current_timestepr   s    r&   current_timestepz&QwenImageEditPipeline.current_timestep  r   r(   c                     | j                   S r    )
_interruptr   s    r&   	interruptzQwenImageEditPipeline.interrupt  s    r(   g      @2         ?pilTi   r   true_cfg_scalerP   rO   r)   r,   r   r   r   output_typereturn_dictr   callback_on_step_endr   c                 z   t        |t              r|d   j                  n|j                  }t        d|d   |d   z        \  }}}|xs |}|xs |}| j                  dz  }||z  |z  }||z  |z  }| j                  ||||||||||
       |	| _        || _        d| _        d| _	        |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                  }|t        |t        j                        r|j                  d      | j                   k(  sM| j"                  j%                  |||      }|}| j"                  j'                  |||      }|j)                  d      }|duxs
 |duxr |du}|dkD  xr |} | j+                  |||||
|      \  }}| r| j+                  ||||||
|      \  }}| j,                  j.                  j0                  d	z  }!| j3                  |||
z  |!|||j4                  |||	      \  }}"d|| j                  z  dz  || j                  z  dz  fd|| j                  z  dz  || j                  z  dz  fgg|z  }#|t7        j8                  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            }%tA        | j<                  ||||%      \  }&}tC        t        |&      || j<                  jD                  z  z
  d      }'t        |&      | _#        | j,                  j.                  jH                  rGt        jJ                  dg|	|t        jL                        }(|(jO                  |j                  d         }(nd}(| jP                  i | _        | |jS                  d      jU                         nd})| |jS                  d      jU                         nd}*| j<                  jW                  d       | jY                  |      5 }+t[        |&      D ]  \  },}-| j\                  r|-| _        |}.|"t        j^                  ||"gd      }.|-jO                  |j                  d         ja                  |j4                        }/| j,                  jc                  d      5  | j-                  |.|/dz  |(|||#|)| jP                  d	      d   }0|0ddd|j                  d      f   }0ddd       | r| j,                  jc                  d      5  | j-                  |.|/dz  |(|||#|*| jP                  d	      d   }1ddd       1ddd|j                  d      f   }1|1|0|1z
  z  z   }2t        jd                  |0dd      }3t        jd                  |2dd      }4|2|3|4z  z  }0|j4                  }5| j<                  jg                  0|-|d      d   }|j4                  |5k7  r9t        jh                  jj                  jm                         r|ja                  |5      }|Hi }6|D ]  }7to               |7   |6|7<     || |,|-|6      }8|8jq                  d|      }|8jq                  d |      }|,t        |&      dz
  k(  s'|,dz   |'kD  r/|,dz   | j<                  jD                  z  dk(  r|+js                          tt        stw        jx                           	 ddd       d| _        |d!k(  r|}n| j{                  |||| j                        }|ja                  | j|                  j4                        }t        j~                  | j|                  j.                  j                        j                  d| j|                  j.                  j                  ddd      ja                  |j                  |j4                        }9d
t        j~                  | j|                  j.                  j                        j                  d| j|                  j.                  j                  ddd      ja                  |j                  |j4                        z  }:||:z  |9z   }| j|                  j                  |d      d   dddddf   }| j"                  j                  ||"      }| j                          |s|fS t        |#      S # 1 sw Y   xY w# 1 sw Y   zx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   i   r   r   )r   rT   r   r   r   r   r   NF)r   r   rT   r   r*   r   r   r   r   base_image_seq_len   max_image_seq_len   r         ?r   ffffff?)r,   r%   r   rs   )totalcondi  )	rp   timestepguidanceencoder_hidden_states_maskencoder_hidden_states
img_shapestxt_seq_lensr   r   uncondr   T)rt   keepdim)r   rC   rT   latent)r   )r   )Ir   r   r   rQ   r]   r   r   r   r   r   r   r6   r   r   rw   Tensorrh   ri   resize
preprocess	unsqueezer   rY   rf   in_channelsr   r   nplinspacer'   r7   getr;   r   orderr   guidance_embedsfullfloat32expandr   rv   ry   set_begin_indexprogress_bar	enumerater   r   r   cache_contextnormstepbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   rU   r   r   r   rg   r*   r   decodepostprocessmaybe_free_model_hooksr   );ro   r   r   r   r   rP   rO   r)   r,   r   r   r=   rC   rT   r   r   r   r   r   r   r   r   r   
image_sizecalculated_widthcalculated_heightr   multiple_ofr   r*   prompt_imagehas_neg_promptdo_true_cfgr   r   r  r"   r%   r+   num_warmup_stepsr
  r  negative_txt_seq_lensr   r   tlatent_model_inputr	  
noise_predneg_noise_pred	comb_pred	cond_norm
noise_normlatents_dtypecallback_kwargsr   callback_outputsr   r   s;                                                              r&   __call__zQwenImageEditPipeline.__call__  sl	   R '1&=U1X]]5::
1EkS]^_S`cmnocpSp1q.+Q,,))++a/${2;&4 	+'#91(C/Q 3 	 	
  .!1!% *VS"9JJvt$<VJ&,,Q/J''j&E%**UV-[_[o[oJo((//7HJZ[E L((33E;LN^_EOOA&E(4 
"$.Z3NVZ3Z 	 %q(;^,0,>,>'1"7 3 -? -
)) BFBTBT"&4#>&;$7 CU C?"$?  $//66BBaG!%!5!5.. 
"
 Fd333q8%4CXCX:X\]:]^%)>)>>!CEUY]YnYnEnrsEs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 F	#\!), E#1>>)*&%," ,).G]3KQR)S& 88GMM!$4588G%%33F; B!%!1!1&8!)D!)3E.;#-%1)-)>)>$) "2 
" 
"J ",A/@a/@,@!AJB ))77A )-)9)9*<%-_%-7R2H'1)>-1-B-B(- *: 
* 
* &4A7Ha7H4H%IN .: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 '') LLNKE#F	#P "&("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4gB B 9F	# F	#sE    Bd0Ad%d0 +d#+E3d0 d0d d0#d-(d00d:NNNN)NNr   NNr^   )NNNNNNNr    )5__name__
__module____qualname____doc__model_cpu_offload_seqr   r   r   r	   r
   r   r   rb   rw   r  r~   r   r   r   r   r*   r   r   r   r   r   staticmethodr   r   	Generatorr   r   r   r   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   floatru   r   r   r   rD  __classcell__)r5   s   @r&   rS   rS      sR   $ =(/:'2' $' 9	'
 "' $' 1'@ELL   )-(,)-'+-5c49n%-5 %-5 &	-5
 $-5d )-)-%&0459#''1c49n%'1 %'1 &	'1
  #'1  -'1 %U\\2'1 !'1\ #$(+/ 5pn    u||  ."#!"" 5&n $ $ & & # # & &   U]]_12 /3(,15 # $##%(, #%&MQ*.04599=>B%* 59KO9B#&/D5*+D5 c49n%D5 sDI~.	D5
 D5 D5 }D5 !D5 e%D5 D5  #D5 E%//43H"HIJD5 %,,'D5  -D5 %U\\2D5  !) 6!D5" &.ell%;#D5$ c]%D5& 'D5( #4S>2)D5* 'xc40@$0F'GH+D5, -1I-D5. !/D5 3 D5r(   rS   )r  r  r  r  rE  )NrA   )8r0   rJ   typingr   r   r   r   r   r   numpyr  rw   transformersr	   r
   r   ri   r   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_loggerrF  r   rO  r   rP  r'   r   r*   r;   r  rL  rG   rQ   rS   r!   r(   r&   <module>r`     sV     = =   ] ] D / I 9 O O - . 4 ))MM 
		H	% 6 

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*z ck
TLL
T-5eoo-F
T\_
Tl
5-/G l
5r(   