
    bix                     ^   d dl Z d dlmZmZmZmZmZmZ d dlZ	d dl
Z
d dlmZmZ ddlmZmZ ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZmZ dd
lmZ ddlm Z  ddl!m"Z" ddl#m$Z$  e       rd dl%m&c m'Z( dZ)ndZ) ejT                  e+      Z, e       rd dl-Z-dZ.d Z/d Z0d Z1 G d de"e      Z2y)    N)AnyCallableDictListOptionalUnion)AutoTokenizerUMT5EncoderModel   )MultiPipelineCallbacksPipelineCallback)WanLoraLoaderMixin)AutoencoderKLWanWanTransformer3DModel)FlowMatchEulerDiscreteScheduler)is_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )WanPipelineOutputTFa  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers.utils import export_to_video
        >>> from diffusers import AutoencoderKLWan, WanPipeline
        >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler

        >>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
        >>> model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
        >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
        >>> pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
        >>> flow_shift = 5.0  # 5.0 for 720P, 3.0 for 480P
        >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
        >>> pipe.to("cuda")

        >>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
        >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"

        >>> output = pipe(
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     height=720,
        ...     width=1280,
        ...     num_frames=81,
        ...     guidance_scale=5.0,
        ... ).frames[0]
        >>> export_to_video(output, "output.mp4", fps=16)
        ```
c                     t        j                  |       } t        j                  t        j                  |             } | j	                         S N)ftfyfix_texthtmlunescapestriptexts    _/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/wan/pipeline_wan.pybasic_cleanr&   N   s3    ==D==t,-D::<    c                 T    t        j                  dd|       } | j                         } | S )Nz\s+ )resubr"   r#   s    r%   whitespace_cleanr,   T   s$    66&#t$D::<DKr'   c                 .    t        t        |             } | S r   )r,   r&   r#   s    r%   prompt_cleanr.   Z   s    K-.DKr'   c            *           e Zd ZdZdZg dZddgZ	 	 	 	 d;deded	e	d
e
dee   dee   dee   def fdZ	 	 	 	 	 d<deeee   f   dededeej*                     deej,                     f
dZ	 	 	 	 	 	 	 	 d=deeee   f   deeeee   f      dededeej0                     deej0                     dedeej*                     deej,                     fdZ	 	 	 	 d>dZ	 	 	 	 	 	 	 	 d?ded ed!ed"ed#edeej,                     deej*                     d$eeej6                  eej6                     f      d%eej0                     d&ej0                  fd'Zed(        Zed)        Zed*        Z ed+        Z!ed,        Z"ed-        Z# ejH                          e%e&      dddddd.d/ddddddd0dddd%gd1fdeeee   f   deeee   f   d!ed"ed#ed2ed3ed4ee   dee   d$eeej6                  eej6                     f      d%eej0                     deej0                     deej0                     d5ee   d6ed7ee'ee(f      d8eee)eee'gdf   e*e+f      d9ee   def&d:              Z, xZ-S )@WanPipelinea  
    Pipeline for text-to-video generation using Wan.

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

    Args:
        tokenizer ([`T5Tokenizer`]):
            Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
            specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        text_encoder ([`T5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        transformer ([`WanTransformer3DModel`]):
            Conditional Transformer to denoise the input latents.
        scheduler ([`UniPCMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLWan`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
        transformer_2 ([`WanTransformer3DModel`], *optional*):
            Conditional Transformer to denoise the input latents during the low-noise stage. If provided, enables
            two-stage denoising where `transformer` handles high-noise stages and `transformer_2` handles low-noise
            stages. If not provided, only `transformer` is used.
        boundary_ratio (`float`, *optional*, defaults to `None`):
            Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising.
            The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided,
            `transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps <
            boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.
    z-text_encoder->transformer->transformer_2->vae)latentsprompt_embedsnegative_prompt_embedstransformertransformer_2N	tokenizertext_encodervae	schedulerboundary_ratioexpand_timestepsc	                    t         	|           | j                  ||||||       | j                  |       | j                  |       t	        | dd       r | j
                  j                  j                  nd| _        t	        | dd       r | j
                  j                  j                  nd| _
        t        | j                        | _        y )N)r8   r7   r6   r4   r9   r5   )r:   )r;   r8         )vae_scale_factor)super__init__register_modulesregister_to_configgetattrr8   configscale_factor_temporalvae_scale_factor_temporalscale_factor_spatialvae_scale_factor_spatialr   video_processor)
selfr6   r7   r8   r9   r4   r5   r:   r;   	__class__s
            r%   rA   zWanPipeline.__init__   s     	%#' 	 	
 	~>1ABRYZ^`egkRl)N)Nrs&PWX\^ceiPj(L(Lpq%-t?\?\]r'   r   promptnum_videos_per_promptmax_sequence_lengthdevicedtypec                    |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}|D cg c]  }t        |       }}t        |      }| j                  |d|dddd      }|j                  |j                  }
}	|
j                  d      j                  d      j                         }| j                  |	j                  |      |
j                  |            j                  }|j                  ||      }t        ||      D cg c]
  \  }}|d |  }}}t!        j"                  |D cg c]J  }t!        j$                  ||j'                  ||j)                  d      z
  |j)                  d            g      L c}d      }|j*                  \  }}}|j-                  d|d      }|j/                  ||z  |d	      }|S c c}w c c}}w c c}w )
