
    bi#                        d dl Z d dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZmZmZ d dlZd dlmZmZ ddl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 dd
lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+  e#       rd dl,m-c m.Z/ dZ0ndZ0 e$jb                  e2      Z3 e!       rd dl4m5Z5  e"       rd dl6Z6dZ7	 	 	 	 ddee8   deee9ejt                  f      dee
e8      dee
e;      fdZ< G d de      Z=y)    N)CallableDictListOptionalTupleUnion)T5EncoderModelT5Tokenizer   )MultiPipelineCallbacksPipelineCallback)AllegroTransformer3DModelAutoencoderKLAllegro)get_3d_rotary_pos_embed_allegro)DiffusionPipeline)KarrasDiffusionSchedulers)BACKENDS_MAPPING	deprecateis_bs4_availableis_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )AllegroPipelineOutputTF)BeautifulSoupa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import AutoencoderKLAllegro, AllegroPipeline
        >>> from diffusers.utils import export_to_video

        >>> vae = AutoencoderKLAllegro.from_pretrained("rhymes-ai/Allegro", subfolder="vae", torch_dtype=torch.float32)
        >>> pipe = AllegroPipeline.from_pretrained("rhymes-ai/Allegro", vae=vae, torch_dtype=torch.bfloat16).to("cuda")
        >>> pipe.enable_vae_tiling()

        >>> prompt = (
        ...     "A seaside harbor with bright sunlight and sparkling seawater, with many boats in the water. From an aerial view, "
        ...     "the boats vary in size and color, some moving and some stationary. Fishing boats in the water suggest that this "
        ...     "location might be a popular spot for docking fishing boats."
        ... )
        >>> video = pipe(prompt, guidance_scale=7.5, max_sequence_length=512).frames[0]
        >>> export_to_video(video, "output.mp4", fps=15)
        ```
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           g/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/allegro/pipeline_allegro.pyretrieve_timestepsr3   U   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            3       *    e Zd ZdZ ej
                  d      Zg ZdZg dZ	de
dededed	ef
 fd
Z	 	 	 	 	 	 	 	 	 	 d?deeee   f   dedededeej.                     deej0                     deej0                     deej0                     deej0                     dedefdZd Z	 	 	 	 	 d@dZdAdZd Z	 dBd Zd!ej0                  d"ej0                  fd#Zd$ed%ed&ed'edej.                  f
d(Z d) Z!d* Z"d+ Z#d, Z$e%d-        Z&e%d.        Z'e%d/        Z(e%d0        Z) ejT                          e+e,      ddd1dd2ddddd3ddddddd4ddd!gddfdeeee   f   ded5ed6ee   d7e-d'ee   d%ee   d&ee   ded8e-d9eeej\                  eej\                     f      d!eej0                     deej0                     deej0                     deej0                     deej0                     d:ee   d;ed<eee/eee0gdf   e1e2f      d=ee   deded"ee3e4f   f.d>              Z5 xZ6S )CAllegroPipelinea  
    Pipeline for text-to-video generation using Allegro.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
    library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)

    Args:
        vae ([`AllegroAutoEncoderKL3D`]):
            Variational Auto-Encoder (VAE) Model to encode and decode video to and from latent representations.
        text_encoder ([`T5EncoderModel`]):
            Frozen text-encoder. PixArt-Alpha uses
            [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
            [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
        tokenizer (`T5Tokenizer`):
            Tokenizer of class
            [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
        transformer ([`AllegroTransformer3DModel`]):
            A text conditioned `AllegroTransformer3DModel` to denoise the encoded video latents.
        scheduler ([`SchedulerMixin`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
    u5   [#®•©™&@·º½¾¿¡§~\)\(\]\[\}\{\|\\/\*]{1,}ztext_encoder->transformer->vae)latentsprompt_embedsnegative_prompt_embeds	tokenizertext_encodervaetransformerr.   c                 r   t         |           | j                  |||||       t        | dd       r/dt	        | j
                  j                  j                        dz
  z  nd| _        t        | dd       r | j
                  j                  j                  nd| _
        t        | j                        | _        y )N)r:   r;   r<   r=   r.   r<      r         )vae_scale_factor)super__init__register_modulesgetattrr-   r<   configblock_out_channelsvae_scale_factor_spatialtemporal_compression_ratiovae_scale_factor_temporalr   video_processor)selfr:   r;   r<   r=   r.   r,   s         r2   rD   zAllegroPipeline.__init__   s     	lQ\hq 	 	
 CJ$PUW[B\A#dhhoo889A=>bc 	% ;B$t:TDHHOO66Z[ 	&  .t?\?\]r4   T r   N   promptdo_classifier_free_guidancenegative_promptnum_videos_per_promptr    r8   r9   prompt_attention_masknegative_prompt_attention_maskclean_captionmax_sequence_lengthc           	      ,   d|v rd}t        dd|d       || j                  }|}|| j                  ||
      }| j                  |d|d	d	d
      }|j                  }| j                  |dd
      j                  }|j
                  d   |j
                  d   k\  rXt        j                  ||      sB| j                  j                  |dd|dz
  df         }t        j                  d| d|        |j                  }|j                  |      }| j                  |j                  |      |      }|d   }| j                  | j                  j                  }n%| j                  | j                  j                  }nd}|j                  ||      }|j
                  \  }}}|j!                  d|d      }|j#                  ||z  |d      }|j!                  d|      }|j#                  ||z  d      }|r|t%        |t&              r|g|z  n|}| j                  ||
      }|j
                  d   }| j                  |d|d	d	d	d
      }|j                  }	|	j                  |      }	| j                  |j                  j                  |      |	      }|d   }|rs|j
                  d   }|j                  ||      }|j!                  d|d      }|j#                  ||z  |d      }|	j!                  d|      }	|	j#                  ||z  d      }	nd}d}	||||	fS )az  
        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_videos_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 PixArt-Alpha, 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 512): Maximum sequence length to use for the prompt.
        mask_featurezThe use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version.z1.0.0F)standard_warnN)rV   
max_lengthTpt)paddingr[   
truncationadd_special_tokensreturn_tensorslongest)r]   r`   r   zZThe following part of your input was truncated because T5 can only handle sequences up to z	 tokens: )attention_maskr   )dtyper    )r]   r[   r^   return_attention_maskr_   r`   )r   _execution_device_text_preprocessingr:   	input_idsshapetorchequalbatch_decodeloggerwarningrc   tor;   rd   r=   repeatview
isinstancestr)rM   rP   rQ   rR   rS   r    r8   r9   rT   rU   rV   rW   r/   deprecation_messager[   text_inputstext_input_idsuntruncated_idsremoved_textrd   bs_embedseq_len_uncond_tokensuncond_inputs                            r2   encode_promptzAllegroPipeline.encode_prompt   s   T V# #Fng/BRWX>++F )
 --fM-RF..$%#'# ) K )22N"nnVYW[n\ffO$$R(N,@,@,DDU[[N  $~~::?1j[\n_aNaKa;bc"|9\N<
 %0$>$>!$9$<$<V$D! --n.?.?.GXm-nM)!,M(%%++E)$$**EE%((uV(D,22'1%,,Q0EqI%**86K+KWVXY 5 < <Q@U V 5 : :8F[;[]_ ` '+A+I<FX[<\_-8bqM 44]R_4`M&,,Q/J>>$%&*#'# * L .:-H-H*-K-N-Nv-V*%)%6%6&&))&1B` &7 &" &<A%>"&,2215G%;%>%>USY%>%Z"%;%B%B1F[]^%_"%;%@%@LaAacjln%o"-K-R-RSTVk-l*-K-P-PQY\qQqsu-v*%)"-1*35KMkkkr4   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'   r(   r.   stepr*   r+   )rM   r   r   accepts_etaextra_step_kwargsaccepts_generators         r2   prepare_extra_step_kwargsz)AllegroPipeline.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*  r4   c           
      p    |dk  rt        d| d      |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
| d| d      ||t        d| d| d      ||	t        d      ||
t        d      |||j                  |j                  k7  r&t        d|j                   d|j                   d      |	j                  |
j                  k7  r&t        d|	j                   d|
j                   d      y y y c c}w )Nr   z(`num_frames` have to be positive but is .r@   z7`height` and `width` have to be divisible by 8 but are z and c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0krM   s     r2   	<genexpr>z/AllegroPipeline.check_inputs.<locals>.<genexpr>  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z 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   rr   rs   listtyperi   )rM   rP   
num_framesheightwidth"callback_on_step_end_tensor_inputsrR   r8   r9   rT   rU   r   s   `           r2   check_inputszAllegroPipeline.check_inputsp  s    ?G
|STUVVA:?eai1nVW]V^^cdicjjklmm-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"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   %F39F3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bs4rb   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   rV   rM   s    r2   processz4AllegroPipeline._text_preprocessing.<locals>.process  sH    **40**40 K zz|))+Kr4   )
r   rm   rn   r   formatr   rr   tupler   rs   )rM   r   rV   r   ts   ` `  r2   rg   z#AllegroPipeline._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\/?(?!@)))rN   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+$)rs   ulunquote_plusr   r   resubr   r   bad_punct_regexcompiler-   findallr   fix_texthtmlunescape)rM   captionregex2s      r2   r   zAllegroPipeline._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}}r4   c
                    t        |t              r)t        |      |k7  rt        dt        |       d| d      |dz  dk(  r#t	        j
                  || j                  z        }n(t	        j
                  |dz
  | j                  z        dz   }||||| j                  z  || j                  z  f}
