
    bi8                        d dl Z d dlZd dlZd dlmZ d dlZd dlmZm	Z	m
Z
mZmZmZm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 ddlmZmZ dd	lmZ dd
l m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3  e%       rd dl4m5c m6Z7 dZ8ndZ8 e&jr                  e:      Z; e#       rd dl<m=Z=  e$       rd dl>Z>dZ?	 	 	 	 ddee@   deeeAej                  f      deee@      deeeC      fdZD G d de/e      ZEy)    N)AnyCallableDictListOptionalTupleUnion)Gemma2PreTrainedModelGemmaTokenizerGemmaTokenizerFast   )MultiPipelineCallbacksPipelineCallback)PixArtImageProcessor)SanaLoraLoaderMixin)AutoencoderDCSanaTransformer2DModel)DPMSolverMultistepScheduler)	BACKENDS_MAPPINGUSE_PEFT_BACKENDis_bs4_availableis_ftfy_availableis_torch_xla_availableloggingreplace_example_docstringscale_lora_layersunscale_lora_layers)
get_deviceis_torch_versionrandn_tensor   )DiffusionPipeline)ASPECT_RATIO_1024_BIN   )SanaPipelineOutputTF)BeautifulSoupa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import SanaSprintPipeline

        >>> pipe = SanaSprintPipeline.from_pretrained(
        ...     "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> image = pipe(prompt="a tiny astronaut hatching from an egg on the moon")[0]
        >>> image[0].save("output.png")
        ```
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(    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r)   len)	schedulerr'   r(   r)   r*   kwargsaccepts_timestepsaccept_sigmass           h/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/sana/pipeline_sana_sprint.pyretrieve_timestepsr;   Q   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''	)))    c            5           e Zd ZdZ ej
                  d      ZdZddgZde	e
ef   deded	ed
ef
 fdZd Zd Zd Zd Z	 	 	 dBde	eee   f   dej0                  dej2                  dededeee      fdZ	 	 	 	 	 	 	 	 dCde	eee   f   dedeej0                     deej<                     deej<                     dededeee      dee   fdZ d Z!	 	 	 dDd Z"dEd!Z#d" Z$dFd#Z%e&d$        Z'e&d%        Z(e&d&        Z)e&d'        Z* ejV                          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g d0fde	eee   f   d1ed2ee   d3ed4ed5edee   d6ed7ed8ed9ee	ej\                  eej\                     f      deej<                     deej<                     deej<                     d:ee   d;eded<ed=ee/ee0f      d>ee1eee/gdf      d?ee   dedee   d@e	e2e3f   f0dA              Z4 xZ5S )GSanaSprintPipelinezn
    Pipeline for text-to-image generation using [SANA-Sprint](https://huggingface.co/papers/2503.09641).
    u5   [#®•©™&@·º½¾¿¡§~\)\(\]\[\}\{\|\\/\*]{1,}ztext_encoder->transformer->vaelatentsprompt_embeds	tokenizertext_encodervaetransformerr6   c                     t         |           | j                  |||||       t        | d      r;| j                  /dt        | j                  j                  j                        dz
  z  nd| _        t        | j                        | _
        y )N)rA   rB   rC   rD   r6   rC   r!   r$       )vae_scale_factor)super__init__register_moduleshasattrrC   r5   configencoder_block_out_channelsrG   r   image_processor)selfrA   rB   rC   rD   r6   r4   s         r:   rI   zSanaSprintPipeline.__init__   s     	lQ\hq 	 	
 tU#(< #dhhoo@@AAEF 	
  4TEZEZ[r<   c                 8    | j                   j                          y)z
        Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
        compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
        N)rC   enable_slicingrO   s    r:   enable_vae_slicingz%SanaSprintPipeline.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)rC   disable_slicingrR   s    r:   disable_vae_slicingz&SanaSprintPipeline.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)rC   enable_tilingrR   s    r:   enable_vae_tilingz$SanaSprintPipeline.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)rC   disable_tilingrR   s    r:   disable_vae_tilingz%SanaSprintPipeline.disable_vae_tiling   rT   r<   F,  Npromptr(   dtypeclean_captionmax_sequence_lengthcomplex_human_instructionc                 8   t        |t              r|gn|}t        | dd      d| j                  _        | j                  ||      }|s|}nOdj                  |      }|D 	cg c]  }	||	z   	 }}	t        | j                  j                  |            }
|
|z   dz
  }| j                  |d|ddd	
      }|j                  }|j                  }|j                  |      }| j                  |j                  |      |      }|d   j                  ||      }||fS c c}	w )a  
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            device: (`torch.device`, *optional*):
                torch device to place the resulting embeddings on
            clean_caption (`bool`, defaults to `False`):
                If `True`, the function will preprocess and clean the provided caption before encoding.
            max_sequence_length (`int`, defaults to 300): Maximum sequence length to use for the prompt.
            complex_human_instruction (`list[str]`, defaults to `complex_human_instruction`):
                If `complex_human_instruction` is not empty, the function will use the complex Human instruction for
                the prompt.
        rA   Nright)ra   
r!   
max_lengthTpt)paddingrg   
truncationadd_special_tokensreturn_tensors)attention_maskr   )r`   r(   )
isinstancestrgetattrrA   padding_side_text_preprocessingjoinr5   encode	input_idsrm   torB   )rO   r_   r(   r`   ra   rb   rc   max_length_all
chi_promptpnum_chi_prompt_tokenstext_inputstext_input_idsprompt_attention_maskr@   s                  r:   _get_gemma_prompt_embedsz+SanaSprintPipeline._get_gemma_prompt_embeds   s;   0 (4&&4d+7*1DNN'))&)N )0N#<=J.45j1n5F5$'(=(=j(I$J!25HH1LNnn %# % 
 %.. + : : 5 8 8 @)).*;*;F*CTi)j%a(++%+G333) 6s   !Dr$   num_images_per_promptr}   
lora_scalec
                    || j                   }| j                  | j                  j                  }
nd}
|	?t        | t              r/|	| _        | j                  t        rt        | j                  |	       t        | dd      d| j                  _
        |}dgt        t        | dz   d            z   }|,| j                  |||
|||      \  }}|dd|f   }|dd|f   }|j                  \  }}}|j                  d|d      }|j!                  ||z  |d      }|j!                  |d      }|j                  |d      }| j                  ,t        | t              rt        rt#        | j                  |	       ||fS )a  
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded

            num_images_per_prompt (`int`, *optional*, defaults to 1):
                number of images that should be generated per prompt
            device: (`torch.device`, *optional*):
                torch device to place the resulting embeddings on
            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.
            clean_caption (`bool`, defaults to `False`):
                If `True`, the function will preprocess and clean the provided caption before encoding.
            max_sequence_length (`int`, defaults to 300): Maximum sequence length to use for the prompt.
            complex_human_instruction (`list[str]`, defaults to `complex_human_instruction`):
                If `complex_human_instruction` is not empty, the function will use the complex Human instruction for
                the prompt.
        NrA   re   r   r$   )r_   r(   r`   ra   rb   rc   )_execution_devicerB   r`   rn   r   _lora_scaler   r   rp   rA   rq   listranger~   shaperepeatviewr   )rO   r_   r   r(   r@   r}   ra   rb   rc   r   r`   rg   select_indexbs_embedseq_len_s                   r:   encode_promptz SanaSprintPipeline.encode_prompt  s   D >++F(%%++EE !j7J&K)D   ,1A!$"3"3Z@4d+7*1DNN' )
