
    +h                        S SK r S SKrS SKrS SKJr  S SKrS SKJrJ	r	J
r
JrJrJrJr  S SKrS SKJrJrJ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#J$r$J%r%J&r&J'r'J(r(J)r)  SSK*J+r+J,r,J-r-  SSK.J/r/  SSK0J1r1J2r2  SSK3J4r4  SSK5J6r6  \%" 5       (       a  S SK7J8s  J9r:  Sr;OSr;\&Rx                  " \=5      r>\#" 5       (       a  S SK?J@r@  \$" 5       (       a  S SKArA0 SSS/_SSS/_SSS/_SSS/_SSS /_S!SS"/_S#SS$/_S%S&S'/_S(S&S)/_S*S+S,/_S-S+S./_S/S+S0/_S1S2S0/_S3S2S4/_S5S6S7/_S8S6S9/_S:S;S9/_0 S<S;S=/_S>S?S=/_S@S?SA/_SBSASA/_SCSAS?/_SDS=S?/_SES=S;/_SFS9S;/_SGS9S6/_SHS7S6/_SIS4S2/_SJS0S2/_SKS.S+/_SLS,S+/_SMS)S&/_SNS'S&/_SOS$S/_ES"S/S S/SS/SS/SS/SS/SP.ErBSQrC    SYSR\\D   SS\\\E\R                  4      ST\\\D      SU\\\G      4SV jjrH " SW SX\/\5      rIg)Z    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_512_BINASPECT_RATIO_1024_BIN)ASPECT_RATIO_2048_BIN   )SanaPipelineOutputTF)BeautifulSoupz0.25g      @g      @z0.26g      @z0.27g      @z0.28g      @z0.32g      @g      @z0.33g      @z0.35g      @z0.4g      @g      @z0.42g      @z0.48g      @g      @z0.5g      @z0.52g      @z0.57g      @z0.6g      @z0.68g      @g      @z0.72g      @z0.78g      @z0.82g      @z0.88g      @z0.94g      @z1.0z1.07z1.13z1.21z1.29z1.38z1.46z1.67z1.75z2.0z2.09z2.4z2.5z2.89)z3.0z3.11z3.62z3.75z3.88z4.0a&  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import SanaPipeline

        >>> pipe = SanaPipeline.from_pretrained(
        ...     "Efficient-Large-Model/Sana_1600M_1024px_BF16_diffusers", torch_dtype=torch.float32
        ... )
        >>> pipe.to("cuda")
        >>> pipe.text_encoder.to(torch.bfloat16)
        >>> pipe.transformer = pipe.transformer.to(torch.bfloat16)

        >>> image = pipe(prompt='a cyberpunk cat with a neon sign that says "Sana"')[0]
        >>> image[0].save("output.png")
        ```
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           `/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/pipelines/sana/pipeline_sana.pyretrieve_timestepsr=      s}   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	M)MfM''	!)n )) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	GvGG''	!)n )) 	 3MFMfM''	))    c            9         ^  \ rS rSrSr\R                  " S5      rSr/ SQr	S\
\\4   S\S\S	\S
\4
U 4S jjrS rS rS rS r   SHS\
\\\   4   S\R2                  S\R4                  S\S\S\\\      4S jjr            SIS\
\\\   4   S\S\S\S\\R2                     S \\R>                     S!\\R>                     S"\\R>                     S#\\R>                     S\S\S\\\      S$\\    4S% jjr!S& r"      SJS' jr#SKS( jr$S) r%SLS* jr&\'S+ 5       r(\'S, 5       r)\'S- 5       r*\'S. 5       r+\'S/ 5       r,\RZ                  " 5       \." \/5      SSS0SSS1SS2S2S3SSSSSSS4SSSSSS5/S/ S6Q4S\
\\\   4   S\S7\S8\\   S9\\    S:\ S\\   S;\S<\S=\ S>\\
\R`                  \\R`                     4      S5\\R>                     S \\R>                     S"\\R>                     S!\\R>                     S#\\R>                     S?\\   S@\S\SA\SB\\1\\24      SC\\3\\\1/S4      SD\\   S\S\\   SE\
\4\54   44SF jj5       5       r6SGr7U =r8$ )MSanaPipeline   z_
Pipeline for text-to-image generation using [Sana](https://huggingface.co/papers/2410.10629).
u5   [#®•©™&@·º½¾¿¡§~\)\(\]\[\}\{\|\\/\*]{1,}ztext_encoder->transformer->vae)latentsprompt_embedsnegative_prompt_embeds	tokenizertext_encodervaetransformerr8   c                   > [         TU ]  5         U R                  XX4US9  [        U S5      (       a<  U R                  b/  S[        U R                  R                  R                  5      S-
  -  OSU l        [        U R                  S9U l
        g )N)rE   rF   rG   rH   r8   rG   r!   r&       )vae_scale_factor)super__init__register_moduleshasattrrG   r7   configencoder_block_out_channelsrK   r   image_processor)selfrE   rF   rG   rH   r8   r6   s         r<   rM   SanaPipeline.__init__   s     	hq 	 	
 tU##(< #dhhoo@@AAEF 	
  4TEZEZ[r>   c                 8    U R                   R                  5         g)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)rG   enable_slicingrS   s    r<   enable_vae_slicingSanaPipeline.enable_vae_slicing       
 	!r>   c                 8    U R                   R                  5         g)z
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
computing decoding in one step.
N)rG   disable_slicingrW   s    r<   disable_vae_slicing SanaPipeline.disable_vae_slicing   s    
 	  "r>   c                 8    U R                   R                  5         g)z
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)rG   enable_tilingrW   s    r<   enable_vae_tilingSanaPipeline.enable_vae_tiling   s     	 r>   c                 8    U R                   R                  5         g)z
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
computing decoding in one step.
N)rG   disable_tilingrW   s    r<   disable_vae_tilingSanaPipeline.disable_vae_tiling   rZ   r>   F,  Npromptr*   dtypeclean_captionmax_sequence_lengthcomplex_human_instructionc           	      2   [        U[        5      (       a  U/OUn[        U SS5      b  SU R                  l        U R                  XS9nU(       d  UnOPSR                  U5      nU V	s/ s H  oU	-   PM	     nn	[        U R                  R                  U5      5      n
X-   S-
  nU R                  USUSSS	S
9nUR                  nUR                  nUR                  U5      nU R                  UR                  U5      US9nUS   R                  X2S9nX4$ s  sn	f )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.
rE   Nright)rj   
r!   
max_lengthTpt)paddingrp   
truncationadd_special_tokensreturn_tensors)attention_maskr   ri   r*   )
isinstancestrgetattrrE   padding_side_text_preprocessingjoinr7   encode	input_idsrv   torF   )rS   rh   r*   ri   rj   rk   rl   max_length_all
chi_promptpnum_chi_prompt_tokenstext_inputstext_input_idsprompt_attention_maskrC   s                  r<   _get_gemma_prompt_embeds%SanaPipeline._get_gemma_prompt_embeds   s3   0 (44&&4d+7*1DNN'))&)N )0N#<=J.45f1nfF5$'(=(=j(I$J!2H1LNnn %# % 
 %.. + : : 5 8 8 @)).*;*;F*CTi)j%a(++%+G33) 6s   (DT r&   do_classifier_free_guidancenegative_promptnum_images_per_promptrC   rD   r   negative_prompt_attention_mask
lora_scalec           	          Uc  U R                   nU R                  b  U R                  R                  nOSnUbI  [        U [        5      (       a4  Xl        U R                  b!  [        (       a  [        U R                  U5        Ub  [        U[        5      (       a  SnO3Ub!  [        U[        5      (       a  [        U5      nOUR                  S   n[        U SS5      b  SU R                  l        UnS/[        [        U* S-   S5      5      -   nUc(  U R!                  UUUU
UUS9u  phUSS2U4   nUSS2U4   nUR                  u  nnnUR#                  SUS5      nUR%                  UU-  US5      nUR%                  US5      nUR#                  US5      nU(       a6  Uc3  [        U[        5      (       a  U/U-  OUnU R!                  UUUU
USS9u  pyU(       ak  UR                  S   nUR'                  XS	9nUR#                  SUS5      nUR%                  X-  US5      nU	R%                  US5      n	U	R#                  US5      n	OSnSn	U R                  b6  [        U [        5      (       a!  [        (       a  [)        U R                  U5        XhXy4$ )
a  
Encodes the prompt into text encoder hidden states.

Args:
    prompt (`str` or `List[str]`, *optional*):
        prompt to be encoded
    negative_prompt (`str` or `List[str]`, *optional*):
        The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
        instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
        PixArt-Alpha, this should be "".
    do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
        whether to use classifier free guidance or not
    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.
    negative_prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated negative text embeddings. For Sana, it's should be the embeddings of the "" string.
    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.
Nr&   r   rE   rn   )rh   r*   ri   rj   rk   rl   Frw   )_execution_devicerF   ri   rx   r   _lora_scaler   r   ry   listr7   shaperz   rE   r{   ranger   repeatviewr   r   )rS   rh   r   r   r   r*   rC   rD   r   r   rj   rk   rl   r   ri   
batch_sizerp   select_indexbs_embedseq_len_s                        r<   encode_promptSanaPipeline.encode_prompt5  s   Z >++F(%%++EE !j7J&K&K)   ,1A1A!$"3"3Z@*VS"9"9JJvt$<$<VJ&,,Q/J4d+7*1DNN' )
sT%a";<< 373P3P+$7*C 4Q 40M *!\/:M$9!\/$J!,22'1%,,Q0EqI%**86K+KWVXY 5 : :8R H 5 < <=RTU V '+A+I@J?\_@`@`/*<fuOEIEbEb&+$7*/ Fc FB" ',2215G%;%>%>U%>%Z"%;%B%B1F[]^%_"%;%@%@Acelnp%q"-K-P-PQY[]-^*-K-R-RShjk-l*%)"-1*($ 3449I9I#D$5$5zB5Kkkr>   c                 n   S[        [        R                  " U R                  R                  5      R
                  R                  5       5      ;   n0 nU(       a  X$S'   S[        [        R                  " U R                  R                  5      R
                  R                  5       5      ;   nU(       a  XS'   U$ )Neta	generator)r0   r1   r2   r8   stepr4   r5   )rS   r   r   accepts_etaextra_step_kwargsaccepts_generators         r<   prepare_extra_step_kwargs&SanaPipeline.prepare_extra_step_kwargs  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  r>   c
           
        ^  US-  S:w  d	  US-  S:w  a  [        SU SU S35      eUbW  [        U 4S jU 5       5      (       d=  [        ST R                   SU V
s/ s H  oT R                  ;  d  M  U
PM     sn
 35      eUb  Ub  [        S	U S
U S35      eUc  Uc  [        S5      eUbA  [        U[        5      (       d,  [        U[
        5      (       d  [        S[        U5       35      eUb  Ub  [        S	U SU S35      eUb  Ub  [        SU SU S35      eUb  Uc  [        S5      eUb  U	c  [        S5      eUb  Ub  UR                  UR                  :w  a&  [        SUR                   SUR                   S35      eUR                  U	R                  :w  a&  [        SUR                   SU	R                   S35      eg g g s  sn
f )NrJ   r   z8`height` and `width` have to be divisible by 32 but are z and .c              3   @   >#    U  H  oTR                   ;   v   M     g 7fN)_callback_tensor_inputs).0krS   s     r<   	<genexpr>,SanaPipeline.check_inputs.<locals>.<genexpr>  s      F
7Y!---7Ys   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z and `negative_prompt_embeds`: z'Cannot forward both `negative_prompt`: zEMust provide `prompt_attention_mask` when specifying `prompt_embeds`.zWMust provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` z`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but got: `prompt_attention_mask` z% != `negative_prompt_attention_mask` )r/   allr   rx   ry   r   typer   )rS   rh   heightwidth"callback_on_step_end_tensor_inputsr   rC   rD   r   r   r   s   `          r<   check_inputsSanaPipeline.check_inputs  s    B;!urzQWX^W__dejdkklmnn-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"8"D0 9*++]_ 
 &+A+M9/9J K*++]_ 
 $)>)Fdee!-2P2Xvww$)?)K""&<&B&BB --:-@-@,A B.445Q8 
 %**.L.R.RR 55J5P5P4Q R6<<=Q@  S *L$C pHs   G1Gc                   ^ ^ T(       aT  [        5       (       dE  [        R                  [        S   S   R	                  S5      5        [        R                  S5        SmT(       aT  [        5       (       dE  [        R                  [        S   S   R	                  S5      5        [        R                  S5        Sm[        U[        [        45      (       d  U/nS[        4UU 4S jjnU Vs/ s H
  oC" U5      PM     sn$ s  snf )	Nbs4r   zSetting `clean_caption=True`z#Setting `clean_caption` to False...Fftfytextc                    > T(       a$  TR                  U 5      n TR                  U 5      n U $ U R                  5       R                  5       n U $ r   )_clean_captionlowerstrip)r   rj   rS   s    r<   process1SanaPipeline._text_preprocessing.<locals>.process  sH    **40**40 K zz|))+Kr>   )
r   loggerwarningr   formatr   rx   tupler   ry   )rS   r   rj   r   ts   ` `  r<   r|    SanaPipeline._text_preprocessing  s    !1!3!3NN+E226==>\]^NN@A!M!2!4!4NN+F3B7>>?]^_NN@A!M$..6D	# 	 	 %))Dq
D)))s   *C>c                 ^
   [        U5      n[        R                  " U5      nUR                  5       R	                  5       n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[        USS9R                  n[
        R                  " SSU5      n[
        R                  " S	SU5      n[
        R                  " S
SU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " S SU5      n[
        R                  " S!SU5      n[
        R                  " U R                  SU5      n[
        R                  " S"SU5      n[
        R                  " S#5      n[        [
        R                  " X!5      5      S$:  a  [
        R                  " USU5      n[        R                  " U5      n[        R                   " [        R                   " U5      5      n[
        R                  " S%SU5      n[
        R                  " S&SU5      n[
        R                  " S'SU5      n[
        R                  " S(SU5      n[
        R                  " S)SU5      n[
        R                  " S*SU5      n[
        R                  " S+SU5      n[
        R                  " S,SU5      n[
        R                  " S-SU5      n[
        R                  " S.SU5      n[
        R                  " S/S0U5      n[
        R                  " S1S2U5      n[
        R                  " S3SU5      nUR                  5         [
        R                  " S4S5U5      n[
        R                  " S6SU5      n[
        R                  " S7SU5      n[
        R                  " S8SU5      nUR                  5       $ )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\/?(?!@)))r   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+$)ry   ulunquote_plusr   r   resubr(   r   bad_punct_regexcompiler7   findallr   fix_texthtmlunescape)rS   captionregex2s      r<   r   SanaPipeline._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	                     Ub  UR                  XeS9$ UU[        U5      U R                  -  [        U5      U R                  -  4n	[        U[        5      (       a*  [        U5      U:w  a  [        S[        U5       SU S35      e[        XXeS9nU$ )N)r*   ri   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*   ri   )r   intrK   rx   r   r7   r/   r    )
rS   r   num_channels_latentsr   r   ri   r*   r   rB   r   s
             r<   prepare_latentsSanaPipeline.prepare_latents  s    ::V:99  K4000J$///	
 i&&3y>Z+GA#i.AQ R&<'gi 
 u&Vr>   c                     U R                   $ r   _guidance_scalerW   s    r<   guidance_scaleSanaPipeline.guidance_scale  s    ###r>   c                     U R                   $ r   )_attention_kwargsrW   s    r<   attention_kwargsSanaPipeline.attention_kwargs  s    %%%r>   c                      U R                   S:  $ )Ng      ?r   rW   s    r<   r   (SanaPipeline.do_classifier_free_guidance  s    ##c))r>   c                     U R                   $ r   )_num_timestepsrW   s    r<   num_timestepsSanaPipeline.num_timesteps  s    """r>   c                     U R                   $ r   )
_interruptrW   s    r<   	interruptSanaPipeline.interrupt  s    r>      g      @i   g        pilrB   )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   output_typereturn_dictuse_resolution_binningr   callback_on_step_endr   returnc                 H   [        U[        [        45      (       a  UR                  nU(       a  U R                  R
                  R                  S:X  a  [        nOU R                  R
                  R                  S:X  a  [        nOaU R                  R
                  R                  S:X  a  [        nO6U R                  R
                  R                  S:X  a  [        nO[        S5      eXnnU R                  R                  XUS9u  pU R                  UUU	UUUUUU5	        X`l        UU l        SU l        Ub  [        U[$        5      (       a  S	nO3Ub!  [        U[&        5      (       a  [)        U5      nOUR*                  S
   nU R,                  nU R.                  b  U R.                  R1                  SS5      OSnU R3                  UU R4                  UUUUUUUUUUUS9u  nnnnU R4                  (       a-  [6        R8                  " X/S
S9n[6        R8                  " UU/S
S9n[;        U R<                  UUXE5      u  pCU R                  R
                  R>                  n U RA                  UU-  U UU	[6        RB                  UUU5      nU RE                  X5      n![G        [)        U5      X0R<                  RH                  -  -
  S
5      n"[)        U5      U l%        U R                  RL                  n#U RO                  US9 n$[Q        U5       GH0  u  n%n&U RR                  (       a  M  U R4                  (       a  [6        R8                  " U/S-  5      OUn'U&RU                  U'R*                  S
   5      n(U(U R                  R
                  RV                  -  n(U R	                  U'RY                  U#S9URY                  U#S9UU(SU R.                  S9S
   n)U)R[                  5       n)U R4                  (       a  U)R]                  S5      u  n*n+U*UU+U*-
  -  -   n)U R                  R
                  R^                  S-  U :X  a  U)R]                  SS	S9S
   n)U R<                  R`                  " U)U&U40 U!DSS0D6S
   nUb\  0 n,U H  n-[c        5       U-   U,U-'   M     U" U U%U&U,5      n.U.Re                  SU5      nU.Re                  SU5      nU.Re                  SU5      nU%[)        U5      S	-
  :X  d)  U%S	-   U":  a0  U%S	-   U R<                  RH                  -  S
:X  a  U$Rg                  5         [h        (       d  GM  [j        Rl                  " 5         GM3     SSS5        US:X  a  Un/OURY                  U Rn                  RL                  5      n[q        [6        [s        5       [6        Rt                  5      n0[w        SS5      (       a  [6        Rx                  OU0Rx                  n1 U Rn                  R{                  XRn                  R
                  R|                  -  SS9S
   n/U(       a  U R                  R                  W/WW5      n/US:X  d  U R                  R                  W/US9n/U R                  5         U(       d  W/4$ [        W/S9$ ! , (       d  f       GN6= f! U1 a#  n2[~        R                  " U2 S35         Sn2A2NSn2A2ff = f)uG  
Function invoked when calling the pipeline for generation.

Args:
    prompt (`str` or `List[str]`, *optional*):
        The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
        instead.
    negative_prompt (`str` or `List[str]`, *optional*):
        The prompt or prompts not to guide the image generation. If not defined, one has to pass
        `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
        less than `1`).
    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.
    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.
    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 4.5):
        Guidance scale as defined in [Classifier-Free Diffusion
        Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
        of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
        `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
        the text `prompt`, usually at the expense of lower image quality.
    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.
    negative_prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated negative text embeddings. For PixArt-Sigma this negative prompt should be "". If not
        provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
    negative_prompt_attention_mask (`torch.Tensor`, *optional*):
        Pre-generated attention mask for negative 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
   @   rJ      zInvalid sample size)ratiosFNr&   r   scale)r   r   r*   rC   rD   r   r   rj   rk   rl   r   )dim)totalr!   )ri   )encoder_hidden_statesencoder_attention_masktimestepr   r   r   rB   rC   rD   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)Erx   r   r   tensor_inputsrH   rP   sample_sizeASPECT_RATIO_4096_BINr%   r$   r#   r/   rR   classify_height_width_binr   r   r   r   ry   r   r7   r   r   r   getr   r   torchcatr=   r8   in_channelsr   float32r   maxorderr   ri   progress_bar	enumerater   expandtimestep_scaler   floatchunkout_channelsr   localspopupdateXLA_AVAILABLExm	mark_steprG   rz   r   cudar   OutOfMemoryErrordecodescaling_factorwarningswarnresize_and_crop_tensorpostprocessmaybe_free_model_hooksr'   )3rS   rh   r   r)   r+   r,   r   r   r   r   r   r   rB   rC   r   rD   r   r   r   rj   r   r   r   r   rk   rl   aspect_ratio_binorig_height
orig_widthr   r*   r   latent_channelsr   num_warmup_stepstransformer_dtyper  ir   latent_model_inputr  
noise_prednoise_pred_uncondnoise_pred_textcallback_kwargsr   callback_outputsimagetorch_accelerator_module	oom_errores3                                                      r<   __call__SanaPipeline.__call__  sr   H *-=?U,VWW1E1S1S. "&&22c9#8 !!((44:#8 !!((44:#8 !!((44:#7  !677&,K 00JJ6aqJrMF."!*
	
  .!1 *VS"9"9JJvt$<$<VJ&,,Q/J''AEAVAVAbT**..w=hl
 ,,+"7'#9"7+I' 3&?!  
	
!"*  ++!II'=&MSTUM$)II/MOd.ekl$m! *<NN/*
&	
 **11==&&..MM	
 !::9J s9~0CnnFZFZ0ZZ\]^!)n ,,22%89\!),1>>AEAaAaUYYy1}%=gn" 88$6$<$<Q$?@#d&6&6&=&=&L&LL "--&))0A)B*7*:*:AR*:*S+@% %%)%:%: .  
 (--/
 339C9I9I!9L6%!2^YjGj5k!kJ ##**771<O!+!1!1!!1!;A!>J ..--j!WmHYmglmnop'3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s* I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLNa - :f ("Ejj0G'.ujlEJJ'O$ $D'22 &&->> 
((//2P2P(P^cdefg &,,CCE:Wbch&((44U4TE 	##%8O!//c :9~  c d e s+   6H"Y&Y&=Y8 &
Y58Z!>ZZ!)r   r   r   r   r   rR   rK   )Frg   N)Tr   r&   NNNNNFrg   NN)NNNNNN)Fr   )9__name__
__module____qualname____firstlineno____doc__r   r   r   model_cpu_offload_seqr   r	   r   r   r
   r   r   r   rM   rX   r]   ra   re   ry   r   r  r*   ri   boolr   r   r   Tensorr  r   r   r   r|   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRING	Generatorr   r   r   r'   r   r;  __static_attributes____classcell__)r6   s   @r<   r@   r@      s   
 jj  "a  bO =T\);;<\ ,\ 	\
 ,\ /\*"#!" $#&9=84c49n%84 84 {{	84
 84 !84 $,DI#684z -1!%&)-049=8<AE##&9=&*@lc49n%@l &*@l 	@l
  #@l &@l  -@l !) 6@l  (5@l )1(>@l @l !@l $,DI#6@l UO@lF!, ,0#"'+@F*2pd& $ $ & & * * # #   ]]_12 )-!#%#" #/0MQ*.048<9=AE%* #'+59KO9B#&	0
5s0c49n%s0 s0 !	s0
 9s0 Us0 s0  (}s0 s0 s0 s0 E%//43H"HIJs0 %,,'s0  -s0  (5s0  !) 6!s0" )1(>#s0$ c]%s0& 's0( )s0* !%+s0, #4S>2-s0. 'xc40@$0F'GH/s00 -1I1s02 !3s04 $(95s0H 
!5(	)Is0 3 s0r>   r@   )NNNN)Jr   r1   r   urllib.parseparser   r%  typingr   r   r   r   r   r   r	   r  transformersr
   r   r   	callbacksr   r   rR   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#   r$   "pixart_alpha.pipeline_pixart_sigmar%   pipeline_outputr'   torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr=  r   r   r(   r   r  rG  r   ry   r*   r  r=   r@   r.   r>   r<   <module>r]     s     	   D D D  R R A 3 * ; 5
 
 
 L K . G / ))MM			H	%!)
VV)
VV) VV) VV	)
 VV) VV) VV) 
FF) VV) VV) 
FF) VV) VV) 
FF) VV)  VV!)" VV#)$ VV%)& VV')( VV))* 
FF+), VV-). VV/)0 VV1)2 VV3)4 VV5)6 VV7)8 VV9): VV;)< 
FF=)> VV?)@ 
FFA)B 
FFC)D VVE)F FVVVVFQ) V , *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vv0$&9 v0r>   