
    
3j              
          S SK r S SKrS SKJrJr  S SK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  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  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\*4S jr+    S"S\)S-  S\,\RZ                  -  S-  S\.\)   S-  S\.\*   S-  4S jjr/ S#S\R`                  S\Rb                  S-  S\,4S jjr2 " S  S!\\5      r3g)$    N)AnyCallable)Qwen2TokenizerFastQwen3ForCausalLM   )PipelineImageInput)Flux2LoraLoaderMixin)AutoencoderKLFlux2Flux2Transformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipeline   )Flux2ImageProcessor)Flux2PipelineOutputTFa	  
    Examples:
        # Inpainting with text only
        ```py
        >>> import torch
        >>> from diffusers import Flux2KleinInpaintPipeline
        >>> from diffusers.utils import load_image

        >>> pipe = Flux2KleinInpaintPipeline.from_pretrained(
        ...     "black-forest-labs/FLUX.2-klein-base-9B", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")
        >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
        >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
        >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
        >>> source = load_image(img_url)
        >>> mask = load_image(mask_url)
        >>> image = pipe(prompt=prompt, image=source, mask_image=mask).images[0]
        >>> image.save("flux2klein_inpainting.png")
        ```

        # Inpainting with image reference conditioning
        ```py
        >>> import torch
        >>> from diffusers import Flux2KleinInpaintPipeline
        >>> from diffusers.utils import load_image

        >>> pipe = Flux2KleinInpaintPipeline.from_pretrained(
        ...     "black-forest-labs/FLUX.2-klein-base-9B", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> prompt = "Replace this ball"
        >>> img_url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/klein_inpaint/the-ball-stadion-football-the-pitch-39362.jpeg"
        >>> mask_url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/klein_inpaint/ball_mask.png"
        >>> image_reference_url = (
        ...     "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/klein_inpaint/ball.jpg"
        ... )

        >>> source = load_image(img_url)
        >>> mask = load_image(mask_url)
        >>> image_reference = load_image(image_reference_url)

        >>> mask = pipe.mask_processor.blur(mask, blur_factor=12)
        >>> image = pipe(
        ...     prompt=prompt, image=source, mask_image=mask, image_reference=image_reference, strength=1.0
        ... ).images[0]
        >>> image.save("flux2klein_inpainting_ref.png")
        ```
image_seq_len	num_stepsreturnc                     Su  p#Su  pEU S:  a  X@-  U-   n[        U5      $ X@-  U-   nX -  U-   nXx-
  S-  n	USU	-  -
  n