sT%a";<< 373P3P+$7*C 4Q 40M0 *!\/:M$9!\/$J!,22'1%,,Q0EqI%**86K+KWVXY 5 : :8R H 5 < <=RTU V($ 349I#D$5$5zB333r<   c                 V   dt        t        j                  | j                  j                        j
                  j                               v }i }|r||d<   dt        t        j                  | j                  j                        j
                  j                               v }|r||d<   |S )Neta	generator)r.   r/   r0   r6   stepr2   r3   )rO   r   r   accepts_etaextra_step_kwargsaccepts_generators         r:   prepare_extra_step_kwargsz,SanaSprintPipeline.prepare_extra_step_kwargs[  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  r<   c           
      h    |dz  dk7  s|dz  dk7  rt        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      |t        |      |dz   k7  rt        d      ||t        d      ||t        d      ||dk7  rt        d      y y c c}w )NrF   r   z8`height` and `width` have to be divisible by 32 but are z and .c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0krO   s     r:   	<genexpr>z2SanaSprintPipeline.check_inputs.<locals>.<genexpr>|  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is zEMust provide `prompt_attention_mask` when specifying `prompt_embeds`.r$   zWIf providing custom timesteps, `timesteps` must be of length `num_inference_steps + 1`.zFIf providing custom timesteps, `max_timesteps` should not be provided.z5Should provide either `timesteps` or `max_timesteps`.r!   zNIntermediate timesteps for SCM is not supported when num_inference_steps != 2.)r-   allr   rn   ro   r   typer5   )rO   r_   heightwidthr'   r)   max_timestepsintermediate_timesteps"callback_on_step_end_tensor_inputsr@   r}   r   s   `           r:   check_inputszSanaSprintPipeline.check_inputsl  s    B;!urzQWX^W__dejdkklmnn-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$)>)Fdee S^7JQ7N%Nvww ]%>eff!6TUU!-2E2Jmnn 3K-7 pHs   D/%D/c                     rOt               sEt        j                  t        d   d   j	                  d             t        j                  d       drOt               sEt        j                  t        d   d   j	                  d             t        j                  d       dt        |t        t        f      s|g}dt        f fd}|D cg c]
  } ||       c}S c c}w )	Nbs4r   zSetting `clean_caption=True`z#Setting `clean_caption` to False...Fftfytextc                     r$j                  |       } j                  |       } | S | j                         j                         } | S r   )_clean_captionlowerstrip)r   ra   rO   s    r:   processz7SanaSprintPipeline._text_preprocessing.<locals>.process  sH    **40**40 K zz|))+Kr<   )
