ó
    oM‡j—  ã                   óZ  • S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SK Jr  S SKJ	r	  S SK
JrJr  S SKrS SKrS SKJs  Jr  \R(                  R+                  5       (       a  S SKJrJr  S SKJr  S SKJr  OSrSrSrSrSS	KJr  SS
K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+  \+" 5       (       a1  S SK,r,\,RZ                  R\                  R_                  5       (       a  S SK.r.\'" 5       (       a  S SK0J1r1  \(" 5       (       a  S SK2J3r3  \*" 5       (       a  S SK4J5r5  \)" 5       (       a  S SK6r6S\74S jr8S r9SSSSS.S\Rt                  S\Rt                  S\;S\;S\Rt                  S-  S\7S\<\Rt                  \Rt                  \Rt                  4   4S jjr=S\>4S  jr? SOS!\S"\"S#\Rt                  S$\Rt                  S%\Rt                  S&\Rt                  S'\Rt                  S(\;S\<\Rt                  \Rt                  4   4S) jjr@S!\S\A\>\Rt                  4   4S* jrB\R†                  4S+\R"                  Rˆ                  \E\R"                  Rˆ                     -  4S, jjrFS-\A\>\Rt                  4   S.\>S/\R"                  Rˆ                  4S0 jrGS1\A\>\R"                  Rˆ                  4   S\A\>\4   4S2 jrH     SPS3\>S4\7S5\;S6\;S7\;S8\R’                  \>-  S9\R”                  S-  4S: jjrKSQS3\>4S; jjrLS< rM\S=S>.S?\R"                  Rˆ                  \ -  S8\>\R’                  -  S@\N4SA jj5       rOSB rPSC rQ/ SDQrRSRSE jrSS\A4SF jrTS\A4SG jrU     SSS+\R"                  Rˆ                  S8\>\R’                  -  S@\NSH\NSI\NSJ\A\>\4   S-  SK\V\W\R"                  Rˆ                        S-  S\4SL jjrX " SM SN5      rYg)Té    N)Úcontextmanager)Úpartial)ÚAnyÚIterable)Ú
CPUOffloadÚShardingStrategy)ÚFullyShardedDataParallel)Útransformer_auto_wrap_policyé   )ÚUNet2DConditionModel)ÚDiffusionPipeline)ÚSchedulerMixin)Úconvert_state_dict_to_diffusersÚconvert_state_dict_to_peftÚ	deprecateÚis_accelerate_availableÚis_peft_availableÚis_torch_npu_availableÚis_torchvision_availableÚis_transformers_available)Ú
get_logger)Úset_peft_model_state_dict)Ú
transformsÚseedc                 ó6  • [         R                  " U 5        [        R                   R                  U 5        [        R                  " U 5        [        5       (       a   [        R                  R                  U 5        g[        R                  R                  U 5        g)z™
Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch`.

Args:
    seed (`int`): The seed to set.

Returns:
    `None`
N)	Úrandomr   ÚnpÚtorchÚmanual_seedr   ÚnpuÚmanual_seed_allÚcuda)r   s    Ú¦C:\Users\johnn\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0\LocalCache\local-packages\Python313\site-packages\diffusers/training_utils.pyÚset_seedr$   =   s[   € ô ‡K‚K�ÔÜ‡I�I‡N�N�4ÔÜ	×Ò�dÔÜ×ÑÜ�	‰	×!Ñ! $Õ'ä�
‰
×"Ñ" 4Õ(ó    c                 óÖ  • U R                   nUS-  nSU-
  S-  nUR                  UR                  S9U   R                  5       n[	        UR
                  5      [	        UR
                  5      :  a3  US   n[	        UR
                  5      [	        UR
                  5      :  a  M3  UR                  UR
                  5      nUR                  UR                  S9U   R                  5       n[	        UR
                  5      [	        UR
                  5      :  a3  US   n[	        UR
                  5      [	        UR
                  5      :  a  M3  UR                  UR
                  5      nXV-  S-  nU$ )a_  
Computes SNR as per
https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
for the given timesteps using the provided noise scheduler.

Args:
    noise_scheduler (`NoiseScheduler`):
        An object containing the noise schedule parameters, specifically `alphas_cumprod`, which is used to compute
        the SNR values.
    timesteps (`torch.Tensor`):
        A tensor of timesteps for which the SNR is computed.

Returns:
    `torch.Tensor`: A tensor containing the computed SNR values for each timestep.
ç      à?ç      ð?©Údevice).Né   )Úalphas_cumprodÚtor*   ÚfloatÚlenÚshapeÚexpand)Únoise_schedulerÚ	timestepsr,   Úsqrt_alphas_cumprodÚsqrt_one_minus_alphas_cumprodÚalphaÚsigmaÚsnrs           r#   Úcompute_snrr9   Q   sF  € ð  %×3Ñ3€NØ(¨#Ñ-ÐØ%(¨>Ñ%9¸cÑ$AÐ!ð .×0Ñ0¸	×8HÑ8HÐ0ÐIÈ)ÑT×ZÑZÓ\ÐÜ
Ð!×'Ñ'Ó
(¬3¨y¯©Ó+?Ó
?Ø1°)Ñ<Ðô Ð!×'Ñ'Ó
(¬3¨y¯©Ó+?Õ
?à×&Ñ& y§¡Ó7€Eà$A×$DÑ$DÈI×L\ÑL\Ð$DÐ$]Ð^gÑ$h×$nÑ$nÓ$pÐ!Ü
Ð+×1Ñ1Ó
2´S¸¿¹Ó5IÓ
IØ(EÀiÑ(PÐ%ô Ð+×1Ñ1Ó
2´S¸¿¹Ó5IÕ
Ià)×0Ñ0°·±ÓA€Eð ‰=˜QÑ
€CØ€Jr%   ç        r(   iœÿÿÿ)Úlambda_confÚtemperatureÚper_token_weightsÚignore_indexÚlogitsÚlabelsr;   r<   r=   r>   Úreturnc                óh  • U R                   S:  a"  [        S[        U R                  5       S35      eUR                  U R                  SS :w  a8  [        S[        UR                  5       S[        U R                  5       S35      eUS::  a  [        S	U S35      eUR	                  U5      nUc  [
        R                  " XR                  S
9nOkUR                  UR                  :w  a8  [        S[        UR                  5       S[        UR                  5       S35      eUR                  U R                  S
9nU R                  S   n[        R                  " U R                  SU5      UR                  S5      SUS9R                  U5      n	XvR                  UR                  5      -  R                  5       R                  S5      n
X—-  UR                  U	R                  5      -  R                  5       U
-  nUS:X  a.  [
        R                  " SU R                   UR                  S9nX»U4$ [
        R"                  " 5          U R%                  SS9nXmR'                  U5      -  nSSS5        U R)                  5       nUS:w  a  U[)        U5      -  n[
        R*                  " USS9n[
        R,                  " UR                  5      R.                  n[
        R0                  " UR                  U5      5      nUU-  R                  SS9R                  U R                  S
9* nUWR                  UR                  5      -  R                  5       R                  S5      nUU-  UR                  UR                  5      -  R                  5       U-  nU[)        U5      U-  -   nUX¼4$ ! , (       d  f       GNC= f)a•  
Computes a confidence-aware training loss for token classification-style heads.

This loss combines:
  - `loss_sft`: standard supervised cross-entropy on all non-ignored labels.
  - `loss_conf`: an entropy penalty applied only on tokens that are already predicted correctly.

Args:
    logits (`torch.Tensor`): Logits of shape `(..., vocab_size)`.
    labels (`torch.Tensor`): Labels of shape `(...)`, matching `logits.shape[:-1]`. Values set to `ignore_index`
        are excluded from both losses.
    lambda_conf (`float`, *optional*, defaults to `0.0`): Weight for the confidence term.
    temperature (`float`, *optional*, defaults to `1.0`): Temperature used for the entropy term only. Lower values
        sharpen the distribution and change the strength of the confidence gradients.
    per_token_weights (`torch.Tensor`, *optional*): Optional weights of shape `(...)` to reweight both losses per
        token (e.g. schedule-aware weights). Tokens with weight `0` contribute nothing.
    ignore_index (`int`, *optional*, defaults to `-100`): Ignore index for labels.

Returns:
    `Tuple[torch.Tensor, torch.Tensor, torch.Tensor]`: `(loss, loss_sft, loss_conf)`.
r+   z.`logits` must have at least 2 dims, got shape Ú.Néÿÿÿÿz:`labels` shape must match `logits.shape[:-1]`, got labels=z logits=r   z`temperature` must be > 0, got )Údtypez9`per_token_weights` shape must match `labels` shape, got z != Únone)Ú	reductionr>   r   r:   © )r*   rE   )Údimr(   )ÚndimÚ
ValueErrorÚtupler0   Úner   Ú	ones_likerE   r-   ÚFÚcross_entropyÚreshapeÚ
reshape_asÚsumÚ	clamp_minÚzerosr*   Úno_gradÚargmaxÚeqr.   ÚsoftmaxÚfinfoÚtinyÚlog)r?   r@   r;   r<   r=   r>   ÚvalidÚweightsÚ
vocab_sizeÚper_token_nllÚ	denom_sftÚloss_sftÚ	loss_confÚpredÚcorrectÚscaled_logitsÚprobsÚepsÚ	log_probsÚentropyÚ
denom_confÚlosss                         r#   Úcompute_confidence_aware_lossrm   v   sQ  € ð< ‡{�{�QƒÜÐIÌ%ÐPV×P\ÑP\ÓJ]ÐI^Ð^_Ð`ÓaÐaØ‡|�|�v—|‘| C RÐ(Ó(ÜØHÌÈvÏ|É|ÓI\ÐH]Ð]eÔfkÐlr×lxÑlxÓfyÐezÐz{Ð|ó
ð 	
ð �aÓÜÐ:¸;¸-ÀqÐIÓJÐJà�I‰I�lÓ#€EØÑ Ü—/’/ &·±Ñ=‰à×"Ñ" f§l¡lÓ2ÜØKÌEÐRc×RiÑRiÓLjÐKkÐkoÔpuÐv|÷  wCñ  wCó  qDð  pEð  EFð  Góð ð $×&Ñ&¨V¯\©\Ð&Ð:ˆð —‘˜bÑ!€JÜ—O’OØ�‰�r˜:Ó&Ø�‰�rÓØØ!ñ	÷
 �j�Óð ð Ÿ8™8 G§M¡MÓ2Ñ2×7Ñ7Ó9×CÑCÀAÓF€IØÑ'¨%¯(©(°=×3FÑ3FÓ*GÑG×LÑLÓNÐQZÑZ€Hð �cÓÜ—K’K ¨6¯=©=ÀÇÁÑOˆ	Ø 9Ð,Ð,ä	�Š�Ø�}‰} ˆ}Ð$ˆØŸ'™' &›/Ñ)ˆ÷ 
ð —L‘L“N€MØ�cÓØ%¬¨kÓ(:Ñ:ˆä�MŠM˜-¨RÑ0€EÜ
�+Š+�e—k‘kÓ
"×
'Ñ
'€CÜ—	’	˜%Ÿ/™/¨#Ó.Ó/€IØ˜	Ñ!×&Ñ&¨2Ð&Ð.×1Ñ1¸¿¹Ð1ÐEÐE€Gà˜GŸJ™J w§}¡}Ó5Ñ5×:Ñ:Ó<×FÑFÀqÓI€JØ˜7Ñ" W§Z¡Z°·±Ó%>Ñ>×CÑCÓEÈ
ÑR€Ià”e˜KÓ(¨9Ñ4Ñ4€DØ�Ð$Ð$÷# 
Žús   É#N"Î"
N1Úinterpolation_typec                 ó0  • [        5       (       d  [        S5      eU S:X  a  [        R                  R                  nU$ U S:X  a  [        R                  R
                  nU$ U S:X  a  [        R                  R                  nU$ U S:X  a  [        R                  R                  nU$ U S:X  a  [        R                  R                  nU$ U S:X  a  [        R                  R                  nU$ U S:X  a  [        R                  R                  nU$ [        S	U  S
35      e)a¥  
Maps a string describing an interpolation function to the corresponding torchvision `InterpolationMode` enum. The
full list of supported enums is documented at
https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.functional.InterpolationMode.

Args:
    interpolation_type (`str`):
        A string describing an interpolation method. Currently, `bilinear`, `bicubic`, `box`, `nearest`,
        `nearest_exact`, `hamming`, and `lanczos` are supported, corresponding to the supported interpolation modes
        in torchvision.

Returns:
    `torchvision.transforms.InterpolationMode`: an `InterpolationMode` enum used by torchvision's `resize`
    transform.
zhPlease make sure to install `torchvision` to be able to use the `resolve_interpolation_mode()` function.ÚbilinearÚbicubicÚboxÚnearestÚnearest_exactÚhammingÚlanczoszThe given interpolation mode z’ is not supported. Currently supported interpolation modes are `bilinear`, `bicubic`, `box`, `nearest`, `nearest_exact`, `hamming`, and `lanczos`.)r   ÚImportErrorr   ÚInterpolationModeÚBILINEARÚBICUBICÚBOXÚNEARESTÚNEAREST_EXACTÚHAMMINGÚLANCZOSrK   )rn   Úinterpolation_modes     r#   Úresolve_interpolation_moder�   Ì   s>  € ô  $×%Ñ%ÜØvó
ð 	
ð ˜ZÓ'Ü'×9Ñ9×BÑBÐð& Ðð% 
˜yÓ	(Ü'×9Ñ9×AÑAÐð" Ðð! 
˜uÓ	$Ü'×9Ñ9×=Ñ=Ðð Ðð 
˜yÓ	(Ü'×9Ñ9×AÑAÐð Ðð 
˜Ó	.Ü'×9Ñ9×GÑGÐð Ðð 
˜yÓ	(Ü'×9Ñ9×AÑAÐð Ðð 
˜yÓ	(Ü'×9Ñ9×AÑAÐð Ðô Ø+Ð,>Ð+?ð @mð nó
ð 	
r%   Úunetr2   r3   ÚnoiseÚnoisy_latentsÚtargetÚencoder_hidden_statesÚdream_detail_preservationc                 ó\  • UR                   R                  UR                  5      USSS4   nSU-
  S-  n	X—-  n
Sn[        R                  " 5          U " XBU5      R
                  nSSS5        Su  pÍUR                  R                  S:X  aL  UnX>-
  R                  5       nUR                  U
5        UR                  XŸ-  5      nUR                  U5      nXÍ4$ UR                  R                  S:X  a  [        S5      e[        SUR                  R                   35      e! , (       d  f       N¿= f)	a²  
Implements "DREAM (Diffusion Rectification and Estimation-Adaptive Models)" from
https://huggingface.co/papers/2312.00210. DREAM helps align training with sampling to help training be more
efficient and accurate at the cost of an extra forward step without gradients.

Args:
    `unet`: The state unet to use to make a prediction.
    `noise_scheduler`: The noise scheduler used to add noise for the given timestep.
    `timesteps`: The timesteps for the noise_scheduler to user.
    `noise`: A tensor of noise in the shape of noisy_latents.
    `noisy_latents`: Previously noise latents from the training loop.
    `target`: The ground-truth tensor to predict after eps is removed.
    `encoder_hidden_states`: Text embeddings from the text model.
    `dream_detail_preservation`: A float value that indicates detail preservation level.
      See reference.

Returns:
    `tuple[torch.Tensor, torch.Tensor]`: Adjusted noisy_latents and target.
Nr(   r'   )NNÚepsilonÚv_predictionz/DREAM has not been implemented for v-predictionzUnknown prediction type )r,   r-   r*   r   rV   ÚsampleÚconfigÚprediction_typeÚdetachÚmul_ÚaddÚNotImplementedErrorrK   )r‚   r2   r3   rƒ   r„   r…   r†   r‡   r,   r5   Údream_lambdard   Ú_noisy_latentsÚ_targetÚpredicted_noiseÚdelta_noises                   r#   Ú compute_dream_and_update_latentsr—   ø   s*  € ð: %×3Ñ3×6Ñ6°y×7GÑ7GÓHÈÐTXÐZ^Ð`dÐIdÑe€NØ%(¨>Ñ%9¸cÑ$AÐ!ð 1ÑK€Là€DÜ	�Š�Ù�MÐ.CÓD×KÑKˆ÷ 
ð +Ñ€NØ×Ñ×-Ñ-°Ó:ØˆØÑ.×6Ñ6Ó8ˆØ×Ñ˜Ô&Ø&×*Ñ*Ð+HÑ+VÓWˆØ—*‘*˜[Ó)ˆð Ð"Ð"ð 
×	Ñ	×	/Ñ	/°>Ó	AÜ!Ð"SÓTÐTäÐ3°O×4JÑ4J×4ZÑ4ZÐ3[Ð\Ó]Ð]÷ 
�ús   ÁDÄ
D+c                 óè   • 0 nU R                  5        H[  u  p#[        US5      (       d  M  [        US5      nUc  M)  UR                  5       nUR	                  5        H  u  pgXqU SU 3'   M     M]     U$ )z@
Returns:
    A state dict containing just the LoRA parameters.
Úset_lora_layerÚ
lora_layerz.lora.)Únamed_modulesÚhasattrÚgetattrÚ
state_dictÚitems)r‚   Úlora_state_dictÚnameÚmodulerš   Úcurrent_lora_layer_sdÚlora_layer_matrix_nameÚ
lora_params           r#   Úunet_lora_state_dictr¦   .  s‚   € ð
 €Oà×*Ñ*Ö,‰ˆÜ�6Ð+×,Ó,Ü  ¨Ó6ˆJØÓ%Ø(2×(=Ñ(=Ó(?Ð%Ø:O×:UÑ:UÖ:WÑ6Ð*àOY t f¨FÐ3IÐ2JÐ$KÓLó ;Xñ -ð Ðr%   Úmodelc                 óÆ   • [        U [        5      (       d  U /n U  HC  nUR                  5        H,  nUR                  (       d  M  UR	                  U5      Ul        M.     ME     g)zÐ
Casts the training parameters of the model to the specified data type.

Args:
    model: The PyTorch model whose parameters will be cast.
    dtype: The data type to which the model parameters will be cast.
N)Ú
isinstanceÚlistÚ
parametersÚrequires_gradr-   Údata)r§   rE   ÚmÚparams       r#   Úcast_training_paramsr°   A  sM   € ô �eœT×"Ñ"Ø�ˆÛˆØ—\‘\–^ˆEà×"×"Ñ"Ø"ŸX™X e›_�–
ó $ò r%   r    ÚprefixÚtext_encoderc                 óè   • U R                  5        VVs0 s H1  u  p4UR                  U5      (       d  M  UR                  US5       U_M3     nnn[        [	        U5      5      n[        X%SS9  gs  snnf )a,  
Sets the `lora_state_dict` into `text_encoder` coming from `transformers`.

Args:
    lora_state_dict: The state dictionary to be set.
    prefix: String identifier to retrieve the portion of the state dict that belongs to `text_encoder`.
    text_encoder: Where the `lora_state_dict` is to be set.
Ú Údefault)Úadapter_nameN)rŸ   Ú
startswithÚreplacer   r   r   )r    r±   r²   ÚkÚvÚtext_encoder_state_dicts         r#   Ú!_set_state_dict_into_text_encoderr¼   R  ss   € ð 3B×2GÑ2GÔ2IôÚ2I©$¨!ÈQÏ\É\ÐZ`×MaÓ%ˆ1�9‰9�V˜RÓ Ð
! AÒ%Ñ2Ið ñ ô 9Ô9XÐYpÓ9qÓrÐÜ˜lÐR[Ó\ùó	s
   ”A.´A.Úmodules_to_savec                 óŠ   • 0 nU R                  5        H,  u  p#Uc  M
  UR                  S   R                  5       X S3'   M.     U$ )Nrµ   Ú_lora_adapter_metadata)rŸ   Úpeft_configÚto_dict)r½   Ú	metadatasÚmodule_namer¢   s       r#   Ú_collate_lora_metadatarÄ   e  sP   € Ø€IØ.×4Ñ4Ö6ÑˆØÓØ@F×@RÑ@RÐS\Ñ@]×@eÑ@eÓ@gˆI˜Ð%;Ð<Ó=ñ  7ð Ðr%   Úweighting_schemeÚ
batch_sizeÚ
logit_meanÚ	logit_stdÚ
mode_scaler*   Ú	generatorc                 óv  • U S:X  aB  [         R                  " X#U4XVS9n[         R                  R                  R	                  U5      nU$ U S:X  aT  [         R
                  " U4XVS9nSU-
  U[         R                  " [        R                  U-  S-  5      S-  S-
  U-   -  -
  nU$ [         R
                  " U4XVS9nU$ )zò
Compute the density for sampling the timesteps when doing SD3 training.

Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.

SD3 paper reference: https://huggingface.co/papers/2403.03206v1.
Úlogit_normal)ÚmeanÚstdÚsizer*   rÊ   Úmode)rÏ   r*   rÊ   r   r+   )	r   ÚnormalÚnnÚ
functionalÚsigmoidÚrandÚcosÚmathÚpi)rÅ   rÆ   rÇ   rÈ   rÉ   r*   rÊ   Úus           r#   Ú%compute_density_for_timestep_samplingrÚ   m  sµ   € ð  ˜>Ó)Ü�LŠL˜j¸z¸mÐTZÑpˆÜ�H‰H×Ñ×'Ñ'¨Ó*ˆð €Hð 
˜VÓ	#Ü�JŠJ˜Z˜M°&ÑNˆØ�‰E�J¤%§)¢)¬D¯G©G°a©K¸!©OÓ"<ÀÑ"AÀAÑ"EÈÑ"IÑJÑJˆð €Hô �JŠJ˜Z˜M°&ÑNˆØ€Hr%   c                 óÆ   • U S:X  a  US-  R                  5       nU$ U S:X  a)  SSU-  -
  SUS-  -  -   nS[        R                  U-  -  nU$ [        R                  " U5      nU$ )zÛ
Computes loss weighting scheme for SD3 training.

Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.

SD3 paper reference: https://huggingface.co/papers/2403.03206v1.
Ú
sigma_sqrtg       ÀÚcosmapr   r+   )r.   r×   rØ   r   rN   )rÅ   ÚsigmasÚ	weightingÚbots       r#   Úcompute_loss_weighting_for_sd3rá   ˆ  sz   € ð ˜<Ó'Ø˜T‘\×(Ñ(Ó*ˆ	ð Ðð 
˜XÓ	%Ø�!�f‘*‰n˜q 6¨1¡9™}Ñ,ˆØœŸ™ 3™Ñ'ˆ	ð Ðô —O’O FÓ+ˆ	ØÐr%   c                  óV  • [         R                  " 5         [        R                  R	                  5       (       a  [        R                  R                  5         g[        R                  R                  R	                  5       (       a  [        R                  R                  5         g[        5       (       a  [        R                  R                  5         g[        [        S5      (       aC  [        R                  R	                  5       (       a  [        R                  R                  5         ggg)zN
Runs garbage collection. Then clears the cache of the available accelerator.
ÚxpuN)ÚgcÚcollectr   r"   Úis_availableÚempty_cacheÚbackendsÚmpsr   Ú	torch_npur    rœ   rã   rH   r%   r#   Úfree_memoryrë   š  s©   € ô ‡J‚J„Lä‡z�z×Ñ× Ñ Ü�
‰
×ÑÕ Ü	�‰×	Ñ	×	(Ñ	(×	*Ñ	*Ü�	‰	×ÑÕÜ	×	!Ñ	!Ü�‰×!Ñ!Õ#Ü	”˜×	Ñ	¤5§9¡9×#9Ñ#9×#;Ñ#;Ü�	‰	×ÑÕð $<Ð	r%   T)ÚoffloadÚmodulesrì   c              '   ó
  #   • U(       a�  [        S U 5       5      (       + nU(       a4  U Vs/ s H&  n[        UR                  5       5      R                  PM(     nnO![	        U5      S:X  d   eUS   R                  /nU H  nUR                  U 5        M      Sv •  U(       a'  [        UW5       H  u  pFUR                  U5        M     ggs  snf ! U(       a'  [        UW5       H  u  pFUR                  U5        M     f f = f7f)a  
Context manager that, if offload=True, moves each module to `device` on enter, then moves it back to its original
device on exit.

Args:
    device (`str` or `torch.Device`): Device to move the `modules` to.
    offload (`bool`): Flag to enable offloading.
c              3   óB   #   • U  H  n[        U[        5      v •  M     g 7f©N)r©   r   )Ú.0r®   s     r#   Ú	<genexpr>Ú!offload_models.<locals>.<genexpr>µ  s   é € ÐMÂWÀœ: aÔ):×;Ð;ÂWùs   ‚r   r   N)ÚanyÚnextr«   r*   r/   r-   Úzip)r*   rì   rí   Úis_modelr®   Úoriginal_devicesÚorig_devs          r#   Úoffload_modelsrú   ª  sâ   é € ö ÜÑMÁWÓMÓMÔMˆæÙELÓMÂWÀ¤ Q§\¡\£^Ó 4× ;Ô ;ÁWÐÐMÐä�w“< 1Ó$Ð$Ð$à '¨¡
× 1Ñ 1Ð2ÐãˆAØ�D‰D�ŽLñ ðÛæä" 7Ð,<Ö=‘�Ø—‘�X–ò  >ð ùò  Nøö ä" 7Ð,<Ö=‘�Ø—‘�X–ò  >ð üs(   ‚*D¬-CÁ>DÂC Â4DÃ0D Ä Dc                 ó^  • U (       d  [        S5      eU R                  5       R                  S5      n/ nU H½  n[        R                  " SU5      nU(       d  [        SU S35      e [        UR                  S5      5      n[        UR                  S5      5      nUS::  d  US::  a  [        S	5      eUS
-  S:w  d	  US
-  S:w  a  [        R                  " SU SU S35        UR                  XV45        M¿     U(       d  [        S5      eU$ ! [          a  n[        SU SU 35      UeSnAff = f)zGParses a string defining buckets into a list of (height, width) tuples.zBucket string cannot be empty.Ú;z^\s*(\d+)\s*,\s*(\d+)\s*$zInvalid bucket format: 'z'. Expected 'height,width'.r   r+   r   z,Bucket dimensions must be positive integers.é   zBucket dimension (Ú,z.) not divisible by 8. This might cause issues.z Invalid integer in bucket pair 'z': Nz.No valid buckets found in the provided string.)
rK   ÚstripÚsplitÚreÚmatchÚintÚgroupÚwarningsÚwarnÚappend)Úbuckets_strÚbucket_pairsÚparsed_bucketsÚpair_strr  ÚheightÚwidthÚes           r#   Úparse_buckets_stringr  Ê  s/  € æÜÐ9Ó:Ð:à×$Ñ$Ó&×,Ñ,¨SÓ1€LØ€NÛ ˆÜ—’Ð5°xÓ@ˆÞÜÐ7¸°zÐA\Ð]Ó^Ð^ð		YÜ˜Ÿ™ Q›Ó(ˆFÜ˜Ÿ™ A›Ó'ˆEØ˜‹{˜e q›jÜ Ð!OÓPÐPØ˜‰z˜Q‹ %¨!¡)¨q£.Ü—’Ð 2°6°(¸!¸E¸7ÐBpÐqÔrØ×!Ñ! 6 /Ö2ñ !ö ÜÐIÓJÐJàÐøô ó 	YÜÐ?À¸zÈÈQÈCÐPÓQÐWXÐXûð	Yús   Á'BDÄ
D,ÄD'Ä'D,c                 óˆ   • [        S5      nSn[        U5       H%  u  nu  pg[        X-  X-  -
  5      nXƒ::  d  M!  UnUnM'     U$ )z6Finds the closes bucket to the given height and width.ÚinfN)r.   Ú	enumerateÚabs)	ÚhÚwÚbucket_optionsÚ
min_metricÚbest_bucket_idxÚ
bucket_idxÚbucket_hÚbucket_wÚmetrics	            r#   Úfind_nearest_bucketr  æ  sS   € ä�u“€JØ€OÜ,5°nÖ,EÑ(ˆ
Ñ(�XÜ�Q‘\ A¡LÑ0Ó1ˆØÕØˆJØ(ŠOñ	 -Fð
 Ðr%   ))r   r   )é   é   )r  r  )r+   é   )r   r+   )r   r  )r  r   )é	   é   )r"  r!  )r   r+   )r+   r   c                 ój  • X -  nUb  U VVs/ s H  u  pEXT4PM
     nnnO[         n/ n[        5       nU Hu  u  pšXš-  nX;-  S-  nXK-  n[        U[        XA-  5      U-  5      n[        U[        XQ-  5      U-  5      nXE4U;  d  MQ  UR	                  XE45        UR                  XE45        Mw     U$ s  snnf )aï  Generate a discrete list of ``(height, width)`` buckets for a target pixel budget.

Buckets are sized so that ``height * width`` is close to ``resolution ** 2`` while spanning a range of aspect
ratios, with each dimension rounded to a multiple of ``divisibility``. When ``base_resolutions`` (a list of
``(height, width)`` pairs, e.g. a model's preferred resolutions) is provided, its aspect ratios are used instead of
the default set and rescaled to the target pixel budget.

Args:
    resolution (`int`): Target resolution; the pixel budget is ``resolution ** 2``.
    divisibility (`int`, *optional*, defaults to 16): Each bucket dimension is rounded to a
        multiple of this value (16 satisfies the patch-size constraints of the Flux/Z-Image VAEs).
    base_resolutions (`list[tuple[int, int]]`, *optional*): ``(height, width)`` pairs whose aspect
        ratios seed the ladder instead of the default aspect-ratio set.

Returns:
    `list[tuple[int, int]]`: The unique ``(height, width)`` buckets.
r'   )Ú_DEFAULT_BUCKET_ASPECT_RATIOSÚsetÚmaxÚroundr�   r  )Ú
resolutionÚdivisibilityÚbase_resolutionsÚtarget_pixelsr  r  Úaspect_ratiosÚbucketsÚseenÚrwÚrhÚaspects               r#   Úgenerate_aspect_ratio_bucketsr2    sË   € ð$ Ñ+€MØÑ#Ù.>Ô?Ò.>¡F Q˜!›Ñ.>ˆÑ?ˆä5ˆà€GÜ‹5€DÛ‰ˆØ‘ˆàÑ#¨Ñ+ˆØ‰JˆÜ�œe AÑ$4Ó5¸ÑDÓEˆÜ�œe AÑ$4Ó5¸ÑDÓEˆØˆ6˜ÕØ�H‰H�a�VÔØ�N‰N˜A˜6Ö"ñ  ð €Nùó! @s   �B/c           	      óð   • U R                  5        VVs0 s HS  u  pU[        U[        R                  5      (       a,  UR	                  5       R                  5       R                  5       OU_MU     snn$ s  snnf rð   )rŸ   r©   r   ÚTensorrŽ   ÚcpuÚ
contiguous)Ústate_dictsr¹   rº   s      r#   Ú_to_cpu_contiguousr8  )  sW   € Ø_j×_pÑ_pÔ_rÔsÒ_rÑW[ÐWXˆA´
¸1¼e¿l¹l×0KÑ0Kˆq�x‰x‹z�~‰~Ó×*Ñ*Ô,ÐQRÒRÑ_rÒsÐsùÓss   ”AA2c                 óü   • 0 n[        U R                  SS5      nUc  [        S5      eU R                  R                  nUc  [        R
                  US'   U$ UR                  =(       d    [        R
                  US'   U$ )zL
Extract and convert FSDP config from Accelerator into PyTorch FSDP kwargs.
Úfsdp_pluginNzLAccelerate isn't configured to handle FSDP. Please update your installation.Úsharding_strategy)r�   ÚstaterK   r:  r   Ú
FULL_SHARDr;  )ÚacceleratorÚkwargsÚ
fsdp_stater:  s       r#   Ú get_fsdp_kwargs_from_acceleratorrA  -  s‚   € ð
 €FÜ˜×*Ñ*¨M¸4Ó@€JàÑÜÐgÓhÐhà×#Ñ#×/Ñ/€KàÑä&6×&AÑ&AˆÐ"Ñ#ð
 €Mð '2×&CÑ&C×&bÔGW×GbÑGbˆÐ"Ñ#à€Mr%   Úuse_orig_paramsÚlimit_all_gathersÚfsdp_kwargsÚtransformer_layer_clsc                 óT  • [        [        5      nUcJ  [        U R                  R                  R
                  S   5      nUR                  SUR                   35        [        [        U1S9nUU(       a	  [        US9OSUUUS.n	U(       a  U	R                  U5        [        U 40 U	D6n
U
$ )u)  
Wrap a model with FSDP using common defaults and optional transformer auto-wrapping.

Args:
    model: Model to wrap
    device: Target device (e.g., accelerator.device)
    offload: Whether to enable CPU parameter offloading
    use_orig_params: Whether to use original parameters
    limit_all_gathers: Whether to limit all gathers
    fsdp_kwargs: FSDP arguments (sharding_strategy, etc.) â€” usually from Accelerate config
    transformer_layer_cls: Classes for auto-wrapping (if not using policy from fsdp_kwargs)

Returns:
    FSDP-wrapped model
Nr   z8transformer_layer_cls is not provided, auto-inferred as )rE  )Úoffload_params)Ú	device_idÚcpu_offloadrB  rC  Úauto_wrap_policy)r   Ú__name__Útyper§   Úlanguage_modelÚlayersÚinfor   r
   r   ÚupdateÚFSDP)r§   r*   rì   rB  rC  rD  rE  ÚloggerrJ  rŒ   Ú
fsdp_models              r#   Úwrap_with_fsdprT  D  s«   € ô2 œÓ!€FàÑ$ä $ U§[¡[×%?Ñ%?×%FÑ%FÀqÑ%IÓ JÐØ�‰ÐNÐOd×OmÑOmÐNnÐoÔpô Ô;ÐTiÐSjÑkÐð Þ=D”z°Ò9È$Ø*Ø.Ø,ñ€Fö Ø�‰�kÔ"ä�eÑ&˜vÑ&€JØÐr%   c                   ó<  • \ rS rSrSr         SS\\R                  R                     S\	S\	S\
S\S	\	\
-  S
\	\
-  S\S\S-  S\\\4   S-  4S jjr\SS S jj5       rS rS\
S\	4S jr\R(                  " 5       S\\R                  R                     4S j5       rS\\R                  R                     SS4S jrS!S jrS"S!S jjrS\4S jrS\\R                  R                     SS4S jrS\\R                  R                     SS4S jrS\SS4S jrSrg)#ÚEMAModeliw  z.
Exponential Moving Average of models weights
Nr«   ÚdecayÚ	min_decayÚupdate_after_stepÚuse_ema_warmupÚ	inv_gammaÚpowerÚforeachÚ	model_clsÚmodel_configc                 ó°  • [        U[        R                  R                  5      (       a   Sn[	        SSUSS9  UR                  5       nSnUR                  SS5      b  S	n[	        SSUSS9  US   nUR                  S
S5      b  Sn[	        S
SUSS9  US
   n[        U5      nU Vs/ s H   oÝR                  5       R                  5       PM"     snU l
        UR                  SS5      b   Sn[	        SSUSS9  U R                  US   S9  SU l        X l        X0l        X@l        XPl        X`l        Xpl        SU l        SU l        X€l        X�l        X l        gs  snf )aâ  
Args:
    parameters (Iterable[torch.nn.Parameter]): The parameters to track.
    decay (float): The decay factor for the exponential moving average.
    min_decay (float): The minimum decay factor for the exponential moving average.
    update_after_step (int): The number of steps to wait before starting to update the EMA weights.
    use_ema_warmup (bool): Whether to use EMA warmup.
    inv_gamma (float):
        Inverse multiplicative factor of EMA warmup. Default: 1. Only used if `use_ema_warmup` is True.
    power (float): Exponential factor of EMA warmup. Default: 2/3. Only used if `use_ema_warmup` is True.
    foreach (bool): Use torch._foreach functions for updating shadow parameters. Should be faster.
    device (str | torch.device | None): The device to store the EMA weights on. If None, the EMA
                weights will be stored on CPU.

@crowsonkb's notes on EMA Warmup:
    If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are good values for models you plan
    to train for a million or more steps (reaches decay factor 0.999 at 31.6K steps, 0.9999 at 1M steps),
    gamma=1, power=3/4 for models you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999
    at 215.4k steps).
zzPassing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. Please pass the parameters of the module instead.z9passing a `torch.nn.Module` to `ExponentialMovingAverage`ú1.0.0F©Ústandard_warnTÚ	max_valueNzCThe `max_value` argument is deprecated. Please use `decay` instead.Ú	min_valuezGThe `min_value` argument is deprecated. Please use `min_decay` instead.r*   z=The `device` argument is deprecated. Please use `to` instead.r)   r   )r©   r   rÒ   ÚModuler   r«   Úgetrª   ÚclonerŽ   Úshadow_paramsr-   Útemp_stored_paramsrW  rX  rY  rZ  r[  r\  Úoptimization_stepÚcur_decay_valuer]  r^  r_  )Úselfr«   rW  rX  rY  rZ  r[  r\  r]  r^  r_  r?  Údeprecation_messageÚps                 r#   Ú__init__ÚEMAModel.__init__|  sg  € ôF �j¤%§(¡(§/¡/×2Ñ2ðDð  ô ØKØØ#Ø#ò	ð $×.Ñ.Ó0ˆJð "ˆNà�:‰:�k 4Ó(Ñ4Ø"gÐÜ�k 7Ð,?ÈuÒUØ˜;Ñ'ˆEà�:‰:�k 4Ó(Ñ4Ø"kÐÜ�k 7Ð,?ÈuÒUØ˜{Ñ+ˆIä˜*Ó%ˆ
Ù:DÓEº*°QŸg™g›i×.Ñ.Ö0¹*ÑEˆÔà�:‰:�h Ó%Ñ1Ø"aÐÜ�h Ð)<ÈEÒRØ�G‰G˜6 (Ñ+ˆGÑ,à"&ˆÔàŒ
Ø"ŒØ!2ÔØ,ÔØ"ŒØŒ
Ø!"ˆÔØ#ˆÔØŒà"ŒØ(Õùò) Fs   Â%'ErA   c                 ó®   • UR                  USS9u  pEUR                  U5      nU " UR                  5       X&R                  US9nUR	                  U5        U$ )NT)Úreturn_unused_kwargs)r^  r_  r]  )Úfrom_configÚfrom_pretrainedr«   rŒ   Úload_state_dict)ÚclsÚpathr^  r]  Ú_Ú
ema_kwargsr§   Ú	ema_models           r#   ru  ÚEMAModel.from_pretrainedÐ  sY   € à!×-Ñ-¨dÈÐ-ÐN‰ˆØ×)Ñ)¨$Ó/ˆá˜×(Ñ(Ó*°iÏlÉlÐdkÑlˆ	à×!Ñ! *Ô-ØÐr%   c                 óv  • U R                   c  [        S5      eU R                  c  [        S5      eU R                   R                  U R                  5      nU R	                  5       nUR                  SS 5        UR                  " S0 UD6  U R                  UR                  5       5        UR                  U5        g )NzJ`save_pretrained` can only be used if `model_cls` was defined at __init__.zM`save_pretrained` can only be used if `model_config` was defined at __init__.ri  rH   )
r^  rK   r_  rt  rž   ÚpopÚregister_to_configÚcopy_tor«   Úsave_pretrained)rm  rx  r§   rž   s       r#   r�  ÚEMAModel.save_pretrainedÚ  s˜   € Ø�>‰>Ñ!ÜÐiÓjÐjà×ÑÑ$ÜÐlÓmÐmà—‘×*Ñ*¨4×+<Ñ+<Ó=ˆØ—_‘_Ó&ˆ
Ø�‰�¨Ô-à× Ò Ñ. :Ò.Ø�‰�U×%Ñ%Ó'Ô(Ø×Ñ˜dÕ#r%   rk  c                 ó  • [        SXR                  -
  S-
  5      nUS::  a  gU R                  (       a#  SSX R                  -  -   U R                  * -  -
  nOSU-   SU-   -  n[        X0R                  5      n[        X0R                  5      nU$ )z>
Compute the decay factor for the exponential moving average.
r   r   r:   é
   )r&  rY  rZ  r[  r\  ÚminrW  rX  )rm  rk  Ústeprl  s       r#   Ú	get_decayÚEMAModel.get_decayé  s‡   € ô �1Ð'×*@Ñ*@Ñ@À1ÑDÓEˆà�1‹9Øà××Ø 1 t¯n©nÑ'<Ñ#<À$Ç*Á*ÀÑ"LÑL‰Oà  4™x¨B°©IÑ6ˆOä˜o¯z©zÓ:ˆä˜o¯~©~Ó>ˆØÐr%   c           	      óT  • [        U[        R                  R                  5      (       a  Sn[	        SSUSS9  UR                  5       n[        U5      nU =R                  S-  sl        U R                  U R                  5      nX0l	        SU-
  n[        R                  " 5       nU R                  (       Ga~  [        5       (       aK  [        R                  R                   R#                  5       (       a  [         R$                  R'                  US S9nU   U Vs/ s H  ofR(                  (       d  M  UPM     nn[+        U R,                  U5       VVs/ s H  u  p†UR(                  (       d  M  UPM     n	nn[/        U5      [/        U5      :  au  [        R0                  " [+        U R,                  U5       VVs/ s H  u  p†UR(                  (       a  M  UPM     snnU Vs/ s H  ofR(                  (       a  M  UPM     snSS	9  [        R2                  " U	[        R4                  " X—5      US
9  S S S 5        g [+        U R,                  U5       H£  u  p†[        5       (       aK  [        R                  R                   R#                  5       (       a  [         R$                  R'                  US S9nU   UR(                  (       a  UR7                  XHU-
  -  5        OUR9                  U5        S S S 5        M¥     g s  snf s  snnf s  snnf s  snf ! , (       d  f       g = f! , (       d  f       MÞ  = f)NzPassing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. Please pass the parameters of the module instead.z>passing a `torch.nn.Module` to `ExponentialMovingAverage.step`ra  Frb  r   )Úmodifier_rankT)Únon_blocking)r6   )r©   r   rÒ   rf  r   r«   rª   rk  r‡  rl  Ú
contextlibÚnullcontextr]  r   ÚtransformersÚintegrationsÚ	deepspeedÚis_deepspeed_zero3_enabledÚzeroÚGatheredParametersr¬   rö   ri  r/   Ú_foreach_copy_Ú_foreach_sub_Ú_foreach_subÚsub_Úcopy_)
rm  r«   rn  rW  Úone_minus_decayÚcontext_managerr¯   Úparams_gradÚs_paramÚs_params_grads
             r#   r†  ÚEMAModel.stepü  so  € ä�j¤%§(¡(§/¡/×2Ñ2ðDð  ô ØPØØ#Ø#ò	ð $×.Ñ.Ó0ˆJä˜*Ó%ˆ
à×Ò !Ñ#Õð —‘˜t×5Ñ5Ó6ˆØ$ÔØ˜e™)ˆä$×0Ò0Ó2ˆà�<�<ˆ<Ü(×*Ñ*¬|×/HÑ/H×/RÑ/R×/mÑ/m×/oÑ/oÜ"+§.¡.×"CÑ"CÀJÐ^bÐ"CÐ"c�â Ù2<ÓT²*¨×@SÕ@SŸu±*�ÐTä25°d×6HÑ6HÈ*Ô2Uô!Ú2U¡ ÐY^×YlÕYl—GÑ2Uð ñ !ô �{Ó#¤c¨*£oÓ5Ü×(Ò(Ü7:¸4×;MÑ;MÈzÔ7ZÔvÒ7Z¡^ WÐbg×buÕbuŸÑ7ZÒvÙ,6ÓRªJ 5×>QÕ>QŸ©JÑRØ%)òô ×#Ò#Ø!¤5×#5Ò#5°mÓ#QÐYhò÷ !�ô$ #& d×&8Ñ&8¸*Ö"E‘�Ü,×.Ñ.´<×3LÑ3L×3VÑ3V×3qÑ3q×3sÑ3sÜ&/§n¡n×&GÑ&GÈÐ]aÐ&GÐ&b�Oâ$Ø×*×*ØŸ™ _À%¹Ñ%HÕIàŸ™ eÔ,÷	 %‘_ò	 #Fùò# Uùó!ùó wùÚR÷ !•ú÷, %–_úsg   ÄLÄK1Ä.K1Ä4LÅK6Å*K6Å0ALÆ4K<ÇK<ÇLÇLÇ4LÇ:0LÊ*:LË1LÌ
LÌ
L'	c           
      ó  • [        U5      nU R                  (       a~  [        R                  " U Vs/ s H  o"R                  PM     sn[        U R                  U5       VVs/ s H*  u  p2UR                  UR                  5      R                  PM,     snn5        g[        U R                  U5       HC  u  p2UR                  R                  UR                  UR                  5      R                  5        ME     gs  snf s  snnf )a1  
Copy current averaged parameters into given collection of parameters.

Args:
    parameters: Iterable of `torch.nn.Parameter`; the parameters to be
        updated with the stored moving averages. If `None`, the parameters with which this
        `ExponentialMovingAverage` was initialized will be used.
N)
rª   r]  r   r”  r­   rö   ri  r-   r*   r˜  )rm  r«   r¯   rœ  s       r#   r€  ÚEMAModel.copy_to6  s·   € ô ˜*Ó%ˆ
Ø�<�<Ü× Ò Ù)3Ó4ª —”©Ñ4ÜEHÈ×I[ÑI[Ð]gÔEhÔiÒEh±>°7�—‘˜EŸL™LÓ)×.Ô.ÑEhÒiõô
 #& d×&8Ñ&8¸*Ö"E‘�Ø—
‘
× Ñ  §¡¨E¯L©LÓ!9×!>Ñ!>Ö?ò #Fùò	 5ùÛis   ±C9Á!1C>c                 ól   • U R                    Vs/ s H  oR                  5       PM     snU l         gs  snf )z’
Move internal buffers of the ExponentialMovingAverage to pinned memory. Useful for non-blocking transfers for
offloading EMA params to the host.
N)ri  Ú
pin_memory)rm  ro  s     r#   r¢  ÚEMAModel.pin_memoryI  s*   € ð 7;×6HÒ6HÓIÒ6H°Ÿl™lžnÑ6HÑIˆÕùÒIs   �1c           	      ó¶   • U R                    Vs/ s H7  nUR                  5       (       a  UR                  XUS9OUR                  XS9PM9     snU l         gs  snf )zƒ
Move internal buffers of the ExponentialMovingAverage to `device`.

Args:
    device: like `device` argument to `torch.Tensor.to`
)r*   rE   r‹  )r*   r‹  N)ri  Úis_floating_pointr-   )rm  r*   rE   r‹  ro  s        r#   r-   ÚEMAModel.toQ  se   € ð ×'Ò'ó	
ò (�ð ×"Ñ"×$Ñ$ð �D‰D˜¸,ˆDÑGà—‘˜V�Ð?ò@ñ (ñ	
ˆÕùò 
s   �>Ac           	      ó¸   • U R                   U R                  U R                  U R                  U R                  U R
                  U R                  U R                  S.$ )z‘
Returns the state of the ExponentialMovingAverage as a dict. This method is used by accelerate during
checkpointing to save the ema state dict.
©rW  rX  rk  rY  rZ  r[  r\  ri  r¨  )rm  s    r#   rž   ÚEMAModel.state_dict`  sN   € ð —Z‘ZØŸ™Ø!%×!7Ñ!7Ø!%×!7Ñ!7Ø"×1Ñ1ØŸ™Ø—Z‘ZØ!×/Ñ/ñ	
ð 		
r%   c                 ó�   • U Vs/ s H.  o"R                  5       R                  5       R                  5       PM0     snU l        gs  snf )z•
Saves the current parameters for restoring later.

Args:
    parameters: Iterable of `torch.nn.Parameter`. The parameters to be temporarily stored.
N)rŽ   r5  rh  rj  )rm  r«   r¯   s      r#   ÚstoreÚEMAModel.stores  s6   € ñ NXÓ"XÊZÀE§<¡<£>×#5Ñ#5Ó#7×#=Ñ#=Ö#?ÉZÑ"XˆÕùÒ"Xs   …5Ac                 ó¬  • U R                   c  [        S5      eU R                  (       aV  [        R                  " U Vs/ s H  o"R
                  PM     snU R                    Vs/ s H  o3R
                  PM     sn5        OD[        U R                   U5       H*  u  p2UR
                  R                  UR
                  5        M,     SU l         gs  snf s  snf )a  
Restore the parameters stored with the `store` method. Useful to validate the model with EMA parameters
without: affecting the original optimization process. Store the parameters before the `copy_to()` method. After
validation (or model saving), use this to restore the former parameters.

Args:
    parameters: Iterable of `torch.nn.Parameter`; the parameters to be
        updated with the stored parameters. If `None`, the parameters with which this
        `ExponentialMovingAverage` was initialized will be used.
NzGThis ExponentialMovingAverage has no `store()`ed weights to `restore()`)rj  ÚRuntimeErrorr]  r   r”  r­   rö   r˜  )rm  r«   r¯   Úc_params       r#   ÚrestoreÚEMAModel.restore|  s¥   € ð ×"Ñ"Ñ*ÜÐhÓiÐiØ�<�<Ü× Ò Ù)3Ó4ª —”©Ñ4ÐSW×SjÒSjÓ6kÒSjÈ·|´|ÑSjÑ6kõô #& d×&=Ñ&=¸zÖ"J‘�Ø—
‘
× Ñ  §¡Ö.ñ #Kð #'ˆÕùò 5ùÒ6ks   ¾CÁ#C
rž   c                 óH  • [         R                  " U5      nUR                  SU R                  5      U l        U R                  S:  d  U R                  S:”  a  [	        S5      eUR                  SU R
                  5      U l        [        U R
                  [        5      (       d  [	        S5      eUR                  SU R                  5      U l        [        U R                  [        5      (       d  [	        S5      eUR                  S	U R                  5      U l
        [        U R                  [        5      (       d  [	        S
5      eUR                  SU R                  5      U l        [        U R                  [        5      (       d  [	        S5      eUR                  SU R                  5      U l        [        U R                  [        [        45      (       d  [	        S5      eUR                  SU R                  5      U l        [        U R                  [        [        45      (       d  [	        S5      eUR                  SS5      nUb]  X l        [        U R                  [         5      (       d  [	        S5      e[#        S U R                   5       5      (       d  [	        S5      egg)zï
Loads the ExponentialMovingAverage state. This method is used by accelerate during checkpointing to save the
ema state dict.

Args:
    state_dict (dict): EMA state. Should be an object returned
        from a call to :meth:`state_dict`.
rW  r:   r(   zDecay must be between 0 and 1rX  zInvalid min_decayrk  zInvalid optimization_steprY  zInvalid update_after_steprZ  zInvalid use_ema_warmupr[  zInvalid inv_gammar\  zInvalid powerri  Nzshadow_params must be a listc              3   óV   #   • U  H  n[        U[        R                  5      v •  M!     g 7frð   )r©   r   r4  )rñ   ro  s     r#   rò   Ú+EMAModel.load_state_dict.<locals>.<genexpr>Â  s    é € ÐOÒ<N°q”z !¤U§\¡\×2Ð2Ò<Nùs   ‚')z!shadow_params must all be Tensors)ÚcopyÚdeepcopyrg  rW  rK   rX  r©   r.   rk  r  rY  rZ  Úboolr[  r\  ri  rª   Úall)rm  rž   ri  s      r#   rv  ÚEMAModel.load_state_dict•  sÿ  € ô —]’] :Ó.ˆ
à—^‘^ G¨T¯Z©ZÓ8ˆŒ
Ø�:‰:˜Ó˜tŸz™z¨CÓ/ÜÐ<Ó=Ð=à#Ÿ™¨°T·^±^ÓDˆŒÜ˜$Ÿ.™.¬%×0Ñ0ÜÐ0Ó1Ð1à!+§¡Ð0CÀT×E[ÑE[Ó!\ˆÔÜ˜$×0Ñ0´#×6Ñ6ÜÐ8Ó9Ð9à!+§¡Ð0CÀT×E[ÑE[Ó!\ˆÔÜ˜$×0Ñ0´#×6Ñ6ÜÐ8Ó9Ð9à(Ÿn™nÐ-=¸t×?RÑ?RÓSˆÔÜ˜$×-Ñ-¬t×4Ñ4ÜÐ5Ó6Ð6à#Ÿ™¨°T·^±^ÓDˆŒÜ˜$Ÿ.™.¬5´#¨,×7Ñ7ÜÐ0Ó1Ð1à—^‘^ G¨T¯Z©ZÓ8ˆŒ
Ü˜$Ÿ*™*¤u¬c l×3Ñ3Ü˜_Ó-Ð-à"Ÿ™ ¸Ó=ˆØÑ$Ø!.ÔÜ˜d×0Ñ0´$×7Ñ7Ü Ð!?Ó@Ð@ÜÑO¸D×<NÒ<NÓO×OÑOÜ Ð!DÓEÐEð Pð	 %r%   )rl  rW  r]  r[  rX  r^  r_  rk  r\  ri  rj  rY  rZ  )	g§èH.ÿï?r:   r   Fr(   gUUUUUUå?FNN)F)rA   rV  )rA   N)NNF)rK  Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   r   rÒ   Ú	Parameterr.   r  r·  r   ÚdictÚstrrp  Úclassmethodru  r�  r‡  rV   r†  r€  r¢  r-   rž   r«  r°  rv  Ú__static_attributes__rH   r%   r#   rV  rV  w  sµ  † ñð ØØ!"Ø$Ø!$Ø"ØØ $Ø.2ñR)à˜UŸX™X×/Ñ/Ñ0ðR)ð ðR)ð ð	R)ð
 ðR)ð ðR)ð ˜3‘;ðR)ð �s‰{ðR)ð ðR)ð ˜‘:ðR)ð ˜3 ˜8‘n tÑ+õR)ðh õó ðò$ð¨3ð °5ô ð& ‡]‚]ƒ_ð7-˜x¨¯©×(:Ñ(:Ñ;ó 7-ó ð7-ðr@ (¨5¯8©8×+=Ñ+=Ñ">ð @À4ô @ô&Jö
ð
˜Dô 
ð&Y ¨¯©×);Ñ);Ñ <ð YÀô Yð' (¨5¯8©8×+=Ñ+=Ñ">ð 'À4ô 'ð2.F¨$ð .F°4÷ .Fr%   rV  )r(   )NNNr5  Nrð   )r"  N)TTTNN)ZrŒ  rµ  rä   r×   r   r  r  r   Ú	functoolsr   Útypingr   r   Únumpyr   r   Útorch.nn.functionalrÒ   rÓ   rO   Údistributedræ   Útorch.distributed.fsdpr   r   r	   rQ  Útorch.distributed.fsdp.wrapr
   Úmodelsr   Ú	pipelinesr   Ú
schedulersr   Úutilsr   r   r   r   r   r   r   r   rŽ  r�  r�  r‘  Úaccelerate.loggingr   Úpeftr   Útorchvisionr   rê   r  r$   r9   r4  r.   rL   rm   rÀ  r�   r—   r¿  r¦   Úfloat32rf  rª   r°   r¼   rÄ   r*   Ú	GeneratorrÚ   rá   rë   r·  rú   r  r  r$  r2  r8  rA  r%  rL  rT  rV  rH   r%   r#   Ú<module>rÓ     sZ  ðÛ Û Û 	Û Û Û 	Û Ý %Ý ß  ã Û ß Ð ð 	×Ñ×!Ñ!×#Ñ#ßCÝGÞHà€JØÐØ€DØ#'Ð å (Ý (Ý &÷	÷ 	ó 	ñ ×ÑÛà× Ñ ×*Ñ*×EÑE×GÑGÛá×ÑÝ-á×ÑÝ.á×ÑÝ&á×ÑÛð)�3ô )ò("ðR ØØ-1ØòS%Ø�L‰LðS%à�L‰LðS%ð ð	S%ð
 ðS%ð —|‘| dÑ*ðS%ð ðS%ð ˆ5�<‰<˜Ÿ™ u§|¡|Ð3Ñ4õS%ðl)°3ô )ðh (+ñ3#Ø
ð3#à#ð3#ð �|‰|ð3#ð �<‰<ð	3#ð
 —<‘<ð3#ð �L‰Lð3#ð !Ÿ<™<ð3#ð  %ð3#ð ˆ5�<‰<˜Ÿ™Ð%Ñ&õ3#ðlÐ3ð ¸¸SÀ%Ç,Á,Ð=NÑ8Oô ð& PUÏ}É}ñ - §¡§¡°$°u·x±x·±Ñ2GÑ Gõ -ð"]Ø˜#˜uŸ|™|Ð+Ñ,ð]Ø69ð]ØINÏÉÏÉô]ð&¨D°°e·h±h·o±oÐ1EÑ,Fð È4ÐPSÐUXÐPXÉ>ô ð ØØØ!&Ø(,ñØðàðð ðð ð	ð
 ðð �L‰L˜3Ñðð �‰ Ñ%õñ6°Sõ ò$ ð  Ønrò ˜UŸX™XŸ_™_Ð/@Ñ@ð È#ÐPU×P\ÑP\ÑJ\ð Ðgkô ó ðò>ò8	ò!Ð ô$ðNt tô tð°Tô ð4 Ø Ø"Ø)-Ø?Cñ/Ø�8‰8�?‰?ð/à�%—,‘,Ñð/ð ð/ð ð	/ð
 ð/ð �c˜3�h‘ $Ñ&ð/ð ˜t E§H¡H§O¡OÑ4Ñ5¸Ñ<ð/ð 
õ/÷fLFò LFr%   