|	t        |
|||      }	n|	j                  |      }	|	| j                  j                  z  }	|	S )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    rd   )rr   r   r-   r%   mathceilrK   rI   r   ro   r.   init_noise_sigma)rM   
batch_sizenum_channels_latentsr   r   r   rd   r    r   r7   ri   s              r2   prepare_latentszAllegroPipeline.prepare_latentsA  s     i&3y>Z+GA#i.AQ R&<'gi 
 >Q:0N0N#NOJJNd6T6T#TUXYYJ  d333T222
 ?"5IfTYZGjj(G DNN;;;r4   r7   returnc                     d| j                   j                  j                  z  |z  }| j                   j                  |      j                  }|j                  ddddd      }|S )Nr   r   r?   r   rA   )r<   rG   scaling_factordecodesamplepermute)rM   r7   framess      r2   decode_latentszAllegroPipeline.decode_latents`  sR    dhhoo444w>)001aA.r4   r   r   r   r   c           	         || j                   | j                  j                  j                  z  z  }|| j                   | j                  j                  j                  z  z  }d||f}	}t	        | j                  j                  j
                  ||	f||f|| j                  j                  j                  | j                  j                  j                  | j                  j                  j                  f|      \  }
}}}}}|j                  t        j                        }|j                  t        j                        }|j                  t        j                        }t        j                  |||      }|j                  dd      j                  dd      j                  ddd      j                         }|\  }}}|
||f|||ffS )N)r   r   )	embed_dimcrops_coords	grid_sizetemporal_sizeinterpolation_scaler    )rd   rb   r   r   r   )rI   r=   rG   
patch_sizer   attention_head_diminterpolation_scale_tinterpolation_scale_hinterpolation_scale_wro   rj   longcartesian_prodreshape	transpose
contiguous)rM   r   r   r   r   r    grid_height
grid_widthstartstopfreqs_tfreqs_hfreqs_wgrid_tgrid_hgrid_wposs                    r2   %_prepare_rotary_positional_embeddingsz5AllegroPipeline._prepare_rotary_positional_embeddingsf  s    !>!>AQAQAXAXAcAc!cdt<<t?O?O?V?V?a?aab
{J7t<[&&--@@"J/$  ''==  ''==  ''==!
 =
9'666 ,,,""666:kk"a **1a088ArBMMO!$'*VVV,DDDr4   c                 8    | j                   j                          y)z
        Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
        compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
        N)r<   enable_slicingrM   s    r2   enable_vae_slicingz"AllegroPipeline.enable_vae_slicing      
 	!r4   c                 8    | j                   j                          y)z
        Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
        computing decoding in one step.
        N)r<   disable_slicingr   s    r2   disable_vae_slicingz#AllegroPipeline.disable_vae_slicing  s    
 	  "r4   c                 8    | j                   j                          y)a  
        Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
        compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
        processing larger images.
        N)r<   enable_tilingr   s    r2   enable_vae_tilingz!AllegroPipeline.enable_vae_tiling  s     	 r4   c                 8    | j                   j                          y)z
        Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
        computing decoding in one step.
        N)r<   disable_tilingr   s    r2   disable_vae_tilingz"AllegroPipeline.disable_vae_tiling  r   r4   c                     | j                   S r   )_guidance_scaler   s    r2   guidance_scalezAllegroPipeline.guidance_scale  s    ###r4   c                     | j                   S r   )_num_timestepsr   s    r2   num_timestepszAllegroPipeline.num_timesteps  s    """r4   c                     | j                   S r   )_current_timestepr   s    r2   current_timestepz AllegroPipeline.current_timestep  s    %%%r4   c                     | j                   S r   )