r   loggerwarningr   formatr   rn   tupler   ro   )rO   r   ra   r   ts   ` `  r:   rr   z&SanaSprintPipeline._text_preprocessing  s    !1!3NN+E226==>\]^NN@A!M!2!4NN+F3B7>>?]^_NN@A!M$.6D	# 	 %))q
)))s   C!c                 	   t        |      }t        j                  |      }|j                         j	                         }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        |d      j                  }t        j                  dd|      }t        j                  d	d|      }t        j                  d
d|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  d d|      }t        j                  d!d|      }t        j                  | j                  d|      }t        j                  d"d|      }t        j                  d#      }t        t        j                  ||            d$kD  rt        j                  |d|      }t        j                  |      }t        j                   t        j                   |            }t        j                  d%d|      }t        j                  d&d|      }t        j                  d'd|      }t        j                  d(d|      }t        j                  d)d|      }t        j                  d*d|      }t        j                  d+d|      }t        j                  d,d|      }t        j                  d-d|      }t        j                  d.d|      }t        j                  d/d0|      }t        j                  d1d2|      }t        j                  d3d|      }|j                          t        j                  d4d5|      }t        j                  d6d|      }t        j                  d7d|      }t        j                  d8d|      }|j                         S )9Nz<person>personzk\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@))) zh\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))zhtml.parser)featuresz
@[\w\d]+\bz[\u31c0-\u31ef]+z[\u31f0-\u31ff]+z[\u3200-\u32ff]+z[\u3300-\u33ff]+z[\u3400-\u4dbf]+z[\u4dc0-\u4dff]+z[\u4e00-\u9fff]+z|[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+-u   [`´«»“”¨]"u   [‘’]'z&quot;?z&ampz"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} z\d:\d\d\s+$z\\nz
#\d{1,3}\bz	#\d{5,}\bz
\b\d{6,}\bz0[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)z
[\"\']{2,}z[\.]{2,}z\s+\.\s+z	(?:\-|\_)r   z\b[a-zA-Z]{1,3}\d{3,15}\bz\b[a-zA-Z]+\d+[a-zA-Z]+\bz\b\d+[a-zA-Z]+\d+\bz!(worldwide\s+)?(free\s+)?shippingz(free\s)?download(\sfree)?z\bclick\b\s(?:for|on)\s\w+z9\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?z\bpage\s+\d+\bz*\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\bu   \b\d+\.?\d*[xх×]\d+\.?\d*\bz
\b\s+\:\s+z: z(\D[,\./])\bz\1 z\s+z^[\"\']([\w\W]+)[\"\']$z\1z^[\'\_,\-\:;]z[\'\_,\-\:\-\+]$z^\.\S+$)ro   ulunquote_plusr   r   resubr&   r   bad_punct_regexcompiler5   findallr   fix_texthtmlunescape)rO   captionregex2s      r:   r   z!SanaSprintPipeline._clean_caption  s   g,//'*--/'')&&Xw7&&z

 &&w
  -@EE &&G4 &&,b':&&,b':&&,b':&&,b':&&,b':&&,b':&&,b': && L
 &&-sG<&&c73 &&R1&&"g. &&>WM &&W5 &&g. &&G4&&r73&&G4&&LbRYZ &&g6&&dG4&&--tW=&&dG4 L)rzz&'*+a/ffVS'2G--(--g 67&&5r7C&&5r7C&&/W=&&=r7K&&6GD&&6GD&&UWY[bc&&*B8&&FgV&&92wG&&w7&&&':&&g.&&3UGD&&)38&&,c7;&&R1}}r<   c	                 $   ||j                  ||      S ||t        |      | j                  z  t        |      | j                  z  f}	t        |t              r)t        |      |k7  rt        dt        |       d| d      t        |	|||      }|S )Nr(   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`   )rv   intrG   rn   r   r5   r-   r    )