N
max_lengthTpt)paddingrS   
truncationadd_special_tokensreturn_attention_maskreturn_tensorsr   r   )dimrQ   rP   )_execution_devicer7   rQ   
isinstancestrr.   lenr6   	input_idsattention_maskgtsumlongtolast_hidden_stateziptorchstackcat	new_zerossizeshaperepeatview)rK   rM   rN   rO   rP   rQ   u
batch_sizetext_inputstext_input_idsmaskseq_lensr2   v_seq_lens                   r%   _get_t5_prompt_embedsz!WanPipeline._get_t5_prompt_embeds   s    14110**00'4&&+12a,q/22[
nn *#"& % 
  +44k6P6P771:>>a>(--/)).*;*;F*CTWWV_Ugg%((uV(D+.}h+GH41a2AHH^klYZUYY1;;':QVVAY'Fq	RSTlrs

 &++7A%,,Q0EqI%**:8M+MwXZ[7 3" Ils   GGAG!Tnegative_promptdo_classifier_free_guidancer2   r3   c
                    |xs | j                   }t        |t              r|gn|}|t        |      }
n|j                  d   }
|| j                  |||||	      }|r||xs d}t        |t              r|
|gz  n|}|:t        |      t        |      ur$t        dt        |       dt        |       d      |
t        |      k7  r!t        d| dt        |       d	| d|
 d
	      | j                  |||||	      }||fS )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 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`).
            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 videos that should be generated per prompt. 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. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            device: (`torch.device`, *optional*):
                torch device
            dtype: (`torch.dtype`, *optional*):
                torch dtype
        r   )rM   rN   rO   rP   rQ    z?`negative_prompt` should be the same type to `prompt`, but got z != .z`negative_prompt`: z has batch size z, but `prompt`: zT. Please make sure that passed `negative_prompt` matches the batch size of `prompt`.)	r]   r^   r_   r`   rn   rz   type	TypeError
ValueError)rK   rM   r{   r|   rN   r2   r3   rO   rP   rQ   rr   s              r%   encode_promptzWanPipeline.encode_prompt   sj   L 1411'4&&VJ&,,Q/J  66&;$7 7 M '+A+I-3O@J?\_@`jO+<<fuO!d6l$:O&OUVZ[jVkUl mV~Q(  s?33 )/)::J3K_J` ax/
| <33  &*%?%?&&;$7 &@ &" 444r'   c	           
          |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| d| d      ||t        d      |7t        |t              s't        |t
              st        dt        |             |7t        |t              s't        |t
              st        dt        |              j                  j                  |t        d      y y c c}	w )N   r   z8`height` and `width` have to be divisible by 16 but are z and r   c              3   :   K   | ]  }|j                   v   y wr   )_callback_tensor_inputs).0krK   s     r%   	<genexpr>z+WanPipeline.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.z'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: 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;`negative_prompt` has to be of type `str` or `list` but is zV`guidance_scale_2` is only supported when the pipeline's `boundary_ratio` is not None.)	r   allr   r^   r_   listr   rE   r:   )