_interruptr   s    r2   	interruptzAllegroPipeline.interrupt  s    r4   d   g      @g        pilr   r!   r   r   r   output_typereturn_dictcallback_on_step_endr   c                 
   t        |t        t        f      r|j                  }d}	|xs- | j                  j
                  j                  | j                  z  }|xs- | j                  j
                  j                  | j                  z  }|xs- | j                  j
                  j                  | j                  z  }| j                  ||||||||||
       || _        d| _        d| _        |t        |t              rd}n-|t        |t               rt#        |      }n|j$                  d   }| j&                  }|dkD  }| j)                  ||||	|||||||      \  }}}}|r2t+        j,                  ||gd      }t+        j,                  ||gd      }|j.                  dk(  r|j1                  d      }t3        | j4                  |||      \  }}| j4                  j7                  ||	       | j                  j
                  j8                  }| j;                  ||	z  |||||j<                  |||	      }| j?                  ||
      }| jA                  ||||jC                  d
      |      }tE        t#        |      || j4                  jF                  z  z
  d      }t#        |      | _$        | jK                  |      5 }tM        |      D ]  \  }} | jN                  r| | _        |rt+        j,                  |gd
z        n|}!| j4                  jQ                  |!|       }!| jS                  |!j$                  d         }"| j	                  |!|||"|d      d   }#|r|#jU                  d
      \  }$}%|$||%|$z
  z  z   }# | j4                  jV                  |#| |fi |ddid   }|Zi }&|D ]  }'tY               |'   |&|'<     || || |&      }(|(j[                  d|      }|(j[                  d|      }|(j[                  d|      }|t#        |      dz
  k(  s'|dz   |kD  r/|dz   | j4                  jF                  z  dk(  r|j]                          t^        sta        jb                           	 ddd       d| _        |dk(  sh|je                  | jf                  j<                        }| ji                  |      })|)ddddd|d|d|f   })| jj                  jm                  |)|      })n|})| jo                          |s|)fS tq        |)      S # 1 sw Y   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 video 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 video 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 100):
                The number of denoising steps. More denoising steps usually lead to a higher quality video at the
                expense of slower inference.
            timesteps (`List[int]`, *optional*):
                Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
                timesteps are used. Must be in descending order.
            guidance_scale (`float`, *optional*, defaults to 7.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 videos that are closely linked to
                the text `prompt`, usually at the expense of lower video quality.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of videos to generate per prompt.
            num_frames: (`int`, *optional*, defaults to 88):
                The number controls the generated video frames.
            height (`int`, *optional*, defaults to self.unet.config.sample_size):
                The height in pixels of the generated video.
            width (`int`, *optional*, defaults to self.unet.config.sample_size):
                The width in pixels of the generated video.
            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*):
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for video
                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 video. 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.
            callback (`Callable`, *optional*):
                A function that will be called every `callback_steps` steps during inference. The function will be
                called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
            callback_steps (`int`, *optional*, defaults to 1):
                The frequency at which the `callback` function will be called. If not specified, the callback will be
                called at every step.
            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.
            max_sequence_length (`int` defaults to `512`):
                Maximum sequence length to use with the `prompt`.

        Examples:

        Returns:
            [`~pipelines.allegro.pipeline_output.AllegroPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.allegro.pipeline_output.AllegroPipelineOutput`] is returned,
                otherwise a `tuple` is returned where the first element is a list with the generated videos.
        r   NFr   g      ?)	rR   rS   r    r8   r9   rT   rU   rV   rW   )dimr   )r    r?   )total)hidden_statesencoder_hidden_statesencoder_attention_masktimestepimage_rotary_embr   r   r7   r8   r9   latent)videor   )r   )9rr   r   r   tensor_inputsr=   rG   sample_framesrK   sample_heightrI   sample_widthr   r   r   r   rs   r   r-   ri   rf   r~   rj   catndim	unsqueezer3   r.   r)   in_channelsr   rd   r   r   sizemaxorderr   progress_bar	enumerater   scale_model_inputexpandchunkr   localspopupdateXLA_AVAILABLExm	mark_stepro   r<   r   rL   postprocess_videomaybe_free_model_hooksr   )*rM   rP   rR   r   r!   r   r   r   r   rS   r   r   r7   r8   rT   r9   rU   r   r   r   r   rV   rW   r   r    rQ   latent_channelsr   r  num_warmup_stepsr  ir   latent_model_inputr  