X-  U
-   n[        U5      $ )N)gT	?gŒ_?)g w:/&?gDw:?i  g     g@g      i@)float)r   r   a1b1a2b2mum_200m_10abs              p/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/pipelines/flux2/pipeline_flux2_klein_inpaint.pycompute_empirical_mur%   b   sy    'FB#FBt"$Ry#E"D	A	A	
	B9    num_inference_stepsdevice	timestepssigmasc                    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 valuesr)   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r)   r(   r*   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r*   r(   r(    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r)   len)	schedulerr'   r(   r)   r*   kwargsaccepts_timestepsaccept_sigmass           r$   retrieve_timestepsr:   u   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''	))r&   encoder_output	generatorsample_modec                    [        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@   moderB   AttributeError)r;   r<   r=   s      r$   retrieve_latentsrF      s}     ~}--+2I))00;;		/	/K84K))..00		+	+%%%RSSr&   c            3         ^  \ rS rSrSrSrSS/r SOS\S\S\	S	\
S
\S\4U 4S jjjr\    SPS\	S	\
S\\\   -  S\R$                  S-  S\R&                  S-  S\S\\   4S jj5       r\ SQS\R,                  S\R,                  S-  4S jj5       r\S\R,                  4S j5       r\ SRS\\R,                     S\S\4S jj5       r\S 5       r\S 5       r\S  5       r\S\R,                  S!\R,                  S"\\R,                     4S# j5       r\S$\S"\\\4   4S% j5       r      SSS\\\   -  S\R&                  S-  S'\S\R,                  S-  S\S(\\   4S) jjr!S$\R,                  S*\RD                  4S+ jr#  STS*\RD                  \\RD                     -  S-  S\R,                  S-  4S, jjr$S-\\R,                     S*\RD                  4S. jr%S/ r&S0 r'    SUS1 jr(\)S2 5       r*\)S3 5       r+\)S4 5       r,\)S5 5       r-\)S6 5       r.\)S7 5       r/\R`                  " 5       \1" \25      SSSSSSSS8S9SS:S&SSSSS;S<SSS/SS4S\\\   -  S-  S$\S-  S=\S-  S>\S-  S?\S-  S@\S-  SA\S-  SB\3SC\SD\\3   S-  SE\3S'\S*\RD                  \\RD                     -  S-  S\R,                  S-  S\R,                  S-  SF\R,                  S-  SG\SH\SI\4\\54   S-  SJ\6\\\4/S4   S-  SK\\   S\S(\\SL4   4.SM jj5       5       r7SNr8U =r9$ )VFlux2KleinInpaintPipeline   a  
Flux2 Klein pipeline for image inpainting with optional reference image conditioning.

Reference:
[https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence](https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence)

Args:
    transformer ([`Flux2Transformer2DModel`]):
        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 ([`AutoencoderKLFlux2`]):
        Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
    text_encoder ([`Qwen3ForCausalLM`]):
        [Qwen3ForCausalLM](https://huggingface.co/docs/transformers/en/model_doc/qwen3#transformers.Qwen3ForCausalLM)
    tokenizer (`Qwen2TokenizerFast`):
        Tokenizer of class
        [Qwen2TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/qwen2#transformers.Qwen2TokenizerFast).
ztext_encoder->transformer->vaerB   prompt_embedsr6   vaetext_encoder	tokenizertransformeris_distilledc           	      $  > [         TU ]  5         U R                  UUUUUS9  U R                  US9  [	        U SS 5      (       a/  S[        U R                  R                  R                  5      S-
  -  OSU l	        [	        U SS 5      (       a   U R                  R                  R                  OSU l
        [        U R                  S-  U R                  S9U l        [        U R                  S-  U R                  S	S
S	S
S9U l        SU l        SU l        g )N)rK   rL   rM   r6   rN   )rO   rK   r   r          )vae_scale_factorvae_latent_channelsFT)rS   rT   do_normalizedo_binarizedo_convert_rgbdo_convert_grayscale      )super__init__register_modulesregister_to_configgetattrr5   rK   configblock_out_channelsrS   latent_channelsr   image_processormask_processortokenizer_max_lengthdefault_sample_size)selfr6   rK   rL   rM   rN   rO   r4   s          r$   r\   "Flux2KleinInpaintPipeline.__init__   s    	%# 	 	
 	\:V]^bdikoVpVpc$((//*L*L&MPQ&Q Rvw CJ$PUW[B\B\txx>>bd2!22Q6DL`L` 
 2!22Q6 $ 4 4 !%
 %(!#& r&   NrY   	         promptdtyper(   max_sequence_lengthhidden_states_layersc           	         Uc  U R                   OUnUc  U R                  OUn[        U[        5      (       a  U/OUn/ n/ nU HM  n	SU	S./n
UR	                  U
SSSS9nU" USSSUS9nUR                  US	   5        UR                  US
   5        MO     [        R                  " USS9R                  U5      n[        R                  " USS9R                  U5      nU " UUSSS9n[        R                  " U Vs/ s H  nUR                  U   PM     snSS9nUR                  X4S9nUR                  u  nnnnUR                  SSSS5      R                  UUUU-  5      nU$ s  snf )Nuser)rolecontentFT)tokenizeadd_generation_promptenable_thinkingpt
max_length)return_tensorspadding
truncationry   	input_idsattention_maskr   dim)r}   r~   output_hidden_states	use_cacher   )rn   r(   r   r   )rn   r(   
isinstancestrapply_chat_templateappendtorchcattostackhidden_statesshapepermutereshape)rL   rM   rm   rn   r(   ro   rp   all_input_idsall_attention_maskssingle_promptmessagestextinputsr}   r~   outputkout
batch_sizenum_channelsseq_len
hidden_dimrJ   s                          r$   _get_qwen3_prompt_embeds2Flux2KleinInpaintPipeline._get_qwen3_prompt_embeds   s    ',m""(.$$F'44&& #M!'MBCH00&* %	 1 D #$.F   !45&&v.>'?@# $& IIm366v>	#6A>AA&I )!%	
 kk<PQ<Pq6//2<PQWXYff5f08;		5
L':Aq!Q/77
G\\fMfg Rs   9E"xt_coordc                    U R                   u  p#n/ n[        U5       H  nUc  [        R                  " S5      OX   n[        R                  " S5      n[        R                  " S5      n	[        R                  " U5      n
[        R                  " XxX5      nUR                  U5        M     [        R                  " U5      $ Nr   )r   ranger   arangecartesian_prodr   r   )r   r   BL_out_idsithwlcoordss               r$   _prepare_text_ids+Flux2KleinInpaintPipeline._prepare_text_ids7  s     ''aqA#*?Q
AQAQAQA))!5FNN6"  {{7##r&   c                 F   U R                   u  pp4[        R                  " S5      n[        R                  " U5      n[        R                  " U5      n[        R                  " S5      n[        R                  " XVXx5      n	U	R	                  S5      R                  USS5      n	U	$ )a:  
Generates 4D position coordinates (T, H, W, L) for latent tensors.

Args:
    latents (torch.Tensor):
        Latent tensor of shape (B, C, H, W)

Returns:
    torch.Tensor:
        Position IDs tensor of shape (B, H*W, 4) All batches share the same coordinate structure: T=0,
        H=[0..H-1], W=[0..W-1], L=0
r   r   )r   r   r   r   	unsqueezeexpand)
rB   r   r   heightwidthr   r   r   r   
latent_idss
             r$   _prepare_latent_ids-Flux2KleinInpaintPipeline._prepare_latent_idsK  s    $ (/}}$
vLLOLL LLLLO ))!5
  ))!,33JBG
r&   image_latentsr   scalec                 $   [        U [        5      (       d  [        S[        U 5       S35      e/ nUnU  GH  nUR                  u  pgp[
        R                  " U/5      R                  S5      n
[
        R                  " U
[
        R                  " U5      [
        R                  " U	5      [
        R                  " S5      5      nUS:X  d  Xa:X  a9  UR                  S5      R                  USS5      nUR                  U5        XB-  nM  U/n[        SU5       H  nXB-  n[
        R                  " U/5      R                  S5      n
UR                  [
        R                  " U
[
        R                  " U5      [
        R                  " U	5      [
        R                  " S5      5      5        M     [
        R                  " USS9nUR                  S5      R                  USS5      nUR                  U5        XB-  nGM     [
        R                  " USS9nU$ )a  
Generates 4D time-space coordinates (T, H, W, L) for a sequence of image latents.

This function creates a unique coordinate for every pixel/patch across all input latent with different
dimensions.

Args:
    image_latents (list[torch.Tensor]):
        A list of image latent feature tensors, typically of shape (C, H, W).
    scale (int, optional):
        A factor used to define the time separation (T-coordinate) between latents. T-coordinate for the i-th
        latent is: 'scale + scale * i'. Defaults to 10.

Returns:
    torch.Tensor:
        The combined coordinate tensor. Shape: (1, N_total, 4) Where N_total is the sum of (H * W) for all
        input latents.

Coordinate Components (Dimension 4):
    - T (Time): The unique index indicating which latent image the coordinate belongs to.
    - H (Height): The row index within that latent image.
    - W (Width): The column index within that latent image.
    - L (Seq. Length): A sequence length dimension, which is always fixed at 0 (size 1)
z+Expected `image_latents` to be a list, got .r   r   r   r   )r   listr-   typer   r   tensorviewr   r   r   r   r   r   r   )r   r   r   all_image_latent_idst_offsetr   b_ir   r   r   r   x_idsitem_idsimage_latent_idss                 r$   _prepare_image_ids,Flux2KleinInpaintPipeline._prepare_image_idsl  s   > -..J4P]K^J__`abb!A$%GG!CF hZ(--b1A((ELL,@%,,uBUW\WcWcdeWfgEax3,*11*b"E$++E2! "7q#A%HhZ055b9AOO,,QV0DellSXFY[`[g[ghi[jk ' 		(2*11*b"E$++E2!/ 2 !99%9qAr&   c                     U R                   u  pp4U R                  XUS-  SUS-  S5      n U R                  SSSSSS5      n U R                  XS-  US-  US-  5      n U $ )Nr   r   r   r         )r   r   r   r   rB   r   num_channels_latentsr   r   s        r$   _patchify_latents+Flux2KleinInpaintPipeline._patchify_latents  su     ;B--7
&,,z1aQVZ[Q[]^_//!Q1a3//*Q.FRSUZ^_U_`r&   c                     U R                   u  pp4U R                  XS-  SSX45      n U R                  SSSSSS5      n U R                  XS-  US-  US-  5      n U $ )Nr   r   r   r   r   r   r   r   r   r   s        r$   _unpatchify_latents-Flux2KleinInpaintPipeline._unpatchify_latents  sn     ;B--7
&//*u.MqRSU[c//!Q1a3//*u.MvXYz[`cd[der&   c                 n    U R                   u  pp4U R                  XX4-  5      R                  SSS5      n U $ )zg
pack latents: (batch_size, num_channels, height, width) -> (batch_size, height * width, num_channels)
r   r   r   r   )rB   r   r   r   r   s        r$   _pack_latents'Flux2KleinInpaintPipeline._pack_latents  s;     3:--/
&//*FNKSSTUWXZ[\r&   r   r   c                    / n[        X5       GH-  u  p4UR                  u  pVUSS2S4   R                  [        R                  5      nUSS2S4   R                  [        R                  5      n[        R
                  " U5      S-   n	[        R
                  " U5      S-   n
Xz-  U-   n[        R                  " X-  U4UR                  UR                  S9nUR                  SUR                  S5      R                  SU5      U5        UR                  XU5      R                  SSS5      nUR                  U5        GM0     [        R                  " USS9$ )z1
using position ids to scatter tokens into place
Nr   r   r(   rn   r   r   r   )zipr   r   r   int64maxzerosr(   rn   scatter_r   r   r   r   r   r   )r   r   x_listdataposr   chh_idsw_idsr   r   flat_idsr   s                r$   _unpack_latents_with_ids2Flux2KleinInpaintPipeline._unpack_latents_with_ids  s    QIDJJEA1ILL-E1ILL-E		% 1$A		% 1$Ay5(H++qubk$++TZZPCLLH..q188R@$G ((1$,,Q15CMM#! '$ {{6q))r&   imagec                    [        U [        5      (       a  U S   n [        U [        R                  R                  5      (       a  U R                  U R
                  4$ [        U [        R                  5      (       a  U R                  S   U R                  S   4$ [        U [        R                  5      (       aL  U R                  S:  a  U R                  S   U R                  S   4$ U R                  S   U R                  S   4$ [        U S5      (       a  U R                  S   U R                  S   4$ [        S[        U 5       35      e)z7Helper to get (height, width) without rounding/scaling.r   r   r   r   zUnsupported image type: )r   r   PILImager   r   r   Tensorr   npndarrayndimrC   r-   r   )r   s    r$   _get_raw_image_size-Flux2KleinInpaintPipeline._get_raw_image_size  s     eT""!HEeSYY__--<<,,u||,,;;r?EKKO33rzz**zzQ{{2B77;;r?EKKO335'"";;r?EKKO333DK=ABBr&   r   num_images_per_prompttext_encoder_out_layersc           	      x   U=(       d    U R                   nUc  Sn[        U[        5      (       a  U/OUnUc(  U R                  U R                  U R
                  UUUUS9nUR                  u  pxn	UR                  SUS5      nUR                  Xs-  US5      nU R                  U5      n
U
R                  U5      n
XJ4$ )N )rL   rM   rm   r(   ro   rp   r   r   )_execution_devicer   r   r   rL   rM   r   repeatr   r   r   )rg   rm   r(   r   rJ   ro   r   r   r   r   text_idss              r$   encode_prompt'Flux2KleinInpaintPipeline.encode_prompt  s     1411>F'44&&  99!....$7%< : M "/!4!4
Q%,,Q0EqI%**:+MwXZ[))-8;;v&&&r&   r<   c                    UR                   S:w  a  [        SUR                    S35      e[        U R                  R	                  U5      USS9nU R                  U5      nU R                  R                  R                  R                  SSSS5      R                  UR                  UR                  5      n[        R                  " U R                  R                  R                  R                  SSSS5      U R                  R                  R                   -   5      R                  UR                  UR                  5      nX4-
  U-  nU$ )Nr   zExpected image dims 4, got r   rA   )r<   r=   r   r   )r   r-   rF   rK   encoder   bnrunning_meanr   r   r(   rn   r   sqrtrunning_varr`   batch_norm_eps)rg   r   r<   r   latents_bn_meanlatents_bn_stds         r$   _encode_vae_image+Flux2KleinInpaintPipeline._encode_vae_image  s   ::?:5::,aHII()?9bjk..}=((++22772q!DGGH\H\^k^q^qrDHHKK$;$;$@$@B1$MPTPXPXP_P_PnPn$norr  -"5"5
 '8NJr&   c                    [        U	[        5      (       a*  [        U	5      U:w  a  [        S[        U	5       SU S35      eS[	        U5      U R
                  S-  -  -  nS[	        U5      U R
                  S-  -  -  nX4S-  US-  US-  4n[        R                  " XUS9nU R                  U5      nUR                  U5      nUR                  XS9nUR                  S   U R                  S-  :w  a  U R                  XS9nOUnU R                  R                  R                  R!                  SS	SS5      R                  UR"                  UR$                  5      n[        R&                  " U R                  R                  R(                  R!                  SS	SS5      U R                  R*                  R,                  -   5      R                  UR"                  UR$                  5      nX-
  U-  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
c'  [1        XXS9nU R2                  R5                  XU5      n
OU
R                  U5      nUn
U R7                  U5      nU R7                  U5      nU R7                  U
5      n
U
UUX4$ )Nz/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   r   r   z'Cannot duplicate `image` of batch size z to z text prompts.)r<   r(   rn   )r   r   r5   r-   intrS   r   r   r   r   r   rb   r  rK   r   r   r   r(   rn   r  r  r`   r  r   r   r6   scale_noiser   )rg   r   timestepr   num_latents_channelsr   r   rn   r(   r<   rB   r   dummy_latentslatent_image_idsr   r  r  additional_image_per_promptnoisepacked_image_latentss                       r$   prepare_latents)Flux2KleinInpaintPipeline.prepare_latents-  s    i&&3y>Z+GA#i.AQ R&<'gi  c&kd&;&;a&?@ASZD$9$9A$=>?A5v{EQJO EF33MB+..v64;;q>T11A55 222TM!M"hhkk66;;Ar1aHKKML`L`bobubuvO"ZZ(?(?(D(DQAq(QTXT\T\TcTcTrTr(rsvv$$m&9&9N +<NM++A..:@S@STU@V3VZ[3[*48K8KA8N*N'!II}o8S&SYZ[M--a00ZBUBUVWBX5X\]5]9-:M:Ma:P9QQUV`Uaaop  ? FXEnn00%PGJJv&EG""5)#11-@$$W-3]TTr&   imagesc                 n   / nU HU  nUR                  XES9nUR                  S   U R                  S-  :w  a  U R                  XsS9nOUnUR	                  U5        MW     U R                  Xb5      n	/ n
U H  nU R                  U5      nUR                  S   nUS:X  a  US:  a  UR                  USS5      nOCX:X  a  O=UR                  S   nUR                  SX-  S5      nUS:  a  UR                  USS5      nU
R	                  U5        M     [        R                  " U
SS9nU	R                  U5      n	Xi4$ )Nr   r   r   r	  r   r   r   )r   r   rb   r  r   r   r   r   r   r   r   )rg   r  r   r<   r(   rn   r   r   image_latentr   final_latentslatentpackedr   r   s                  r$   prepare_image_latents/Flux2KleinInpaintPipeline.prepare_image_latentsk  sC    EHHFH8E{{1~!5!5!99#55E5W$  .   22=M #F''/F,,q/CaxJNz1a8" !,,q/3="=>#]]:q!<F  ( $  		-Q7+..v6..r&   c                    [        U5      U R                  S-  -  n[        U5      U R                  S-  -  n	[        R                  R                  R                  XU	4SS9nUR                  XvS9nX#-  nUR                  S   U:  aW  X!R                  S   -  S:X  d  [        SU SUR                  S    S35      eUR                  X!R                  S   -  S	S	S	5      nU R                  U5      nU$ )
Nr   bilinear)sizerD   r   r   zvThe passed mask and the required batch size don't match. Masks are supposed to be duplicated to a total batch size of z, but zo masks were passed. Make sure the number of masks that you pass is divisible by the total requested batch size.r   )r
  rS   r   nn
functionalinterpolater   r   r-   r   r   )
rg   maskr   r   r   r   rn   r(   target_htarget_ws
             r$   prepare_mask_latents.Flux2KleinInpaintPipeline.prepare_mask_latents  s    v;4#8#81#<=u:$"7"7!";<xx""..tX:NU_.`wwfw27
 ::a=:%

1-2 ..8\

1 O^^ 
 ;;zZZ]:Aq!DD !!$'r&   c                 N   [        X-  U5      n[        [        X-
  S5      5      nU R                  R                  XPR                  R
                  -  S  n[        U R                  S5      (       a1  U R                  R                  XPR                  R
                  -  5        XaU-
  4$ )Nr   set_begin_index)minr
  r   r6   r)   orderrC   r)  )rg   r'   strengthr(   init_timestept_startr)   s          r$   get_timesteps'Flux2KleinInpaintPipeline.get_timesteps  s    /:<OPc-=qABNN,,W~~7K7K-K-MN	4>>#455NN**7^^5I5I+IJ777r&   c           
        ^  Uc  [        S5      eUc  [        S5      eUS:  d  US:  a  [        SU 35      eUb  UT R                  S-  -  S:w  d  UbB  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[        R                  R                  5      (       d  [        S[        U5       S35      e[        U[        R                  R                  5      (       d  [        S[        U5       S35      eUS:w  a  [        SU S35      eOUbe  [        U[        R                  R                  [        R                  [        R                  [        45      (       d  [        S[        U5       S35      eUbe  [        U[        R                  R                  [        R                  [        R                  [        45      (       d  [        S[        U5       S35      eUbe  [        U[        R                  R                  [        R                  [        R                  [        45      (       d  [        S[        U5       S35      eUS:  a6  T R                   R"                  (       a  [        R                  SU S35        g g g s  snf )Nz*`image` has to be provided for inpainting.z/`mask_image` has to be provided for inpainting.r   r   z2The value of strength should in [0.0, 1.0] but is 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).0r   rg   s     r$   	<genexpr>9Flux2KleinInpaintPipeline.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 zJThe image should be a PIL image when inpainting mask crop, but is of type r   zOThe mask image should be a PIL image when inpainting mask crop, but is of type pilz@The output type should be PIL when inpainting mask crop, but is z\`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `np.ndarray`, or `list` but is za`mask_image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `np.ndarray`, or `list` but is zf`image_reference` has to be of type `PIL.Image.Image`, `torch.Tensor`, `np.ndarray`, or `list` but is       ?zGuidance scale z+ is ignored for step-wise distilled models.)r-   rS   loggerwarningallr4  r   r   r   r   r   r   r   r   r   r   r`   rO   )rg   rm   r   
mask_imageimage_referencer,  r   r   output_typerJ   "callback_on_step_end_tensor_inputspadding_mask_cropguidance_scaler   s   `             r$   check_inputs&Flux2KleinInpaintPipeline.check_inputs  s    =IJJNOOa<8a<QRZQ[\]] $//!349 ..23q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(eSYY__55 `aefkal`mmno  j#))//:: Z(),  e# #cdocppq!rss $  !%#))//5<<UY)Z[[$##';-q2  %!*syybjjZ^._``$##'
#3"4A7 
 &o		rzz[_/`aa #O45Q8 
 CDKK$<$<NN_^,<<ghi %=a pHs   
M-!M-c                     U R                   $ r3  )_guidance_scalerg   s    r$   rB  (Flux2KleinInpaintPipeline.guidance_scale  s    ###r&   c                 d    U R                   S:  =(       a    U R                  R                  (       + $ r   )rF  r`   rO   rG  s    r$   do_classifier_free_guidance5Flux2KleinInpaintPipeline.do_classifier_free_guidance!  s%    ##a'H0H0H,HHr&   c                     U R                   $ r3  )_attention_kwargsrG  s    r$   attention_kwargs*Flux2KleinInpaintPipeline.attention_kwargs%      %%%r&   c                     U R                   $ r3  )_num_timestepsrG  s    r$   num_timesteps'Flux2KleinInpaintPipeline.num_timesteps)  s    """r&   c                     U R                   $ r3  )_current_timesteprG  s    r$   current_timestep*Flux2KleinInpaintPipeline.current_timestep-  rP  r&   c                     U R                   $ r3  )
_interruptrG  s    r$   	interrupt#Flux2KleinInpaintPipeline.interrupt1  s    r&   g?2   g       @r8  Tr>  r=  r   r   rA  r,  r'   r*   rB  negative_prompt_embedsr?  return_dictrN  callback_on_step_endr@  .c                 "   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UUUS9  Xl        UU l        SU l        SU l        U R                  S-  n[        U[        R                  5      (       az  UR                  S:X  aj  UR                  S5      U R                  S-  :X  aH  UnUnSnSnUR                  S   U R                  -  S-  nUR                  S   U R                  -  S-  nGOtUGbp  [        U[        5      (       aJ  [        US	   [        R                  5      (       a(  US	   R                  S:X  a  [        R                  " US	S
9n[        U[        5      (       a  US	   OUnU R!                  U5      u  nnUU-  S:  a  ["        R$                  " SUU-  -  5      n U R&                  R)                  U[+        UU -  5      [+        UU -  5      5      n[        U[        5      (       a  US	   OUnU R!                  U5      u  nnUU-  U-  n!UU-  U-  n"U!nU"nUb  U R,                  R/                  XFXWS9nSnOSnSnUnU R&                  R1                  UU"U!UUS9nSn#UGb  [        U[        R                  5      (       a#  UR                  S5      U R                  S-  :X  GdF  [        U[        5      (       aJ  [        US	   [        R                  5      (       a(  US	   R                  S:X  a  [        R                  " US	S
9n[        U[        5      (       a  US	   OUn$U R!                  U$5      u  n%n&U%U&-  S:  a  ["        R$                  " SU%U&-  -  5      n U R&                  R)                  U[+        U%U -  5      [+        U&U -  5      5      n[        U[        5      (       a  US	   OUn$U R!                  U$5      u  n%n&U&U-  U-  n'U%U-  U-  n(U R&                  R1                  UU(U'SS9n#OUb  U R2                  R4                  R6                  R9                  SSSS5      R;                  UR<                  UR>                  5      n)[        R$                  " U R2                  R4                  R@                  R9                  SSSS5      U R2                  RB                  RD                  -   5      R;                  UR<                  UR>                  5      n*UU)-
  U*-  n#Ub  [        U[F        5      (       a  Sn+O3Ub!  [        U[        5      (       a  [I        U5      n+OUR                  S	   n+U RJ                  n,U RM                  UUU,UUUS9u  nn-U RN                  (       a@  Sn.Ub$  [        U[        5      (       a  U./[I        U5      -  n.U RM                  U.UU,UUUS9u  nn/U
c  [P        RR                  " SSU	-  U	5      OU
n
[U        U RV                  RB                  S5      (       a'  U RV                  RB                  RX                  (       a  Sn
[+        U5      U R                  -  S-  [+        U5      U R                  -  S-  -  n0[[        U0U	S9n1[]        U RV                  U	U,U
U1S9u  n2n	U R_                  XU,5      u  n2n	U	S:  a  [a        SU SU	 S35      eU2SS Rc                  U+U-  5      n3U Rd                  RB                  Rf                  S-  n4U Ri                  WU3U+U-  U4UUUR>                  U,UU5
      u  nn5n6n7n8U7/n9U#b  U9Rk                  U#5        U Rm                  U9U+U-  UU,UR>                  5      u  n:n;U R,                  R1                  XEUWWS9n<U Ro                  U<U+UUUUR>                  U,5      n=[q        [I        U25      XRV                  Rr                  -  -
  S	5      n>[I        U25      U l:        [        R                  " U8U;/SS
9n?U Rw                  U	S9 n@[y        U25       GH  u  nAnBU Rz                  (       a  M  WBU l        UBR}                  UR                  S	   5      R;                  UR>                  5      nC[        R                  " UU:/SS
9nDU?nEUDR;                  U Rd                  R>                  5      nDU Rd                  R                  S5         U Re                  UDUCS-  SUU-UEU R                  SS9S	   nFSSS5        WFSS2SUR                  S5      24   nFU RN                  (       ao  U Rd                  R                  S 5         U Re                  WDWCS-  SUW/WEU R                  SS9S	   nGSSS5        WGSS2SUR                  S5      24   nGUGUWFUG-
  -  -   nFUR>                  nHU RV                  R                  WFWBUSS!9S	   nU6nIU=nJWA[I        U25      S-
  :  a:  U2WAS-      nKU RV                  R                  WI[        R                  " UK/5      U55      nISWJ-
  WI-  UJU-  -   nUR>                  WH:w  a>  [        R                  R                  R                  5       (       a  UR;                  WH5      nUbJ  0 nLU H  nM[        5       UM   WLUM'   M     U" U WAWBWL5      nNUNR                  S"U5      nUNR                  S#U5      nWA[I        U25      S-
  :X  d)  WAS-   U>:  a0  WAS-   U RV                  Rr                  -  S	:X  a  W@R                  5         [        (       d  GM  [        R                  " 5         GM     SSS5        SU l        U R                  UU85      nU R2                  R4                  R6                  R9                  SSSS5      R;                  UR<                  UR>                  5      nO[        R$                  " U R2                  R4                  R@                  R9                  SSSS5      U R2                  RB                  RD                  -   5      R;                  UR<                  UR>                  5      nPUUP-  UO-   nU R                  U5      nUS$:X  a  UnOhU R2                  R                  USS!9S	   nU R&                  R                  UUS%9nUb.  U VAs/ s H!  nAU R&                  R                  UWUAU5      PM#     nnAU R                  5         U(       d  U4$ [        US&9$ ! , (       d  f       GN= f! , (       d  f       GN= f! , (       d  f       GN= fs  snAf )'u8!  
Function invoked when calling the pipeline for inpainting.

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.
    image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
        `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
        numpy array and pytorch tensor, the expected value range is between `[0, 1]`. If it's a tensor or a
        list of tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or
        a list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)`. It can also accept image
        latents directly, in which case encoding is skipped. Latents must be in patchified form of shape `(B,
        latent_channels * 4, H // 2, W // 2)`, where each 2×2 spatial patch has been folded into the channel
        dimension.
    image_reference (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`, *optional*):
        `Image`, numpy array or tensor representing an image batch to be used as the reference for the masked
        area. This allows conditioning the inpainted region on a specific reference image. For both numpy array
        and pytorch tensor, the expected value range is between `[0, 1]`. If it's a tensor or a list of
        tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a list
        of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)`. It can also accept image latents
        directly, in which case encoding is skipped. Latents must be in patchified form of shape `(B,
        latent_channels * 4, H // 2, W // 2)`, where each 2×2 spatial patch has been folded into the channel
        dimension.
    mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
        `Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
        are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
        single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
        color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
        H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
        1)`, or `(H, W)`.
    height (`int`, *optional*, defaults to self.default_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.default_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.
    padding_mask_crop (`int`, *optional*, defaults to `None`):
        The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
        image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
        with the same aspect ration of the image and contains all masked area, and then expand that area based
        on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
        resizing to the original image size for inpainting. This is useful when the masked area is small while
        the image is large and contain information irrelevant for inpainting, such as background.
    strength (`float`, *optional*, defaults to 0.8):
        Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
        starting point and more noise is added the higher the `strength`. The number of denoising steps depends
        on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
        process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
        essentially ignores `image`.
    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 8.0):
        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. For step-wise distilled models,
        `guidance_scale` is ignored.
    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. Note that "" is used as the negative prompt in this pipeline.
        If not provided, will be generated from "".
    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.flux2.Flux2PipelineOutput`] 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`.
    text_encoder_out_layers (`Tuple[int]`):
        Layer indices to use in the `text_encoder` to derive the final prompt embeddings.

Examples:

Returns:
    [`~pipelines.flux2.Flux2PipelineOutput`] or `tuple`: [`~pipelines.flux2.Flux2PipelineOutput`] if
    `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
    generated images.
)rm   r   r=  r>  r,  r   r   r?  rJ   r@  rA  rB  NFr   r   r   defaultr   r   r   i   )padfill)crops_coordsresize_modecrop)rf  r   )rm   rJ   r(   r   ro   r   r   r9  use_flow_sigmas)r   r   )r*   r   z?After adjusting the num_inference_steps by strength parameter: z", the number of pipeline steps is z4 which is < 1 and not appropriate for this pipeline.)r   r   rf  re  )totalcondi  )r   r  guidanceencoder_hidden_statestxt_idsimg_idsjoint_attention_kwargsr_  uncond)r_  rB   rJ   r  )r?  )r  )Trf   rS   rC  rF  rM  rV  rZ  r   r   r   r   r  rb   r   r   r   r   mathr  rc   resizer
  rd   get_crop_region
preprocessrK   r   r   r   r   r(   rn   r  r`   r  r   r5   r   r   rJ  r   linspacerC   r6   rh  r%   r:   r/  r-   r   rN   in_channelsr  r   r  r&  r   r+  rR  progress_bar	enumerater[  r   cache_contextrN  stepr  r   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   r   decodepostprocessapply_overlaymaybe_free_model_hooksr   )Qrg   rm   r   r>  r=  r   r   rA  r,  r'   r*   rB  r   r<   rB   rJ   r^  r?  r_  rN  r`  r@  ro   r   multiple_of
init_imageoriginal_imagere  rf  imgraw_hraw_wr   image_widthimage_heightprocessed_image_referenceimg_reference	raw_ref_h	raw_ref_wimage_reference_widthimage_reference_heightbn_meanbn_stdr   r(   r   negative_promptnegative_text_idsr   r   r)   latent_timestepr   r  r   image_latents_encodedr  
ref_imagescondition_image_latentscondition_image_idsmask_conditionr#  num_warmup_stepscombined_image_idsrw  r   r   r  latent_model_inputrn  
noise_predneg_noise_predlatents_dtypeinit_latents_proper	init_masknoise_timestepcallback_kwargsr   callback_outputsr  r  sQ                                                                                    r$   __call__"Flux2KleinInpaintPipeline.__call__5  s   N K433d6K6KKI11D4I4II 	!+#'/Q/) 	 	
  .!1!% ++a/eU\\**uzzQ5::a=TXThThklTlClJ"NL#K[[^d&;&;;a?FKKNT%:%::Q>E%&&:eAh+M+MRWXYRZR_R_cdRd		%Q/(55%(5C33C8LE5u}{*		+"?@,,33E3uu};MsSX[`S`Oab",UD"9"9eAhu#77<u K/;>K![0K?L  E!F !,#22BB:V\Bt$#'"N--88|[|Yd 9 J
 %)!&55/:N:Nq:QUYUiUilmUm:m ?D11q15<<@@#A&++q0"'))O"C2<_d2S2SOA.YhM#'#;#;M#J Iy9${2		+Y1F"GH"&"6"6"="=#SU):%;SUAR=S# 7ARV6W6W 2]l'+'?'?'N$	9%.+%=$L!&/;&>+%M"(,(<(<(G(G&%"	 )H )% *((++22772q!DGGH^H^`o`u`uvDHHKK$;$;$@$@B1$MPTPXPXP_P_PnPn$norr#**O,A,A .=w-F&,P) *VS"9"9JJvt$<$<VJ&,,Q/J'' #'"4"4'"7 3$; #5 #
x ++ O!j&>&>#2"3c&k"A8<8J8J&4&;$7(? 9K 95"$5 TZSaS!&9"9;NOgm4>>((*;<<AVAVAfAfFV(=(==Bs5zUYUjUjGjnoGop!I\]);NN*
&	& *.););<O[a)b&	&"QRZQ[ \/00df  $BQ-..z<Q/QR  $//66BBaGQUQeQe.. R
N'<>N ,,
$0787;7Q7Q..8
4!4 ,,77UZf 8 
 ((!
 s9~0CnnFZFZ0ZZ\]^!)n #YY(8:M'NTUV %89\!),1>>)*&88GMM!$4588G%*YY9P/QWX%Y",%7%:%:4;K;K;Q;Q%R"%%33F;!%!1!1&8!)D!%.; ( '/3/D/D$) "2 	" 	"J < (+<W\\!_+<(<=
33))77A)-)9)9*<%-_%)2H$5$+373H3H(- *: 	* 	* B &4A7Ha7H4H%IN!/.JQ_D_2`!`J !(..--j!WRW-XYZ[&3# 	s9~))%.q1u%5N*...*D*D+U\\>:J-KU+' y=,??)gBUU==M1~~))6688")**]";'3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLNW - :\ "& //9IJ((++22772q!DGGX_XeXefDHHKK$;$;$@$@B1$MPTPXPXP_P_PnPn$norrNNGMM
 N*_<**73("EHHOOGO?BE((44U4TE ,mrmrhiD((66z>STVbcmr  
 	##%8O"%00{ <; BA9 :9BsK   
B=s:'s.As:<'s(#F%s:s:	(t
s% s:(
s72s::
t	)rM  rV  rF  rZ  rR  rf   rc   rb   rd   re   rS   )F)NNrY   ri   r3  )
   )Nr   NrY   ri   )NNNNNN):__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seqr4  r   r
   r   r   r   boolr\   staticmethodr   r   r   rn   r(   r
  r   r   r   r   r   r   r   r   r   r   tupler   r   	Generatorr  r  r  r&  r/  rC  propertyrB  rJ  rN  rS  rW  r[  no_gradr   EXAMPLE_DOC_STRINGr   dictr   r   r  __static_attributes____classcell__)r4   s   @r$   rH   rH      s   ( =(/: #%'2%'  %' '	%'
 &%' -%' %' %'N  %)&*#&*56&6%6 d3i6 {{T!	6
 t#6 !6 #3i6 6p  (,$<<$$$ $$  >  > ELL)> >  >  > @       *ELL * *$u||J\ * *2 C#5 C%S/ C C. '+%&-1#&.9 'd3i ' t# '  #	 '
 ||d* ' ! ' "'s 'Fu||  2 EI'+<U ??T%//%::TA<U $<U|*/U\\"*/ ??	*/XD	8* +/Wjr $ $ I I & & # # & &   ]]_12 *.+/5904! (,#%%) #%&DH'+-16:  26HL9B#&3>1A1d3i$&A1 "D(A1 ,d2	A1
 '-A1 d
A1 TzA1 :A1 A1 !A1 Ud"A1 A1  #A1 ??T%//%::TAA1 $A1  ||d*!A1" !&t 3#A1$ %A1& 'A1( sCx.4/)A1* 'S$'7'=>E+A1, -1I-A1. !/A10 "'sCx1A1 3 A1r&   rH   r  )Nr@   )4r/   rq  typingr   r   numpyr   r   r   transformersr   r   rc   r   loadersr	   modelsr
   r   
schedulersr   utilsr   r   r   utils.torch_utilsr   pipeline_utilsr   r   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr  r:  r  r
  r   r%   r   r(   r   r:   r   r  rF   rH   r,   r&   r$   <module>r     s/        
  = 1 + A 9 O O - . 0 0 ))MM 
		H	%1 j   * '+(,"&!%8*t8* %,,%8* Cy4	8*
 K$8*z `h
TLL
T-2__t-C
TY\
Tz1 13G z1r&   