rK   rM   r{   heightwidthr2   r3   "callback_on_step_end_tensor_inputsguidance_scale_2r   s
   `         r%   check_inputszWanPipeline.check_inputs  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  (-C-O9/9JJi  kA  jB B0 0  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa(?C0OUY9ZZ[_`o[pZqrss;;%%-2B2Nuvv 3O-1 pHs   E%E  @  Q   rr   num_channels_latentsr   r   
num_frames	generatorr1   returnc
                 P   |	|	j                  ||      S |dz
  | j                  z  dz   }
|||
t        |      | j                  z  t        |      | j                  z  f}t	        |t
              r)t        |      |k7  rt        dt        |       d| d      t        ||||      }	|	S )N)rP   rQ   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   rP   rQ   )	rf   rG   intrI   r^   r   r`   r   r   )rK   rr   r   r   r   r   rQ   rP   r   r1   num_latent_framesrn   s               r%   prepare_latentszWanPipeline.prepare_latentsD  s     ::V5:99'!^0N0NNQRR K4888J$777
 i&3y>Z+GA#i.AQ R&<'gi 
 u	&PUVr'   c                     | j                   S r   _guidance_scalerK   s    r%   guidance_scalezWanPipeline.guidance_scaled  s    ###r'   c                      | j                   dkD  S )N      ?r   r   s    r%   r|   z'WanPipeline.do_classifier_free_guidanceh  s    ##c))r'   c                     | j                   S r   )_num_timestepsr   s    r%   num_timestepszWanPipeline.num_timestepsl  s    """r'   c                     | j                   S r   )_current_timestepr   s    r%   current_timestepzWanPipeline.current_timestepp      %%%r'   c                     | j                   S r   )
_interruptr   s    r%   	interruptzWanPipeline.interruptt  s    r'   c                     | j                   S r   )_attention_kwargsr   s    r%   attention_kwargszWanPipeline.attention_kwargsx  r   r'   2   g      @npi   num_inference_stepsr   r   output_typereturn_dictr   callback_on_step_endr   c                 X   t        |t        t        f      r|j                  }| j	                  ||||||||       || j
                  z  dk7  rBt        j                  d| j
                   d       || j
                  z  | j
                  z  dz   }t        |d      }| j                  j                  ||}|| _        || _        || _        d| _        d| _        | j                   }|t        |t"              rd}n-|t        |t$              rt'        |      }n|j(                  d   }| j+                  ||| j,                  |	||||      \  }}| j.                  | j.                  j0                  n| j2                  j0                  }|j5                  |      }||j5                  |      }| j6                  j9                  ||       | j6                  j:                  }| j.                   | j.                  j                  j<                  n| j2                  j                  j<                  }| j?                  ||	z  ||||t@        jB                  ||
|	      }tA        jD                  |j(                  t@        jB                  |	      }t'        |      || j6                  jF                  z  z
  }t'        |      | _$        | j                  j                  8| j                  j                  | j6                  j                  jJ                  z  }nd}| jM                  |
      5 }tO        |      D ]&  \  }}| jP                  r|| _        |||k\  r| j.                  }|} n| j2                  }|} |j5                  |      }!| j                  jR                  rV|d   d   ddddddddf   |z  jU                         }"|"jW                  d      jY                  |j(                  d   d      }#n|jY                  |j(                  d         }#|j[                  d      5   ||!|#||d      d   }$ddd       | j,                  r5|j[                  d      5   ||!|#||d      d   }%ddd       %| $|%z
  z  z   }$| j6                  j]                  $||d      d   }|Zi }&|D ]  }'t_               |'   |&|'<     || |||&      }(|(ja                  d|      }|(ja                  d|      }|(ja                  d|      }|t'        |      dz
  k(  s'|dz   |kD  r/|dz   | j6                  jF                  z  dk(  r|jc                          td        stg        jh                          ) 	 ddd       d| _        |dk(  s~|j5                  | jj                  j0                        }tA        jl                  | jj                  j                  jn                        jq                  d| jj                  j                  jr                  ddd      j5                  |jt                  |j0                        })dtA        jl                  | jj                  j                  jv                        jq                  d| jj                  j                  jr                  ddd      j5                  |jt                  |j0                        z  }*||*z  |)z   }| jj                  jy                  |d      d   }+| jz                  j}                  |+|      }+n|}+| j                          |s|+fS t        |+      S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w)a  
        The call function to the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
                instead. Ignored when not using guidance (`guidance_scale` < `1`).
            height (`int`, defaults to `480`):
                The height in pixels of the generated image.
            width (`int`, defaults to `832`):
                The width in pixels of the generated image.
            num_frames (`int`, defaults to `81`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, defaults to `5.0`):
                Guidance scale as defined in [Classifier-Free Diffusion
                Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
                of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
                `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
                the text `prompt`, usually at the expense of lower image quality.
            guidance_scale_2 (`float`, *optional*, defaults to `None`):
                Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline's
                `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2`
                and the pipeline's `boundary_ratio` are not None.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                A [`torch.Generator`](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 is 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 (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            output_type (`str`, *optional*, defaults to `"np"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
            attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
                each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
                DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
                list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            max_sequence_length (`int`, defaults to `512`):
                The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
                truncated. If the prompt is shorter, it will be padded to this length.

        Examples:

        Returns:
            [`~WanPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
                the first element is a list with the generated images and the second element is a list of `bool`s
                indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
        r   z(`num_frames - 1` has to be divisible by z!. Rounding to the nearest number.NFr   )rM   r{   r|   rN   r2   r3   rO   rP   )rP   r[   )totalr   r\   cond)hidden_statestimestepencoder_hidden_statesr   r   uncond)r   r1   r2   r3   latentr   )r   )frames)Ar^   r   r   tensor_inputsr   rG   loggerwarningmaxrE   r:   r   _guidance_scale_2r   r   r   r]   r_   r   r`   rn   r   r|   r4   rQ   r5   rf   r9   set_timesteps	timestepsin_channelsr   ri   float32onesorderr   num_train_timestepsprogress_bar	enumerater   r;   flatten	unsqueezeexpandcache_contextsteplocalspopupdateXLA_AVAILABLExm	mark_stepr8   tensorlatents_meanrp   z_dimrP   latents_stddecoderJ   postprocess_videomaybe_free_model_hooksr   ),rK   rM   r{   r   r   r   r   r   r   rN   r   r1   r2   r3   r   r   r   r   r   rO   rP   rr   transformer_dtyper   r   ru   num_warmup_stepsboundary_timestepr   itcurrent_modelcurrent_guidance_scalelatent_model_inputtemp_tsr   
noise_prednoise_uncondcallback_kwargsr   callback_outputsr   r   videos,                                               r%   __call__zWanPipeline.__call__|  s   @ *-=?U,VW1E1S1S. 	".		
 666!;NN:4;Y;Y:ZZ{| $t'E'EEHfHffijjJQ'
;;%%16F6N--!1!1!%'' *VS"9JJvt$<VJ&,,Q/J 150B0B+(,(H(H"7'#9 3 1C 	1
-- 7;6F6F6RD,,22X\XjXjXpXp%(():;!-%;%>%>?P%Q" 	$$%8$HNN,,	
 + ##//##**66 	
 &&.. MM

 zz'--u}}VL y>,?$..BVBV,VV!)n;;%%1 $ : :T^^=R=R=f=f f $%89 ?	#\!), >#1>>)*&$,5F0F$($4$4M-;* %)$6$6M-=*%,ZZ0A%B";;//#Awqz!SqS#A#+6:CCEG&003::7==;KRPH xxa(89H"008 !.&8!).;)9$)" "J 33&44X> '4*<%-2H-=(-( ( ".0F*WcJc0d!dJ ..--j!WRW-XYZ['3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s* I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLN}>#?	#B "&h&jj0GTXX__99:a..1a8GNNGMM2 
 TXX__-H-H I N NqRVRZRZRaRaRgRgijlmop q t t! K +l:GHHOOGO?BE((::5k:ZEE 	##%8O ..A  G?	# ?	#sD   C7\\ %\\C\7\\
\\\\))NNNF)Nr      NN)NTr   NNr   NN)NNNN)r   r   r   r   NNNN).__name__
__module____qualname____doc__model_cpu_offload_seqr   _optional_componentsr	   r
   r   r   r   r   floatboolrA   r   r_   r   r   ri   rP   rQ   rz   Tensorr   r   	Generatorr   propertyr   r|   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   r   r   r   r   r   __classcell__)rL   s   @r%   r0   r0   _   s   < LT)?; 8<9=*.!&^ ^ '^ 	^
 3^ 34^   56^ !^ ^: )-%&#&)-'+'c49n%'  #' !	'
 &' $'X <@,0%&049=#&)-'+O5c49n%O5 "%T#Y"78O5 &*	O5
  #O5  -O5 !) 6O5 !O5 &O5 $O5n #+/+w` %''+)-MQ*. " 	
   $ & E%//43H"HIJ %,,' 
@ $ $ * * # # & &   & & U]]_12 )-15#% #,0/0MQ*.049=%) 59 9B#&-R/c49n%R/ sDI~.R/ 	R/
 R/ R/ !R/ R/ #5/R/  (}R/ E%//43H"HIJR/ %,,'R/  -R/ !) 6R/ c]R/  !R/" #4S>2#R/$ '(Cd+T124DF\\]
%R/* -1I+R/, !-R/ 3 R/r'   r0   )3r    typingr   r   r   r   r   r   regexr*   ri   transformersr	   r
   	callbacksr   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   rJ   r   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr   r   r   r   r&   r,   r.   r0    r'   r%   <module>r     s     = =   8 A ) = 9 b b - - . . ))MM			H	% @
q/#%7 q/r'   