+
    Lj                        ^ RI t ^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RI Ht ^ RIH	t	 ^ RI
HtHt ^ RIt^ RIt^ RIHu Ht ]P(                  P+                  4       '       d   ^ RIHtHt ^ RIHt ^ RIHt MRtRtRtRt^RIHt ^R	IH t  ^R
I!H"t" ^RI#H$t$H%t%H&t&H't'H(t(H)t)H*t*H+t+ ]+! 4       '       d3   ^ RI,t,],PZ                  P\                  P_                  4       '       d   ^ RI.t.]'! 4       '       d   ^ RI0H1t1 ](! 4       '       d   ^ RI2H3t3 ]*! 4       '       d   ^ RI4H5t5 ])! 4       '       d   ^ RI6t6R R lt7R t8RRRRRRRR9/R R llt9R R lt:R:R R llt;R R lt<]Pz                  3R  R! llt>R" R# lt?R$ R% lt@R;R& R' lltAR<R( R) lltBR* tC]R+R,/R- R. ll4       tDR/ tER0 tFR1 R2 ltGR3 R4 ltHR=R5 R6 lltI ! R7 R84      tJR# )>    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)
transformsc                $    V ^8  d   QhR\         /# )   seed)int)formats   "D/app/.local/lib/python3.14/site-packages/diffusers/training_utils.py__annotate__r   =   s     ) )3 )    c                <   \         P                  ! V 4       \        P                   P                  V 4       \        P                  ! V 4       \        4       '       d"   \        P                  P                  V 4       R# \        P                  P                  V 4       R# )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   &r   set_seedr)   =   s[     KKIINN4	d		!!$'

""4(r    c                ~   V P                   pVR,          pRV,
          R,          pVP                  VP                  R7      V,          P                  4       p\	        VP
                  4      \	        VP
                  4      8  d   VR,          pK8  VP                  VP
                  4      pVP                  VP                  R7      V,          P                  4       p\	        VP
                  4      \	        VP
                  4      8  d   VR,          pK8  VP                  VP
                  4      pWV,          ^,          pV# )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_snrr<   Q   s     %33N(#-%(>%9c$A! .00	8H8H0I)TZZ\
!''
(3y+?
?1)<&&y7E$A$D$DIL\L\$D$]^g$h$n$n$p!
+11
2S5I
I(Ei(P%)00AE =Q
CJr    lambda_conf        temperaturer,   per_token_weightsignore_indexc                   V ^8  d   QhR\         P                  R\         P                  R\        R\        R\         P                  R,          R\        R\        \         P                  \         P                  \         P                  3,          /# )	r   logitslabelsr=   r?   r@   NrA   return)r$   Tensorr1   r   tuple)r   s   "r   r   r   v   s     S% S%LLS%LLS% 	S%
 S% ||d*S% S% 5<<u||34S%r    c               *   V P                   ^8  d#   \        R\        V P                  4       R24      hVP                  V P                  RR 8w  d9   \        R\        VP                  4       R\        V P                  4       R24      hV^ 8:  d   \        RV R24      hVP	                  V4      pVf#   \
        P                  ! WP                  R7      pMoVP                  VP                  8w  d9   \        R\        VP                  4       R	\        VP                  4       R24      hVP                  V P                  R7      pV P                  R,          p\        P                  ! V P                  RV4      VP                  R4      R
VR7      P                  V4      p	WvP                  VP                  4      ,          P                  4       P                  ^4      p
W,          VP                  V	P                  4      ,          P                  4       V
,          pVR8X  d2   \
        P                  ! RV P                   VP                  R7      pWV3# \
        P"                  ! 4       ;_uu_ 4        V P%                  RR7      pWmP'                  V4      ,          pRRR4       V P)                  4       pVR8w  d   V\)        V4      ,          p\
        P*                  ! VRR7      p\
        P,                  ! VP                  4      P.                  p\
        P0                  ! VP                  V4      4      pVV,          P                  RR7      P                  V P                  R7      ) pVXP                  VP                  4      ,          P                  4       P                  ^4      pVV,          VP                  VP                  4      ,          P                  4       V,          pV\)        V4      V,          ,           pVW3#   + '       g   i     ELo; i)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)`.
z.`logits` must have at least 2 dims, got shape .Nz:`labels` shape must match `logits.shape[:-1]`, got labels=z logits=z`temperature` must be > 0, got )dtypez9`per_token_weights` shape must match `labels` shape, got z != none)	reductionrA   r>   )r.   rJ   )dimr,    )ndim
ValueErrorrG   r3   ner$   	ones_likerJ   r0   Fcross_entropyreshape
reshape_assum	clamp_minzerosr.   no_gradargmaxeqr1   softmaxfinfotinylog)rC   rD   r=   r?   r@   rA   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_lossrr   v   sU   < {{QI%PVP\P\J]I^^_`aa||v||CR((Hv||I\H]]efklrlxlxfyezz{|
 	
 a:;-qIJJIIl#E //&=""fll2KERcRiRiLjKkkopuv|  wC  wC  qD  pE  EF  G  $&&V\\&: b!JOOr:&r!	
 j  88GMM22779CCAFI'%((=3F3F*GGLLNQZZH cKK6==O	9,,	}}}$''&/) 
 LLNMc%k(::MM-R0E
++ekk
"
'
'C		%//#./I	!&&2&.111EEGGJJw}}55::<FFqIJ7"WZZ%>>CCE
RIeK(944D$$# 
s   1*PP	c                $    V ^8  d   QhR\         /# )r   interpolation_typestr)r   s   "r   r   r      s     ) )3 )r    c                @   \        4       '       g   \        R4      hV R8X  d   \        P                  P                  pV# V R8X  d   \        P                  P
                  pV# V R8X  d   \        P                  P                  pV# V R8X  d   \        P                  P                  pV# V R8X  d   \        P                  P                  pV# V R8X  d   \        P                  P                  pV# V R8X  d   \        P                  P                  pV# \        R	V  R
24      h)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LANCZOSrQ   )rt   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    c                2   V ^8  d   QhR\         R\        R\        P                  R\        P                  R\        P                  R\        P                  R\        P                  R\        R	\
        \        P                  \        P                  3,          /	# )
r   unetr5   r6   noisenoisy_latentstargetencoder_hidden_statesdream_detail_preservationrE   )r   r   r$   rF   r1   rG   )r   s   "r   r   r      s     3# 3#
3##3# ||3# <<	3#
 <<3# LL3# !<<3#  %3# 5<<%&3#r    c                   VP                   P                  VP                  4      VRRR3,          pRV,
          R,          p	W,          p
Rp\        P                  ! 4       ;_uu_ 4        V ! WBV4      P
                  pRRR4       RRrVP                  P                  R8X  dU   TpW>,
          P                  4       pVP                  V
4       VP                  W,          4      pVP                  V4      pW3# VP                  P                  R8X  d   \        R4      h\        RVP                  P                   24      h  + '       g   i     L; i)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+   epsilonv_predictionz/DREAM has not been implemented for v-predictionzUnknown prediction type )r/   r0   r.   r$   r[   sampleconfigprediction_typedetachmul_addNotImplementedErrorrQ   )r   r5   r6   r   r   r   r   r   r/   r8   dream_lambdari   _noisy_latents_targetpredicted_noisedelta_noises   &&&&&&&&        r    compute_dream_and_update_latentsr      s+   : %3366y7G7GHTXZ^`dIdeN%(>%9c$A! 1KLD	M.CDKK 
  $TG--:.668&&**+H+VW**[) "" 
			/	/>	A!"STT3O4J4J4Z4Z3[\]] 
s   (D>>E	c                f    V ^8  d   QhR\         R\        \        \        P                  3,          /# )r   r   rE   )r   dictrv   r$   rF   )r   s   "r   r   r   .  s)      3 S%,,=N8O r    c                    / pV P                  4        F]  w  r#\        VR4      '       g   K  \        VR4      pVf   K+  VP                  4       pVP	                  4        F  w  rgWqV RV 2&   K  	  K_  	  V# )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+,, 6J%(2(=(=(?%:O:U:U:W6*OYtfF3I2J$KL ;X - r    c                    V ^8  d   QhR\         P                  P                  \        \         P                  P                  ,          ,          /# )r   model)r$   nnModulelist)r   s   "r   r   r   A  s-     - -$uxx2G G -r    c                    \        V \        4      '       g   V .p V  FD  pVP                  4        F-  pVP                  '       g   K  VP	                  V4      Vn        K/  	  KF  	  R# )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)
isinstancer   
parametersrequires_gradr0   data)r   rJ   mparams   &&  r   cast_training_paramsr   A  sM     eT""\\^E""""XXe_
 $ r    c                    V ^8  d   QhR\         \        \        P                  3,          R\        R\        P                  P
                  /# )r   r   prefixtext_encoder)r   rv   r$   rF   r   r   )r   s   "r   r   r   R  s?     ] ]#u||+,]69]IN]r    c                    V P                  4        UUu/ uF2  w  r4VP                  V4      '       g   K  VP                  VR4       VbK4  	  ppp\        \	        V4      4      p\        W%RR7       R# u uppi )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2G2G2I2I$!Q\\Z`Ma%199VR 
!A%2I   99XYp9qrlR[\	s
   A2A2c                    V ^8  d   QhR\         \        \        P                  P                  3,          R\         \        \
        3,          /# )r   modules_to_saverE   )r   rv   r$   r   r   r   )r   s   "r   r   r   e  s7      Dehhoo1E,F 4PSUXPX> r    c                     / pV P                  4        F1  w  r#Vf   K  VP                  R,          P                  4       W R2&   K3  	  V# )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@RS\@]@e@e@gI%;<=  7 r    c                    V ^8  d   QhR\         R\        R\        R\        R\        R\        P                  \         ,          R\        P
                  R,          /# )	r   weighting_scheme
batch_size
logit_mean	logit_std
mode_scaler.   	generatorN)rv   r   r1   r$   r.   	Generator)r   s   "r   r   r   m  s`        	
  LL3 %r    c                   V R8X  dF   \         P                  ! W#V3WVR7      p\         P                  P                  P	                  V4      pV# V R8X  dx   \         P
                  ! V3WVR7      p^V,
          V\         P                  ! \        P                  V,          ^,          4      ^,          ^,
          V,           ,          ,
          pV# \         P
                  ! V3WVR7      pV# )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$   normalr   
functionalsigmoidrandcosmathpi)r   r   r   r   r   r.   r   us   &&&&&&& r   %compute_density_for_timestep_samplingr   m  s      >)LLjzmTZpHH''* H 
V	#JJZM&NEJ%))DGGaK!O"<"AA"E"IJJ H JJZM&NHr    c                $    V ^8  d   QhR\         /# )r   r   ru   )r   s   "r   r   r     s      S r    c                
   V R8X  d   VR,          P                  4       pV# V R8X  dF   ^^V,          ,
          ^V^,          ,          ,           p^\        P                  V,          ,          pV# \        P                  ! V4      pV# )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_sqrtcosmapg       )r1   r   r   r$   rS   )r   sigmas	weightingbots   &&  r   compute_loss_weighting_for_sd3r     sz     <'T\((*	  
X	%!f*nq619},3'	  OOF+	r    c                 l   \         P                  ! 4        \        P                  P	                  4       '       d!   \        P                  P                  4        R# \        P                  P                  P	                  4       '       d!   \        P                  P                  4        R# \        4       '       d!   \        P                  P                  4        R# \        \        R4      '       dG   \        P                  P	                  4       '       d!   \        P                  P                  4        R# R# R# )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   rO   r    r   free_memoryr     s     JJLzz  

 				(	(	*	*				!	!!!#			599#9#9#;#;		 $<	r    offloadTc                    V ^8  d   QhR\         P                  P                  \        ,          R\        \         P
                  ,          R\        /# )r   modulesr.   r   )r$   r   r   r   rv   r.   bool)r   s   "r   r   r     s<      UXX__/@@ #PUP\P\J\ gk r    c              '  b  "   V'       d   \         ;QJ d    R V 4       F  '       g   K   RM	  RM! R V 4       4      '       * pV'       d4   V Uu. uF&  p\        VP                  4       4      P                  NK(  	  ppM&\	        V4      ^8X  g   Q hV^ ,          P                  .pV F  pVP                  V 4       K  	   Rx  V'       d)   \        VX4       F  w  rFVP                  V4       K  	  R# R# u upi   T'       d(   \        TX4       F  w  rFTP                  T4       K  	  i i ; i5i)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   "   T F  p\        V\        4      x  K  	  R # 5iN)r   r   ).0r   s   & r   	<genexpr>!offload_models.<locals>.<genexpr>  s     MW:a):;;Ws   TFN)anynextr   r.   r2   r0   zip)r.   r   r   is_modelr   original_devicesorig_devs   $$*    r   offload_modelsr    s      sMWMsssMWMMMELMWQ\\^ 4 ; ;WMw<1$$$ '
 1 12ADDL "7,<=X  >   N "7,<=X  > s:   D/D/!D/D/,C6<AD/ C; 7D/;1D,,D/c                ~   V '       g   \        R4      hV P                  4       P                  R4      p. pV F  p\        P                  ! RV4      pV'       g   \        RV R24      h \        VP                  ^4      4      p\        VP                  ^4      4      pV^ 8:  g   V^ 8:  d   \        R4      hV^,          ^ 8w  g   V^,          ^ 8w  d   \        P                  ! RV RV R	24       VP                  WV34       K  	  V'       g   \        R4      hV#   \          d   p\        R
T RT 24      ThRp?ii ; i)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'.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.)
rQ   stripsplitrematchr   groupwarningswarnappend)buckets_strbucket_pairsparsed_bucketspair_strr  heightwidthes   &       r   parse_buckets_stringr!    s/   9::$$&,,S1LN 5x@7zA\]^^		YQ(FA'E{eqj !OPPzQ%!)q. 26(!E7Bpqr!!6/2 ! IJJ  	Y?zQCPQWXX	Ys   )BDD<%D77D<c                    \        R4      pRp\        V4       F2  w  pw  rg\        W,          W,          ,
          4      pW8:  g   K.  TpTpK4  	  V# )z6Finds the closes bucket to the given height and width.infN)r1   	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,5n,E(
(XQ\AL01J(O	 -F
 r    c                $    V ^8  d   QhR\         /# r   rE   r   )r   s   "r   r   r     s     t tt tr    c           	          V P                  4        UUu/ uFT  w  rT\        V\        P                  4      '       d-   VP	                  4       P                  4       P                  4       MTbKV  	  upp# u uppi r  )r   r   r$   rF   r   cpu
contiguous)state_dictsr   r   s   &  r   _to_cpu_contiguousr7    sW    _j_p_p_rs_rW[WXA
1ell0K0Kqxxz~~**,QRR_rssss   AA2c                $    V ^8  d   QhR\         /# r1  r2  )r   s   "r   r   r     s      T r    c                   / p\        V P                  RR4      pVf   \        R4      hV P                  P                  pVf   \        P
                  VR&   V# VP                  ;'       g    \        P
                  VR&   V# )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   staterQ   r:  r   
FULL_SHARDr;  )acceleratorkwargs
fsdp_stater:  s   &   r    get_fsdp_kwargs_from_acceleratorrA    s    
 F**M4@Jghh##//K&6&A&A"#
 M '2&C&C&b&bGWGbGb"#Mr    c                \   V ^8  d   QhR\         P                  P                  R\        \         P                  ,          R\
        R\
        R\
        R\        \        \        3,          R,          R\        \        \         P                  P                  ,          ,          R,          R	\        /# )
r   r   r.   r   use_orig_paramslimit_all_gathersfsdp_kwargsNtransformer_layer_clsrE   )r$   r   r   rv   r.   r  r   r   settypeFSDP)r   s   "r   r   r     s     / /88??/%,,/ / 	/
 / c3h$&/ tEHHOO45</ 
/r    c           
     v   \        \        4      pVfO   \        V P                  P                  P
                  ^ ,          4      pVP                  RVP                   24       \        \        V0R7      pRTRV'       d   \        VR7      MRRVRVR	V/p	V'       d   V	P                  V4       \        V 3/ V	B p
V
# )
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
Nz8transformer_layer_cls is not provided, auto-inferred as )rF  	device_idcpu_offload)offload_paramsrC  rD  auto_wrap_policy)r   __name__rH  r   language_modellayersinfor   r
   r   updaterI  )r   r.   r   rC  rD  rE  rF  loggerrN  r   
fsdp_models   &&&&&&&    r   wrap_with_fsdprV    s    2 !F$ $U[[%?%?%F%Fq%I JNOdOmOmNnop ;TiSjk 	VWz9$?.,F k"e&v&Jr    c                   .  a  ] tR tRt o RtRV 3R lR llt]RV 3R lR ll4       tR tV 3R	 lR
 lt	]
P                  ! 4       V 3R lR l4       tV 3R lR ltV 3R lR ltRV 3R lR lltV 3R lR ltV 3R lR ltV 3R lR ltV 3R lR ltRtV tR# )EMAModeli@  z.
Exponential Moving Average of models weights
Nc                   < V ^8  d   QhRS[ S[P                  P                  ,          RS[RS[RS[RS[RS[S[,          RS[S[,          RS[R	S[R
,          RS[S[	S[3,          R
,          /
# )r   r   decay	min_decayupdate_after_stepuse_ema_warmup	inv_gammapowerforeach	model_clsNmodel_config)
r   r$   r   	Parameterr1   r   r  r   r   rv   )r   __classdict__s   "r   r   EMAModel.__annotate__E  s     R) R)UXX//0R) R) 	R)
 R) R) 3;R) s{R) R) :R) 38nt+R)r    c                   \        V\        P                  P                  4      '       d$   Rp\	        RRVRR7       VP                  4       pRpVP                  RR4      e   R	p\	        RRVRR7       VR,          pVP                  R
R4      e   Rp\	        R
RVRR7       VR
,          p\        V4      pV Uu. uF   qP                  4       P                  4       NK"  	  upV n
        VP                  RR4      e+   Rp\	        RRVRR7       V P                  VR,          R7       RV n        W n        W0n        W@n        WPn        W`n        Wpn        ^ V n        RV n        Wn        Wn        Wn        R# u upi )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   r   r   getr   cloner   shadow_paramsr0   temp_stored_paramsrZ  r[  r\  r]  r^  r_  optimization_stepcur_decay_valuer`  ra  rb  )selfr   rZ  r[  r\  r]  r^  r_  r`  ra  rb  r?  deprecation_messageps   &&&&&&&&&&&,  r   __init__EMAModel.__init__E  sg   F j%((//22D   K##	 $..0J "N::k4(4"gk7,?uU;'E::k4(4"kk7,?uU{+I*%
:DE*Qggi..0*E::h%1"ah)<ERGG6(+G,"&
"!2,"
!"#"() Fs   9&E2c                   < V ^8  d   QhRR/# )r   rE   rX  rO   )r   rd  s   "r   r   re    s      
 r    c                    VP                  VR R7      w  rEVP                  V4      pV ! VP                  4       W&P                  VR7      pVP	                  V4       V# )T)return_unused_kwargs)ra  rb  r`  )from_configfrom_pretrainedr   r   load_state_dict)clspathra  r`  _
ema_kwargsr   	ema_models   &&&&    r   r{  EMAModel.from_pretrained  sY    !--d-N))$/((*illdkl	!!*-r    c                |   V P                   f   \        R4      hV P                  f   \        R4      hV P                   P                  V P                  4      pV P	                  4       pVP                  RR 4       VP                  ! R/ VB  V P                  VP                  4       4       VP                  V4       R # )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__.rn  rO   )
ra  rQ   rb  rz  r   popregister_to_configcopy_tor   save_pretrained)rr  r~  r   r   s   &&  r   r  EMAModel.save_pretrained  s    >>!ijj$lmm**4+<+<=__&
-  .:.U%%'(d#r    c                &   < V ^8  d   QhRS[ RS[/# )r   rp  rE   )r   r1   )r   rd  s   "r   r   re    s      3 5 r    c                j   \        ^ WP                  ,
          ^,
          4      pV^ 8:  d   R# V P                  '       d4   ^^W P                  ,          ,           V P                  ) ,          ,
          pM^V,           ^
V,           ,          p\        W0P                  4      p\        W0P                  4      pV# )z>
Compute the decay factor for the exponential moving average.
r>   )maxr\  r]  r^  r_  minrZ  r[  )rr  rp  steprq  s   &&  r   	get_decayEMAModel.get_decay  s     1'*@*@@1DE191tnn'<#<$**"LLO 4xBI6Oozz:o~~>r    c                X   < V ^8  d   QhRS[ S[P                  P                  ,          /# )r   r   r   r$   r   rc  )r   rd  s   "r   r   re    s#     7- 7-x(:(:; 7-r    c           
        \        V\        P                  P                  4      '       d"   R p\	        RRVRR7       VP                  4       p\        V4      pV ;P                  ^,          un        V P                  V P                  4      pW0n	        ^V,
          p\        P                  ! 4       pV P                  '       Ed   \        4       '       dP   \        P                  P                   P#                  4       '       d"   \         P$                  P'                  VRR7      pT;_uu_ 4        V Uu. uF  qfP(                  '       g   K  VNK  	  pp\+        V P,                  V4       UUu. uF  w  rVP(                  '       g   K  VNK  	  p	pp\/        V4      \/        V4      8  dy   \        P0                  ! \+        V P,                  V4       UUu. uF  w  rVP(                  '       d   K  VNK  	  uppV Uu. uF  qfP(                  '       d   K  VNK  	  upRR7       \        P2                  ! V	\        P4                  ! W4      VR	7       RRR4       R# \+        V P,                  V4       F  w  r\        4       '       dP   \        P                  P                   P#                  4       '       d"   \         P$                  P'                  VRR7      pT;_uu_ 4        VP(                  '       d    VP7                  WHV,
          ,          4       MVP9                  V4       RRR4       K  	  R# u upi u uppi u uppi u upi   + '       g   i     R# ; i  + '       g   i     K  ; i)
z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`rg  Frh  N)modifier_rankT)non_blocking)r9   )r   r$   r   r   r   r   r   rp  r  rq  
contextlibnullcontextr`  r   transformersintegrations	deepspeedis_deepspeed_zero3_enabledzeroGatheredParametersr   r
  rn  r2   _foreach_copy__foreach_sub__foreach_subsub_copy_)
rr  r   rs  rZ  one_minus_decaycontext_managerr   params_grads_params_params_grads
   &&        r   r  EMAModel.step  s   j%((//22D   P##	 $..0J*%
!# t556$e)$002<<<(**|/H/H/R/R/m/m/o/o"+.."C"CJ^b"C"c 2<T*@S@Suu*T25d6H6H*2U!2UY^YlYlGG2U  ! {#c*o5((7:4;M;Mz7Zv7Z^Wbgbubu7Zv,6RJ5>Q>QJR%) ##!5#5#5m#QYh !$ #&d&8&8*"E,..<3L3L3V3V3q3q3s3s&/nn&G&G]a&G&bO$_***_%%HIe,	 %_	 #F# U! wR !, %__sh   +M 0L*L*M )L/
L/

AM L5*L50M 7L;L;6M AM*M  M	M%c                \   < V ^8  d   QhRS[ S[P                  P                  ,          RR/# r   r   rE   Nr  )r   rd  s   "r   r   re    s.     @ @(588+=+="> @4 @r    c           
     
   \        V4      pV P                  '       d~   \        P                  ! V Uu. uF  q"P                  NK  	  up\        V P                  V4       UUu. uF*  w  r2VP                  VP                  4      P                  NK,  	  upp4       R# \        V P                  V4       FC  w  r2VP                  P                  VP                  VP                  4      P                  4       KE  	  R# u upi u uppi )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
  rn  r0   r.   r  )rr  r   r   r  s   &&  r   r  EMAModel.copy_to  s     *%
<<<  )344EHI[I[]gEhiEh>7ELL)..Ehi
 #&d&8&8*"E

  ELL!9!>!>? #F	 5is   C:!0C?c                   < V ^8  d   QhRR/# r   rE   NrO   )r   rd  s   "r   r   re    s     J JD Jr    c                l    V P                    Uu. uF  qP                  4       NK  	  upV n         R# u upi )z
Move internal buffers of the ExponentialMovingAverage to pinned memory. Useful for non-blocking transfers for
offloading EMA params to the host.
N)rn  
pin_memory)rr  rt  s   & r   r  EMAModel.pin_memory  s*     7;6H6HI6Hlln6HIIs   1c                   < V ^8  d   QhRR/# r  rO   )r   rd  s   "r   r   re    s     
 
 
r    c           	         V P                    Uu. uF>  pVP                  4       '       d   VP                  WVR7      MVP                  WR7      NK@  	  upV n         R# u upi )z
Move internal buffers of the ExponentialMovingAverage to `device`.

Args:
    device: like `device` argument to `torch.Tensor.to`
)r.   rJ   r  )r.   r  N)rn  is_floating_pointr0   )rr  r.   rJ   r  rt  s   &&&& r   r0   EMAModel.to  se     ''	
 ( ""$$ DD,DGV?@ (	
 
s
   A)Ac                    < V ^8  d   QhRS[ /# r1  r2  )r   rd  s   "r   r   re  )  s     
 
D 
r    c                    RV P                   RV P                  RV P                  RV P                  RV P                  RV P
                  RV P                  RV P                  /# )	z
Returns the state of the ExponentialMovingAverage as a dict. This method is used by accelerate during
checkpointing to save the ema state dict.
rZ  r[  rp  r\  r]  r^  r_  rn  )rZ  r[  rp  r\  r]  r^  r_  rn  )rr  s   &r   r   EMAModel.state_dict)  s^     TZZ!7!7!7!7d11TZZT//	
 		
r    c                \   < V ^8  d   QhRS[ S[P                  P                  ,          RR/# r  r  )r   rd  s   "r   r   re  <  s.     Y Y);); < Y Yr    c                    V Uu. uF.  q"P                  4       P                  4       P                  4       NK0  	  upV n        R# u upi )z
Saves the current parameters for restoring later.

Args:
    parameters: Iterable of `torch.nn.Parameter`. The parameters to be temporarily stored.
N)r   r4  rm  ro  )rr  r   r   s   && r   storeEMAModel.store<  s6     NX"XZE<<>#5#5#7#=#=#?Z"X"Xs   4Ac                \   < V ^8  d   QhRS[ S[P                  P                  ,          RR/# r  r  )r   rd  s   "r   r   re  E  s*     ' '(588+=+="> '4 'r    c                   V P                   f   \        R4      hV P                  '       dU   \        P                  ! V Uu. uF  q"P
                  NK  	  upV P                    Uu. uF  q3P
                  NK  	  up4       MD\        V P                   V4       F*  w  r2VP
                  P                  VP
                  4       K,  	  RV n         R# u upi u upi )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()`)ro  RuntimeErrorr`  r$   r  r   r
  r  )rr  r   r   c_params   &&  r   restoreEMAModel.restoreE  s     ""*hii<<<  )344SWSjSj6kSj||Sj6k #&d&=&=z"J

  . #K #' 56ks    C$C
c                $   < V ^8  d   QhRS[ RR/# )r   r   rE   Nr2  )r   rd  s   "r   r   re  ^  s     .F .F$ .F4 .Fr    c                   \         P                  ! V4      pVP                  RV P                  4      V n        V P                  R8  g   V P                  R8  d   \	        R4      hVP                  RV P
                  4      V n        \        V P
                  \        4      '       g   \	        R4      hVP                  RV P                  4      V n        \        V P                  \        4      '       g   \	        R4      hVP                  R	V P                  4      V n
        \        V P                  \        4      '       g   \	        R
4      hVP                  RV P                  4      V n        \        V P                  \        4      '       g   \	        R4      hVP                  RV P                  4      V n        \        V P                  \        \        34      '       g   \	        R4      hVP                  RV P                  4      V n        \        V P                  \        \        34      '       g   \	        R4      hVP                  RR4      pVe   W n        \        V P                  \         4      '       g   \	        R4      h\"        ;QJ d&    R V P                   4       F  '       d   K   RM	  RM! R V P                   4       4      '       g   \	        R4      hR# R# )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`.
rZ  r>   r,   zDecay must be between 0 and 1r[  zInvalid min_decayrp  zInvalid optimization_stepr\  zInvalid update_after_stepr]  zInvalid use_ema_warmupr^  zInvalid inv_gammar_  zInvalid powerrn  Nzshadow_params must be a listc              3   V   "   T F  p\        V\        P                  4      x  K!  	  R # 5ir  )r   r$   rF   )r  rt  s   & r   r  +EMAModel.load_state_dict.<locals>.<genexpr>  s      O<Nqz!U\\22<Ns   ')FTz!shadow_params must all be Tensors)copydeepcopyrl  rZ  rQ   r[  r   r1   rp  r   r\  r]  r  r^  r_  rn  r   all)rr  r   rn  s   && r   r|  EMAModel.load_state_dict^  s    ]]:.
^^GTZZ8
::tzzC/<==#T^^D$..%00011!+0CTE[E[!\$00#66899!+0CTE[E[!\$00#66899(nn-=t?R?RS$--t44566#T^^D$..5#,77011^^GTZZ8
$**ucl33_--"=$!.d00$77 !?@@3OD<N<NO333OD<N<NOOO !DEE P	 %r    )rq  rZ  r`  r^  r[  ra  rb  rp  r_  rn  ro  r\  r]  )	gH.?r>   r   Fr,   gUUUUUU?FNN)F)NNF)rO  
__module____qualname____firstlineno____doc__ru  classmethodr{  r  r  r$   r[   r  r  r  r0   r   r  r  r|  __static_attributes____classdictcell__)rd  s   @r   rX  rX  @  s     R) R)h   $ & ]]_7- 7-r@ @&J J
 

 
&Y Y' '2.F .Fr    rX  i)r,   )NNNr4  Nr  )TTTNN)Kr  r  r   r   r"   r  r  r   	functoolsr   typingr   r   numpyr#   r$   torch.nn.functionalr   r   rT   distributedr   torch.distributed.fsdpr   r   r	   rI  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<   rr   r   r   r   float32r   r   r   r   r   r   r  r!  r/  r7  rA  rV  rX  rO   r    r   <module>r     s     	   	  %        	!!##CGHJD#'  ( ( &	 	 	   **EEGG-.&)("JS% 	S%
 S% .2S% S%l)X3#l& PU}} -"]&6$   nr  >8	t./fLF LFr    