rO   
batch_sizenum_channels_latentsr   r   r`   r(   r   r?   r   s
             r:   prepare_latentsz"SanaSprintPipeline.prepare_latents+  s    ::V5:99  K4000J$///	
 i&3y>Z+GA#i.AQ R&<'gi 
 u	&PUVr<   c                     | j                   S r   )_guidance_scalerR   s    r:   guidance_scalez!SanaSprintPipeline.guidance_scale>  s    ###r<   c                     | j                   S r   )_attention_kwargsrR   s    r:   attention_kwargsz#SanaSprintPipeline.attention_kwargsB  s    %%%r<   c                     | j                   S r   )_num_timestepsrR   s    r:   num_timestepsz SanaSprintPipeline.num_timestepsF  s    """r<   c                     | j                   S r   )
_interruptrR   s    r:   	interruptzSanaSprintPipeline.interruptJ  s    r<   r!   gH.!?g?g      @i   g        pilT)zGiven a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:z- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.zo- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.z8Here are examples of how to transform or refine prompts:z- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.z- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.zPlease generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:zUser Prompt: r'   r)   r   r   r   r   r   r   r   output_typereturn_dictuse_resolution_binningr   callback_on_step_endr   returnc                    t        |t        t        f      r|j                  }|rZ| j                  j
                  j                  dk(  rt        }nt        d      ||	}}| j                  j                  ||	|      \  }}	| j                  |||	|||||||
       || _        || _        d| _        |t        |t              rd}n-|t        |t               rt#        |      }n|j$                  d   }| j&                  }| j(                  | j(                  j+                  d	d      nd}| j-                  |||||||||
	      \  }}t/        | j0                  |||d||      \  }}t3        | j0                  d      r| j0                  j5                  d       | j                  j
                  j6                  }| j9                  ||z  |||	t:        j<                  |||      }|| j0                  j
                  j>                  z  }t;        j@                  dg||t:        j<                        }|jC                  |j$                  d         jE                  |jF                        }|| j                  j
                  jH                  z  }| jK                  ||
      } |dd }tM        t#        |      || j0                  jN                  z  z
  d      }!t#        |      | _(        | j                  jF                  }"| jS                  |      5 }#tU        |      D ]Y  \  }$}%| jV                  r|%jC                  |j$                  d         }&|| j0                  j
                  j>                  z  }'t;        jX                  |&      t;        jZ                  |&      t;        jX                  |&      z   z  }(|(j]                  dddd      })|'t;        j^                  |)dz  d|)z
  dz  z         z  }*| j	                  |*jE                  |"      |jE                  |"      |||(d| j(                        d   }+dd|)z  z
  |*z  dd|)z  z
  d|)dz  z  z   |+z  z   t;        j^                  |)dz  d|)z
  dz  z         z  }+|+ja                         | j0                  j
                  j>                  z  }+ | j0                  jb                  |+|&|fi | ddi\  }},|Hi }-|D ]  }.te               |.   |-|.<     || |$|%|-      }/|/jg                  d|      }|/jg                  d|      }|$t#        |      dz
  k(  s'|$dz   |!kD  r/|$dz   | j0                  jN                  z  dk(  r|#ji                          tj        sFtm        jn                          \ 	 ddd       ,| j0                  j
                  j>                  z  }|dk(  r|}0n|jE                  | jp                  jF                        }ts        t:        tu               t:        jv                        }1ty        dd      rt:        jz                  n|1jz                  }2	 | jp                  j}                  || jp                  j
                  j~                  z  d      d   }0|r| j                  j                  0      }0|dk(  s| j                  j                  0|      }0| j                          |s0fS t        0      S # 1 sw Y   MxY w# |2$ r"}3t        j                  |3 d       Y d}3~3d}3~3ww xY w)u  
        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.
            num_inference_steps (`int`, *optional*, defaults to 20):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            max_timesteps (`float`, *optional*, defaults to 1.57080):
                The maximum timestep value used in the SCM scheduler.
            intermediate_timesteps (`float`, *optional*, defaults to 1.3):
                The intermediate timestep value used in SCM scheduler (only used when num_inference_steps=2).
            timesteps (`List[int]`, *optional*):
                Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
                in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
                passed will be used. Must be in descending order.
            guidance_scale (`float`, *optional*, defaults to 4.5):
                Embedded guiddance scale is enabled by setting `guidance_scale` > 1. Higher `guidance_scale` encourages
                a model to generate images more aligned with `prompt` at the expense of lower image quality.

                Guidance-distilled models approximates true classifer-free guidance for `guidance_scale` > 1. Refer to
                the [paper](https://huggingface.co/papers/2210.03142) to learn more.
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            height (`int`, *optional*, defaults to self.unet.config.sample_size):
                The height in pixels of the generated image.
            width (`int`, *optional*, defaults to self.unet.config.sample_size):
                The width in pixels of the generated image.
            eta (`float`, *optional*, defaults to 0.0):
                Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only
                applies to [`schedulers.DDIMScheduler`], will be ignored for others.
            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 ge 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.
            prompt_attention_mask (`torch.Tensor`, *optional*): Pre-generated attention mask for text embeddings.
            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.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
            attention_kwargs:
                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).
            clean_caption (`bool`, *optional*, defaults to `True`):
                Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
                be installed. If the dependencies are not installed, the embeddings will be created from the raw
                prompt.
            use_resolution_binning (`bool` defaults to `True`):
                If set to `True`, the requested height and width are first mapped to the closest resolutions using
                `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
                the requested resolution. Useful for generating non-square images.
            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 `300`):
                Maximum sequence length to use with the `prompt`.
            complex_human_instruction (`List[str]`, *optional*):
                Instructions for complex human attention:
                https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.

        Examples:

        Returns:
            [`~pipelines.sana.pipeline_output.SanaPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.sana.pipeline_output.SanaPipelineOutput`] is returned,
                otherwise a `tuple` is returned where the first element is a list with the generated images
        rF   zInvalid sample size)ratios)