noise_prednoise_pred_uncondnoise_pred_textcallback_kwargsr   callback_outputsr	  s*                                             r2   __call__zAllegroPipeline.__call__  si   R *-=?U,VW1E1S1S. !  i4#3#3#:#:#H#H4KiKi#i
`4++22@@4C`C``]))00==@]@]]."!*	
  .!% *VS"9JJvt$<VJ&,,Q/J''
 '5s&:# '+"7'#9"7+I' 3  
	
!"* '!II'=}&MSTUM$)II/MOd.ekl$m!")33A6M *<DNNL_agir)s&	&$$%8$H **11==&&..

 !::9cJ  EEw||A

 s9~0CdnnFZFZ0ZZ\]^!)n%89 -	#\!), ,#1>>)*&A\UYYy1}%=bi"%)^^%E%EFXZ[%\" 88$6$<$<Q$?@ "--"4*7+@%%5 % .  
 /9C9I9I!9L6%!2^YjGj5k!kJ .$..--j!WmHYmglmnop (3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s*I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNY,#-	#^ "&h&jj0G''0E!QWfWfuf<=E((::T_:`EE 	##%8O$E22-	# -	#s   4F	S6?S66S?)
TrN   r   NNNNNFrO   )NNNNN)Fr   )7__name__
__module____qualname____doc__r   r   r   _optional_componentsmodel_cpu_offload_seqr   r
   r	   r   r   r   rD   r   rs   r   boolintr   rj   r    Tensorr~   r   r   rg   r   r   r   r   r   r   r   r   propertyr   r   r   r   no_gradr   EXAMPLE_DOC_STRINGfloat	Generatorr   r   r   r   r   r   r+  __classcell__)r,   s   @r2   r6   r6      sW   , !bjj	O  <^^ %^ "	^
 /^ -^4 -1!%&)-049=8<AE##&Elc49n%El &*El 	El
  #El &El  -El !) 6El  (5El )1(>El El !ElP!0 #"'+CL*2pf nr>ell u|| !E!E !E 	!E
 !E !EF"#!" $ $ # # & &   U]]_12 )-!#&# #$( $#%&MQ*.048<9=AE%*  9B"#&3F3c49n%F3 F3 !	F3
 9F3 F3 SMF3 F3 }F3  #F3 F3 E%//43H"HIJF3 %,,'F3  -F3  (5F3  !) 6!F3" )1(>#F3$ c]%F3& 'F3( '(Cd+T124DF\\]
)F3. -1I/F30 1F32 !3F34 
$e+	,5F3 3 F3r4   r6   )NNNN)>r   r'   r   r   urllib.parseparser   typingr   r   r   r   r   r   rj   transformersr	   r
   	callbacksr   r   modelsr   r   models.embeddingsr   pipelines.pipeline_utilsr   
schedulersr   utilsr   r   r   r   r   r   r   utils.torch_utilsr   rL   r   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr,  rm   r   r   r   r7  r3  rs   r    r8  r3   r6   r$   r4   r2   <module>rK     s       	  ? ?  4 A E @ 9 3   . - 2 ))MM 
		H	%! 2 *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vn3' n3r4   