r_   r   r   r'   r)   r   r   r   r@   r}   FNr$   r   scale)r   r(   r@   r}   ra   rb   rc   r   )r*   r   r   set_begin_indexr   r   )totalr!   )r`   )encoder_hidden_statesencoder_attention_maskguidancetimestepr   r   r   r?   r@   latentz>=z2.5.0)r   z. 
Try to use VAE tiling for large images. For example: 
pipe.vae.enable_tiling(tile_sample_min_width=512, tile_sample_min_height=512))r   )images)Frn   r   r   tensor_inputsrD   rL   sample_sizer#   r-   rN   classify_height_width_binr   r   r   r   ro   r   r5   r   r   r   getr   r;   r6   rK   r   in_channelsr   torchfloat32
sigma_datafullexpandrv   r`   guidance_embeds_scaler   maxorderr   progress_bar	enumerater   sincosr   sqrtfloatr   localspopupdateXLA_AVAILABLExm	mark_steprC   rp   r   cudar   OutOfMemoryErrordecodescaling_factorwarningswarnresize_and_crop_tensorpostprocessmaybe_free_model_hooksr%   )4rO   r_   r'   r)   r   r   r   r   r   r   r   r   r?   r@   r}   r   r   ra   r   r   r   r   rb   rc   aspect_ratio_binorig_height
orig_widthr   r(   r   latent_channelsr   r   num_warmup_stepstransformer_dtyper   ir   r   latents_model_inputscm_timestepscm_timestep_expandedlatent_model_input
noise_preddenoisedcallback_kwargsr   callback_outputsimagetorch_accelerator_module	oom_errores4                                                       r:   __call__zSanaSprintPipeline.__call__N  s   r *-=?U,VW1E1S1S. "&&22b8#8  !677&,eK 00JJ6SXaqJrMFE 3'#9/Q'"7 	 	
  .!1 *VS"9JJvt$<VJ&,,Q/J''AEAVAVAbT**..w=hl
 "7'"7' 3&?!  

	
! *<NN'#9*
&	& 4>>#45NN**1- **11==&&..MM	
 DNN11<<<::qc>&V??7==#34778K8KLd..55KKK !::9cJ crN	s9~0CdnnFZFZ0ZZ\]^!)n ,,22%89 4	#\!), 3#1>> 88GMM!$45&-0E0E0P0P&P#$yy2eii6IEIIV^L_6_`(4(9(9"aA(F%%85::)1,4I0Ia/OO< &"
 "--&))0A)B*7*:*:AR*:*S+@%) %%)%:%: .  
 2226HH1444q;PRS;S7SSWaabJJ4a71?T;TYZ:ZZ[\
 (--/$..2G2G2R2RR
 %8DNN$7$7'%5F%TY%! (3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNg3#4	#l T^^22===("Ejj0G'.ujlEJJ'O$ $D'2 &&->> 
$((//2P2P(P^cdefg &,,CCE:Wbch&((44U4TE 	##%8O!//k4	# 4	#F  c d e s,    IZ5Z5A[ 5Z?[)[$$[))Fr^   N)r$   NNNFr^   NN)NNN)Fr   )6__name__
__module____qualname____doc__r   r   r   model_cpu_offload_seqr   r	   r   r   r
   r   r   r   rI   rS   rW   rZ   r]   ro   r   r   r(   r`   boolr   r   r~   Tensorr   r   r   r   rr   r   r   propertyr   r   r   r   no_gradr   EXAMPLE_DOC_STRING	Generatorr   r   r   r%   r   r!  __classcell__)r4   s   @r:   r>   r>      s+   
 !bjj  "a  bO =(/:\);;<\ ,\ 	\
 ,\ /\*"#!" $#&9=84c49n%84 84 {{	84
 84 !84 $,DI#684z &')-048<##&9=&*S4c49n%S4  #S4 &	S4
  -S4  (5S4 S4 !S4 $,DI#6S4 UOS4l!4 ,0"0of*2pf& $ $ & & # #   U]]_12 )-#$#&(+ #/0MQ*.048<%* #'+59KO9B#&	0
1m0c49n%m0 !m0 9	m0
 m0 !&m0 m0  (}m0 m0 m0 m0 E%//43H"HIJm0 %,,'m0  -m0  (5m0  c]!m0" #m0$ %m0& !%'m0( #4S>2)m0* 'xc40@$0F'GH+m0, -1I-m0. !/m00 $(91m0D 
!5(	)Em0 3 m0r<   r>   )NNNN)Fr   r/   r   urllib.parseparser   r	  typingr   r   r   r   r   r   r	   r   transformersr
   r   r   	callbacksr   r   rN   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   r   r   r   r   r   r   utils.torch_utilsr   r   r    pipeline_utilsr"   "pixart_alpha.pipeline_pixart_alphar#   pipeline_outputr%   torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr"  r   r   r&   r   r+  r   ro   r(   r   r;   r>   r,   r<   r:   <module>r?     s     	   D D D  R R A 3 * ; 5
 
 
 L K . F / ))MM			H	%! ( *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vq0*,? q0r<   