+
     °³j¥Â  ã                   óÞ  € ^ 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 ^ RIHt ^ RIHt ^ RIHtHt ^ RIt^RIHt ^R	IHtHtHtHt ^R
IHt ^RIHtHt ^RIH t H!t!H"t" ^RI#H$t$ ]! ]%4      t&R t'R t(R.R lt)R.R lt*R t+R/R lt,R/R lt-R0R lt.R/R lt/R1R R llt0R2R R llt1R R lt2R3R R llt3R R  lt4R! R" lt5R# R$ lt6R% R& lt7R' R( lt8R) t9R* R+ lt:R, R- lt;R# )4é    N)Údefaultdict)ÚIterable)Únullcontext)Úreplace)ÚPath)ÚCallableÚUnion)Ú
get_logger)ÚFSDP_MODEL_NAMEÚOPTIMIZER_NAMEÚSAFE_WEIGHTS_NAMEÚWEIGHTS_NAME)Úget_module_class_from_name)Úget_non_persistent_buffersÚis_peft_model)Úget_module_children_bottom_upÚis_compiled_moduleÚsave)Úis_torch_versionc                 ó|   € R\         P                  9  d   R\         P                  R&   R\         P                  R&   R# )zS
Enables RAM efficient loading of Hugging Face models for FSDP in the environment.
ÚACCELERATE_USE_FSDPÚTrueÚFSDP_CPU_RAM_EFFICIENT_LOADINGN©ÚosÚenviron© ó    Ú\/home/luca/screen-checking/.venv/lib/python3.14/site-packages/accelerate/utils/fsdp_utils.pyÚ!enable_fsdp_ram_efficient_loadingr    (   s.   € ð
 ¤B§J¡JÔ.Ø,2Œ�
‰
Ð(Ñ)Ø39„B‡J�JÐ/Ó0r   c                 ó,   € R\         P                  R&   R# )zT
Disables RAM efficient loading of Hugging Face models for FSDP in the environment.
ÚFalser   Nr   r   r   r   Ú"disable_fsdp_ram_efficient_loadingr#   2   s   € ð 4;„B‡J�JÐ/Ó0r   c                 ó  € V'       d\   \        V 4      '       dK   Ve.   VP                  '       d   ^ RIHp V! V \	        VRR7      R7      # ^ RIHp V! W P                  R7      # Ve   ^ RIHp V! WR7      # V P                  4       # )N)Úget_model_state_dictT)Úignore_frozen_params©Úoptions)Úget_peft_model_state_dict©Úadapter_name)	r   Úfull_state_dictÚ'torch.distributed.checkpoint.state_dictr%   r   Úpeftr)   Úactive_adapterÚ
state_dict)ÚmodelÚadapter_onlyÚ
sd_optionsr%   r)   s   &&&  r   Ú_get_model_state_dictr4   9   sq   € ßœ e×,Ò,ØÒ! j×&@×&@Ð&@ÝTá'¨´w¸zÐ`dÔ7eÔfÐfå2á(¨×=QÑ=QÔRÐRð ÒÝPá# EÔ>Ð>à×ÑÓ!Ð!r   c           	      ó  € V'       d]   \        V 4      '       dL   Ve.   VP                  '       d   ^ RIHp V! W\	        VRR7      R7      # ^ RIHp V! WV P                  R7      # Ve   ^ RIHp V! WVR7      # V P                  V4      # )N)Úset_model_state_dictF)Ústrictr'   )Úset_peft_model_state_dictr*   )	r   r,   r-   r6   r   r.   r8   r/   Úload_state_dict)r1   r0   r2   r3   r6   r8   s   &&&&  r   Ú_set_model_state_dictr:   M   sw   € ßœ e×,Ò,ØÒ! j×&@×&@Ð&@ÝTá'¨Ä7È:Ð^cÔCdÔeÐeå2á(¨È×I]ÑI]Ô^Ð^ð ÒÝPá# E¸zÔJÐJà×$Ñ$ ZÓ0Ð0r   c           	      óÜ   € R pV P                   ^8X  dY   ^ RIHp ^ RIHp V! V P
                  VP                  8H  \        V P                  RR4      \        V P                  RR4      R7      pV# )N)ÚStateDictOptions©ÚStateDictTypeÚoffload_to_cpuFÚ
rank0_only)r,   Úcpu_offloadÚbroadcast_from_rank0)	Úfsdp_versionr-   r<   Ú2torch.distributed.fsdp.fully_sharded_data_parallelr>   Ústate_dict_typeÚFULL_STATE_DICTÚgetattrÚstate_dict_config)Úfsdp_pluginr3   r<   r>   s   &   r   Ú_prepare_sd_optionsrJ   a   sj   € Ø€Jð ×Ñ 1Ô$ÝLÝTá%Ø'×7Ñ7¸=×;XÑ;XÑXÜ × =Ñ =Ð?OÐQVÓWÜ!(¨×)FÑ)FÈÐV[Ó!\ô
ˆ
ð Ðr   c                ó`  € ^ RI Hp ^ RI Hp \        P                  ! VRR7       V P
                  VP                  8X  d0   VP                  ^8„  p	W�P                  n	        W�P                  n
        V P                  ^8X  d2   VP                  W P
                  V P                  V P                  4      M	\        4       p
\        V 4      pT
;_uu_ 4        \        W%VR7      pV P
                  VP                  8X  d•   V^ 8X  d
   \          R2M\          RV R2p\        P"                  P%                  W=4      pVP&                  ^ 8X  dG   \(        P+                  RV 24       \,        P.                  ! WÎ4       \(        P+                  R	V 24       EMV P
                  VP0                  8X  dž   V^ 8X  d   \          R
VP&                   R2M\          RV R
VP&                   R2p\        P"                  P%                  W=4      p\(        P+                  RV 24       \,        P.                  ! WÎ4       \(        P+                  R	V 24       EMMV P
                  VP2                  8X  Ed2   V'       d¬   ^ RIHu Hp ^ RIHp \        P"                  P%                  V\          RV 24      p\        P                  ! VRR7       \(        P+                  RV 24       VP/                  RV/VP?                  V4      V! 4       R7       \(        P+                  R	V 24       M~\          RV R
VP&                   R2p\        P"                  P%                  W=4      p\(        P+                  RV 24       \,        P.                  ! WÎ4       \(        P+                  R	V 24       RRR4       R#   + '       g   i     R# ; i)aZ  
Save an FSDP model checkpoint.

When ``state_dict_type`` is ``SHARDED_STATE_DICT``, the ``use_dcp`` parameter controls the saving strategy:

- ``use_dcp=True`` (default): Uses ``torch.distributed.checkpoint`` (DCP) to save sharded model state.
  This is the standard approach and works well for typical training setups.
- ``use_dcp=False``: Uses per-rank ``torch.save`` instead of DCP. Each rank saves its own shard
  independently to a separate file, avoiding cross-rank communication entirely. This is significantly
  faster at large scale (e.g., 2800+ GPUs) where DCP's all-gather-based saving can cause timeouts
  due to TCP congestion from Gloo-based collective communication.

.. note::
    Checkpoints saved with ``use_dcp=False`` are saved as per-rank files
    (``{prefix}_rank{local_rank}.bin``) and must be loaded with ``use_dcp=False`` as well.
©ÚFullyShardedDataParallelr=   T©Úexist_ok©r2   r3   ú.binÚ_zSaving model to zModel saved to Ú_rankN©ÚDefaultSavePlannerr1   ©r0   Ústorage_writerÚplanner) rD   rM   r>   r   ÚmakedirsrE   rF   Únum_processesrH   r?   r@   rC   Úoptim_state_dict_configr   rJ   r4   r   ÚpathÚjoinÚprocess_indexÚloggerÚinfoÚtorchr   ÚLOCAL_STATE_DICTÚSHARDED_STATE_DICTÚtorch.distributed.checkpointÚdistributedÚ
checkpointÚ,torch.distributed.checkpoint.default_plannerrU   ÚFileSystemWriter)rI   Úacceleratorr1   Ú
output_dirÚmodel_indexr2   Úuse_dcpÚFSDPr>   Úis_multi_processÚctxr3   r0   Úweights_nameÚoutput_model_fileÚdist_cprU   Úckpt_dirs   &&&&&&&           r   Úsave_fsdp_modelrt   r   s  € õ$ dÝPä‡K‚K�
 TÕ*Ø×"Ñ" m×&CÑ&CÔCð '×4Ñ4°qÑ8ÐØ7G×%Ñ%Ô4Ø3C×%Ñ%Ô0ð ×#Ñ# qÔ(ð 	×ÑØ×.Ñ.°×0MÑ0MÈ{×OrÑOrô	
ô ‹]ð ô % [Ó1€Jç	ŠÜ*¨5ÐXbÔcˆ
Ø×&Ñ&¨-×*GÑ*GÔGØ7BÀaÔ7GœoÐ.¨dÑ3ÔP_ÐO`Ð`aÐbmÐanÐnrÐMsˆLÜ "§¡§¡¨ZÓ FÐØ×(Ñ(¨AÔ-Ü—‘Ð.Ð/@Ð.AÐBÔCÜ—
’
˜:Ô9Ü—‘˜oÐ.?Ð-@ÐAÔBùà×(Ñ(¨M×,JÑ,JÔJð  !Ô#ô #Ð# 5¨×)BÑ)BÐ(CÀ4ÑHä'Ð(¨¨+¨°e¸K×<UÑ<UÐ;VÐVZÐ[ð ô
 !#§¡§¡¨ZÓ FÐÜ�K‰KÐ*Ð+<Ð*=Ð>Ô?Ü�JŠJ�zÔ5Ü�K‰K˜/Ð*;Ð)<Ð=Ö>Ø×(Ñ(¨M×,LÑ,LÕLßß>Ð>Ý[äŸ7™7Ÿ<™<¨
´Ð6GÀqÈÈÐ4VÓW�Ü—’˜H¨tÕ4Ü—‘Ð.¨x¨jÐ9Ô:Ø—‘Ø '¨Ð4Ø#*×#;Ñ#;¸HÓ#EÙ.Ó0ð ô ô
 —‘˜o¨h¨ZÐ8Õ9ä"1Ð!2°!°K°=ÀÀk×F_ÑF_ÐE`Ð`dÐe�Ü$&§G¡G§L¡L°Ó$JÐ!Ü—‘Ð.Ð/@Ð.AÐBÔCÜ—
’
˜:Ô9Ü—‘˜oÐ.?Ð-@ÐAÔB÷O 
��Šús   ÃFNÉ)D)NÎN-	c           	     óÎ  € ^ RI Hp ^ RI Hp VP                  4        V P                  VP
                  8X  d0   VP                  ^8„  p	W�P                  n        W�P                  n	        V P                  ^8X  d2   VP	                  W P                  V P                  V P                  4      M	\        4       p
\        V 4      pT
;_uu_ 4        V P                  VP
                  8X  Ed!   \        V4      VJd]   VP                  ^ 8w  dL   VP                   '       g:   V P"                  '       g   V P                  ^8X  d   \%        R4      h RRR4       R# V^ 8X  d
   \&         R2M\&         RV R2p\(        P*                  P-                  W<4      p\.        P1                  RV 24       VP                   '       * ;'       g    VP2                  pV'       d   \4        P6                  ! VRR	7      pM/ p\.        P1                  R
V 24       EM'V P                  VP8                  8X  d    V^ 8X  d   \&         RVP                   R2M\&         RV RVP                   R2p\(        P*                  P-                  W<4      p\.        P1                  RV 24       \4        P6                  ! VRR	7      p\.        P1                  R
V 24       EMmV P                  VP:                  8X  EdR   V'       dÊ   ^ RIHu H p ^ RI!H"p \G        V4      PH                  \&         RV 28w  d   \G        V4      \&         RV 2,          M
\G        V4      p\.        P1                  RV 24       R\K        W%VR7      /pVP7                  VVPM                  V4      V! 4       R7       VR,          p\.        P1                  R
V 24       M€\&         RV RVP                   R2p\(        P*                  P-                  W<4      p\.        P1                  RV 24       \4        P6                  ! VRR	7      p\.        P1                  R
V 24       \O        VXW[R7      pRRR4       VP                  4        X#   + '       g   i     L"; i)au  
Load an FSDP model checkpoint.

When ``state_dict_type`` is ``SHARDED_STATE_DICT``, the ``use_dcp`` parameter controls the loading strategy:

- ``use_dcp=True`` (default): Uses ``torch.distributed.checkpoint`` (DCP) to load sharded model state.
  This is the standard approach and works well for typical training setups.
- ``use_dcp=False``: Uses per-rank ``torch.load`` instead of DCP. Each rank loads its own shard
  independently from a separate file, avoiding cross-rank communication entirely. This is significantly
  faster at large scale (e.g., 2800+ GPUs) where DCP's broadcast-based loading can cause timeouts
  due to TCP congestion from Gloo-based collective communication.

.. note::
    Checkpoints saved with ``use_dcp=False`` must be loaded with ``use_dcp=False`` as well, since the
    file format differs (per-rank ``.bin`` files vs. DCP's sharded directory format).
rL   r=   zzSet the `sync_module_states` flag to `True` so that model states are synced across processes when initializing FSDP objectNrQ   rR   zLoading model from T©Úweights_onlyzModel loaded from rS   ©ÚDefaultLoadPlannerr1   rP   ©r0   Ústorage_readerrX   )(rD   rM   r>   Úwait_for_everyonerE   rF   rZ   rH   r?   r@   rC   r[   r   rJ   Útyper^   Úis_fsdp2Úsync_module_statesÚ
ValueErrorr   r   r\   r]   r_   r`   Úis_main_processra   Úloadrb   rc   rd   re   rf   rg   ry   r   Únamer4   ÚFileSystemReaderr:   )rI   ri   r1   Ú	input_dirrk   r2   rl   rm   r>   rn   ro   r3   rp   Úinput_model_fileÚ
load_modelr0   rr   ry   rs   Úload_results   &&&&&&&             r   Úload_fsdp_modelr‰   Â   så  € õ$ dÝPà×!Ñ!Ô#Ø×"Ñ" m×&CÑ&CÔCð '×4Ñ4°qÑ8ÐØ7G×%Ñ%Ô4Ø3C×%Ñ%Ô0ð ×#Ñ# qÔ(ð 	×ÑØ×.Ñ.°×0MÑ0MÈ{×OrÑOrô	
ô ‹]ð ô % [Ó1€Jß	ŠØ×&Ñ&¨-×*GÑ*GÕGÜ�E‹{ $Ó&¨;×+DÑ+DÈÔ+IÐR]×Rf×RfÐRfØ"×5×5Ð5¸+×:RÑ:RÐVWÔ:WÜ$ð3óð ð ÷ 
‰ð 8CÀaÔ7GœoÐ.¨dÑ3ÔP_ÐO`Ð`aÐbmÐanÐnrÐMsˆLÜ!Ÿw™wŸ|™|¨IÓDÐÜ�K‰KÐ-Ð.>Ð-?Ð@ÔAà(×1Ñ1Ô1×PÐP°[×5PÑ5PˆJßÜ"ŸZšZÐ(8ÀtÔL‘
à�
Ü�K‰KÐ,Ð-=Ð,>Ð?Ö@Ø×(Ñ(¨M×,JÑ,JÔJð  !Ô#ô #Ð# 5¨×)BÑ)BÐ(CÀ4ÑHä'Ð(¨¨+¨°e¸K×<UÑ<UÐ;VÐVZÐ[ð ô
  "Ÿw™wŸ|™|¨IÓDÐÜ�K‰KÐ-Ð.>Ð-?Ð@ÔAÜŸšÐ$4À4ÔHˆJÜ�K‰KÐ,Ð-=Ð,>Ð?Ö@Ø×(Ñ(¨M×,LÑ,LÕLßß>Ð>Ý[ô ˜I“×+Ñ+´/Ð1BÀ!ÀKÀ=Ð/QÔQô ˜“O¬Ð(9¸¸;¸-Ð&HÖHä˜i›ð ô
 —‘Ð1°(°Ð<Ô=Ø%Ô'<¸UÐjtÔ'uÐv�
Ø—‘Ø)Ø#*×#;Ñ#;¸HÓ#EÙ.Ó0ð ô ð
 (¨Õ0�
Ü—‘Ð0°°
Ð;Õ<ä"1Ð!2°!°K°=ÀÀk×F_ÑF_ÐE`Ð`dÐe�Ü#%§7¡7§<¡<°	Ó#HÐ Ü—‘Ð1Ð2BÐ1CÐDÔEÜ"ŸZšZÐ(8ÀtÔL�
Ü—‘Ð0Ð1AÐ0BÐCÔDä+¨E°:ÈLÔpˆ÷o 
ðp ×!Ñ!Ô#ØÐ÷s 
�ús4   ÃAQÄQÄ)QÅA*QÆ;QÇDQË#EQÑQ$	c                óp  € ^ RI Hp ^ RI Hp \        P                  ! VRR7       V P
                  ^8X  d2   VP                  W0P                  V P                  V P                  4      M	\        4       p	\        V 4      p
T	;_uu_ 4        V P
                  ^8X  d   ^ RIHp V! W2V
R7      pMVP                  W24      pV P                  VP                  8X  d•   VP                  ^ 8X  d‚   V^ 8X  d
   \          R2M\          RV R2p\        P"                  P%                  WM4      p\&        P)                  R	V 24       \*        P,                  ! WÎ4       \&        P)                  R
V 24       EM1V'       d¬   ^ RIHu Hp ^ RIHp \        P"                  P%                  V\          RV 24      p\        P                  ! VRR7       \&        P)                  R	V 24       VP-                  RV/VP9                  V4      V! 4       R7       \&        P)                  R
V 24       M~\          RV RVP                   R2p\        P"                  P%                  WM4      p\&        P)                  R	V 24       \*        P,                  ! WÎ4       \&        P)                  R
V 24       RRR4       R#   + '       g   i     R# ; i)a¦  
Save an FSDP optimizer state checkpoint.

When ``state_dict_type`` is not ``FULL_STATE_DICT``, the ``use_dcp`` parameter controls the saving strategy:

- ``use_dcp=True`` (default): Uses ``torch.distributed.checkpoint`` (DCP) to save the optimizer state.
- ``use_dcp=False``: Uses per-rank ``torch.save`` instead of DCP, avoiding cross-rank communication.
  This is useful at large scale (e.g., 2800+ GPUs) where DCP can cause timeouts due to TCP congestion
  from Gloo-based collective communication.

.. note::
    Checkpoints saved with ``use_dcp=False`` are saved as per-rank files
    (``{prefix}_rank{local_rank}.bin``) and must be loaded with ``use_dcp=False`` as well.
rL   r=   TrN   ©Úget_optimizer_state_dictr'   rQ   rR   zSaving Optimizer state to zOptimizer state saved in NrT   Ú	optimizerrV   rS   )rD   rM   r>   r   rY   rC   rE   rH   r[   r   rJ   r-   rŒ   Úoptim_state_dictrF   r^   r   r\   r]   r_   r`   ra   r   rd   re   rf   rg   rU   rh   )rI   ri   r�   r1   rj   Úoptimizer_indexrl   rm   r>   ro   r3   rŒ   Úoptim_stateÚoptim_state_nameÚoutput_optimizer_filerr   rU   rs   s   &&&&&&&           r   Úsave_fsdp_optimizerr“   #  sD  € õ  dÝPä‡K‚K�
 TÕ*ð ×#Ñ# qÔ(ð 	×ÑØ×.Ñ.°×0MÑ0MÈ{×OrÑOrô	
ô ‹]ð ô % [Ó1€Jç	ŠØ×#Ñ# qÔ(ÝXá2°5ÈZÔX‰Kà×/Ñ/°ÓAˆKà×&Ñ&¨-×*GÑ*GÔGØ×(Ñ(¨AÔ-à/>À!Ô/C”~Ð& dÑ+ÌNÐK[Ð[\Ð]lÐ\mÐmqÐIrð !ô )+¯©¯©°ZÓ(RÐ%Ü—‘Ð8Ð9NÐ8OÐPÔQÜ—
’
˜;Ô>Ü—‘Ð7Ð8MÐ7NÐOÔPùçß>Ð>Ý[äŸ7™7Ÿ<™<¨
´~Ð6FÀaÈÐGXÐ4YÓZ�Ü—’˜H¨tÕ4Ü—‘Ð8¸¸
ÐCÔDØ—‘Ø +¨[Ð9Ø#*×#;Ñ#;¸HÓ#EÙ.Ó0ð ô ô
 —‘Ð7¸°zÐBÕCä&4Ð%5°Q°Ð6GÀuÈ[×MfÑMfÐLgÐgkÐ#lÐ Ü(*¯©¯©°ZÓ(RÐ%Ü—‘Ð8Ð9NÐ8OÐPÔQÜ—
’
˜;Ô>Ü—‘Ð7Ð8MÐ7NÐOÔP÷I 
��Šús   ÂC*J$Å1D)J$Ê$J5	c           	     ót  € ^ RI Hp ^ RI Hp	 VP                  4        V P                  ^8X  d2   VP                  W0P
                  V P                  V P                  4      M	\        4       p
\        V 4      pT
;_uu_ 4        V P
                  V	P                  8X  dµ   RpVP                  ^ 8X  g   V P                  P                  '       g„   V^ 8X  d
   \         R2M\         RV R2p\        P                  P!                  WM4      p\"        P%                  RV 24       \&        P(                  ! VRR7      p\"        P%                  R	V 24       EMyV'       dò   ^ RIHu Hp ^ R
IHp \5        V4      P6                  \         RV 28w  d   \5        V4      \         RV 2,          M
\5        V4      p\"        P%                  RV 24       V P                  ^8X  d   ^ RIHp V! W2VR7      pMVP=                  W24      pRV/pVP)                  VVP?                  V4      V! 4       R7       VR,          p\"        P%                  RV 24       M€\         RV RVP                   R2p\        P                  P!                  WM4      p\"        P%                  RV 24       \&        P(                  ! VRR7      p\"        P%                  RV 24       V P                  ^8X  d&   VPA                  W2VR7      pVPC                  V4       M^ RIH"p V! W2WËR7       RRR4       VP                  4        R#   + '       g   i     L"; i)a¿  
Load an FSDP optimizer state checkpoint.

When ``state_dict_type`` is not ``FULL_STATE_DICT``, the ``use_dcp`` parameter controls the loading strategy:

- ``use_dcp=True`` (default): Uses ``torch.distributed.checkpoint`` (DCP) to load the optimizer state.
- ``use_dcp=False``: Uses per-rank ``torch.load`` instead of DCP, avoiding cross-rank communication.
  This is useful at large scale (e.g., 2800+ GPUs) where DCP can cause timeouts due to TCP congestion
  from Gloo-based collective communication.

.. note::
    Checkpoints saved with ``use_dcp=False`` must be loaded with ``use_dcp=False`` as well, since the
    file format differs (per-rank ``.bin`` files vs. DCP's sharded directory format).
rL   r=   NrQ   rR   zLoading Optimizer state from Trv   zOptimizer state loaded from rx   zLoading Optimizer from r‹   r'   r�   rz   zOptimizer loaded from rS   )r1   ÚoptimrŽ   )Úset_optimizer_state_dict)#rD   rM   r>   r|   rC   rE   rH   r[   r   rJ   rF   r^   r@   r   r   r\   r]   r_   r`   ra   r‚   rd   re   rf   rg   ry   r   rƒ   r-   rŒ   rŽ   r„   Úoptim_state_dict_to_loadr9   r–   )rI   ri   r�   r1   r…   r�   r2   rl   rm   r>   ro   r3   r�   Úoptimizer_nameÚinput_optimizer_filerr   ry   rs   rŒ   Úflattened_osdr–   s   &&&&&&&&             r   Úload_fsdp_optimizerr›   i  sÜ  € õ$ dÝPà×!Ñ!Ô#ð
 ×#Ñ# qÔ(ð 	×ÑØ×.Ñ.°×0MÑ0MÈ{×OrÑOrô	
ô ‹]ð ô % [Ó1€Jß	ŠØ×&Ñ&¨-×*GÑ*GÔGØˆKØ×(Ñ(¨AÔ-°[×5XÑ5X×5c×5cÐ5cà/>À!Ô/C”~Ð& dÑ+ÌNÐK[Ð[\Ð]lÐ\mÐmqÐIrð ô (*§w¡w§|¡|°IÓ'NÐ$Ü—‘Ð;Ð<PÐ;QÐRÔSÜ#ŸjšjÐ)=ÈDÔQ�Ü—‘Ð:Ð;OÐ:PÐQÔRùçß>Ð>Ý[ô ˜I“×+Ñ+´.Ð1AÀÀ?ÐBSÐ/TÔTô ˜“O¬Ð(8¸¸/Ð9JÐ&KÖKä˜i›ð ô
 —‘Ð5°h°ZÐ@ÔAØ×+Ñ+¨qÔ0Ý`á":¸5ÐU_Ô"`‘Kà"&×"7Ñ"7¸Ó"I�KØ*¨KÐ8�Ø—‘Ø*Ø#*×#;Ñ#;¸HÓ#EÙ.Ó0ð ô ð
 *¨+Õ6�Ü—‘Ð4°X°JÐ?Õ@ä$2Ð#3°1°_Ð4EÀUÈ;×KdÑKdÐJeÐeiÐ!j�Ü')§w¡w§|¡|°IÓ'NÐ$Ü—‘Ð5Ð6JÐ5KÐLÔMÜ#ŸjšjÐ)=ÈDÔQ�Ü—‘Ð4Ð5IÐ4JÐKÔLà×#Ñ# qÔ(Ø ×9Ñ9ÀÐitÐ9ÓuˆMØ×%Ñ% mÕ4åXá$ U°{ÕW÷c 
ðf ×!Ñ!Ö#÷g 
�ús   Á>A
L'Ã	BL'ÅF7L'Ì'L7	c                ó<   € V ^8„  d   QhR\         R\         R\        /# )é   Úcheckpoint_dirÚ	save_pathÚsafe_serialization©ÚstrÚbool)Úformats   "r   Ú__annotate__r¥   ½  s"   € ÷ ñ ¼cð Ìcð Ôgkñ r   c                óž  € ^ RI Hu Hp ^ RIHu Hu Hp / p\        V4      pVP                  RR7       VP                  VVP                  V 4      VP                  4       RR7       V'       d   V\        ,          MV\        ,          p\        VP                  4       4      ^8X  d   V\        V4      ^ ,          ,          p\        WQVR7       V# )z¡
Passthrough to `torch.distributed.checkpoint.format_utils.dcp_to_torch_save`

Will save under `save_path` as either `model.safetensors` or `pytorch_model.bin`.
NTrN   )r{   rX   Úno_dist)r    )rd   re   rf   Ú)torch.distributed.checkpoint.format_utilsÚformat_utilsr   ÚmkdirÚ_load_state_dictr„   Ú_EmptyStateDictLoadPlannerr   r   ÚlenÚkeysÚlistr   )rž   rŸ   r    rr   Údist_cp_format_utilsr0   s   &&&   r   Ú)_distributed_checkpoint_to_merged_weightsr±   ½  s²   € ÷ 3Ð2ßLÓLà€JÜ�Y“€IØ‡O�O˜T€OÔ"Ø×)Ñ)ØØ×/Ñ/°Ó?Ø$×?Ñ?ÓAØð	 *ô ÷ 2D�	Ô-Ö-ÈÔUaÕIa€Iô ˆ:�?‰?ÓÓ Ô"Ø¤ ZÓ 0°Õ 3Õ4ˆ
ÜˆÐ3EÕFØÐr   c                óH   € V ^8„  d   QhR\         R\         R\        R\        /# )r�   rž   Úoutput_pathr    Úremove_checkpoint_dirr¡   )r¤   s   "r   r¥   r¥   Ù  s,   € ÷ 4ñ 4Üð4Ü&)ð4Ü?Cð4Ücgñ4r   c                ó"  € \        V 4      p ^ RIHp \        RR4      '       g   \	        R4      hV P                  4       '       g°   V R,          P                  4       pV R,          P                  4       pRV  R2pV'       d,   V'       d$   VR	,          pVR
V  RV  R2,          pVR,          pM=V'       d   VR,          pVRV  R2,          pMV'       d   VR,          pVRV  R2,          p\	        V4      hV! 4       pVP                  '       ds   \        P                  RV  24       \        WV4      p	\        P                  RV	 24       V'       d/   \        P                  RV  24       \        P                  ! V 4       VP                  4        R# )a  
Merge the weights from sharded FSDP model checkpoints into a single combined checkpoint. Should be used if
`SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}/model.safetensors` if
`safe_serialization` else `pytorch_model.bin`.

Note: this is a CPU-bound process.

Args:
    checkpoint_dir (`str`):
        The directory containing the FSDP checkpoints (can be either the model or optimizer).
    output_path (`str`):
        The path to save the merged checkpoint.
    safe_serialization (`bool`, *optional*, defaults to `True`):
        Whether to save the merged weights with safetensors (recommended).
    remove_checkpoint_dir (`bool`, *optional*, defaults to `False`):
        Whether to remove the checkpoint directory after merging.
)ÚPartialStateú>=z2.3.0z/`merge_fsdp_weights` requires PyTorch >= 2.3.0`Úpytorch_model_fsdp_0Úoptimizer_0zTried to load from z) but couldn't find a valid metadata file.zE However, potential model and optimizer checkpoint directories exist.zPlease pass in either z/pytorch_model_fsdp_0 or z/optimizer_0zinstead.z8 However, a potential model checkpoint directory exists.zPlease try passing in z/pytorch_model_fsdp_0 instead.z< However, a potential optimizer checkpoint directory exists.z/optimizer_0 instead.zMerging FSDP weights from z.Successfully merged FSDP weights and saved to z"Removing old checkpoint directory N)r   Úaccelerate.stater¶   r   r€   Úexistsr�   r_   r`   r±   ÚshutilÚrmtreer|   )
rž   r³   r    r´   r¶   Úmodel_path_existsÚoptimizer_path_existsÚerrÚstaterŸ   s
   &&&&      r   Úmerge_fsdp_weightsrÂ   Ù  s{  € ô( ˜.Ó)€NÝ-ä˜D '×*Ò*ÜÐJÓKÐKð × Ñ ×"Ò"Ø+Ð.DÕD×LÑLÓNÐØ!/°-Õ!?× GÑ GÓ IÐØ# NÐ#3Ð3\Ð]ˆß×!6ØÐZÕZˆCØÐ+¨NÐ+;Ð;TÐUcÐTdÐdpÐqÕqˆCØ�:Õ‰CßØÐMÕMˆCØÐ+¨NÐ+;Ð;YÐZÕZ‰Cß"ØÐQÕQˆCØÐ+¨NÐ+;Ð;PÐQÕQˆCÜ˜‹oÐñ ‹N€EØ××ÐÜ�‰Ð0°Ð0@ÐAÔBÜ=¸nÐ[mÓnˆ	Ü�‰ÐDÀYÀKÐPÔQß Ü�K‰KÐ<¸^Ð<LÐMÔNÜ�MŠM˜.Ô)Ø	×ÑÖr   c                ól   € V ^8„  d   QhR\         P                  P                  R\         P                  /# )r�   r1   Údevice)ra   ÚnnÚModulerÄ   )r¤   s   "r   r¥   r¥     s&   € ÷ +$ñ +$´·±·±ð +$ÌÏÉñ +$r   c                 ó  a a	€ \        VR R4      pV'       g   S # / o	V FZ  pVP                  R4      pRP                  VRR 4      VR,          rTVP                  V4      p\        We4      pRS	\	        V4      &   K\  	  R V	V 3R llpV# )Ú_tied_weights_keysNÚ.c                óL   € V ^8„  d   QhR\         P                  P                  /# )r�   Úmodule©ra   rÅ   rÆ   )r¤   s   "r   r¥   Ú+ensure_weights_retied.<locals>.__annotate__"  s   € ÷ ñ ¬¯©¯©ñ r   c                 óh  <€ \        \        4      pV P                  R R7       F8  w  r#\        V4      S9   g   K  V\        V4      ,          P	                  V4       K:  	  S! V 4      p VP                  4        F7  w  rEV F,  pSV,          pVf   \        W4      SV&   K   \        WV4       K.  	  K9  	  V # )F)Úrecurse)r   r¯   Únamed_parametersÚidÚappendÚitemsrG   Úsetattr)	rË   Úparams_to_tieÚnÚparamÚid_keyÚ_param_namesÚ
param_nameÚ_tied_paramsÚparam_init_fns	   &      €€r   Úparam_init_fn_tied_paramÚ7ensure_weights_retied.<locals>.param_init_fn_tied_param"  s«   ø€ ô $¤DÓ)ˆØ×/Ñ/¸Ð/Ö>‰HˆAÜ�%‹y˜LÖ(Øœb ›iÕ(×/Ñ/°Ö2ñ ?ñ ˜vÓ&ˆð %2×$7Ñ$7Ö$9Ñ ˆFÛ*�
Ø$ VÕ,�Ø’=ô ,3°6Ó+F�L Ó(ä˜F°Ö6ó +ñ %:ð ˆr   éÿÿÿÿ)rG   Úsplitr]   Úget_submodulerÑ   )
rÜ   r1   rÄ   Ú_tied_namesrƒ   rÚ   Úmodr×   rÝ   rÛ   s
   f&&      @r   Úensure_weights_retiedrä     s�   ù€ Ü˜%Ð!5°tÓ<€KßàÐð €LÛˆØ�z‰z˜#‹ˆØŸ8™8 D¨¨" IÓ.°°RµˆjØ×!Ñ! $Ó'ˆÜ˜Ó(ˆà"&ˆ”R˜“YÓñ ÷ñ ð2 $Ð#r   c                ód   € V ^8„  d   QhR\         P                  P                  R\        R\        /# )r�   r1   Úfull_sdrA   )ra   rÅ   rÆ   Údictr£   )r¤   s   "r   r¥   r¥   >  s/   € ÷ ]ñ ]´5·8±8·?±?ð ]ÌTð ]Ô`dñ ]r   c                óh  € ^ RI Hp ^ RIHpHp VP                  4       p/ pR p	R p
V P                  '       Ed   VP                  4        EF   w  r¼W²9  d(   \        RV R\        V4       R\        V4       R24      hW+,          pVP                  pVP                  4       P                  VP                  4      p\        WÕ4      '       d   VP                  4       pVP!                  V^ VP"                  P$                  R	7       V! WÞVP&                  4      pV	! VVV4      w  ppV
! VVV4      pV'       d   VP                  R
4      pWøV&   EK  	  MÏVP                  4        F»  w  r¼VP                  p\(        P*                  ! VP-                  4       VP                  VP.                  R7      pVP!                  V^ VP"                  P$                  R	7       V! VWìP&                  4      pV	! VVV4      w  ppV
! VVV4      pV'       d   VP                  R
4      pWøV&   K½  	  VP1                  VRR7       V# )au  
Loads the full state dict (could be only on rank 0) into the sharded model. This is done by broadcasting the
parameters from rank 0 to all other ranks. This function modifies the model in-place.

Args:
    accelerator (`Accelerator`): The accelerator instance
    model (`torch.nn.Module`):
        The model to load the state dict into, expected to be on meta device or a VRAM spike can occur
    full_sd (`dict`): The full state dict to load, can only be on rank 0
    cpu_offload (`bool`, defaults to `False`):
        If True, move sharded parameters to CPU after distribution. Required when FSDP CPU offloading is enabled.
N)ÚDTensorÚdistribute_tensorc                 ó¶  €  V P                  V4      p\        \        R4      pRpT;'       d    VP                  \        P                  8H  p	VP                  P                  '       d   V	'       g   VP                  pVRJ;'       d    VP                  4       V3#   \         d4    TP                  R ^4      w  rET P                  T4      p\	        Ye4      p LÄi ; i)rÉ   Úfloat8_e4m3fnN)Úget_parameter_or_bufferÚAttributeErrorÚrsplitrá   rG   Úhasattrra   Údtyperì   Úis_floating_pointÚis_contiguous)
r1   rÚ   Úempty_paramÚ	old_paramÚbase_param_nameÚlocal_param_nameÚ	submoduleÚis_torch_e4m3fn_availableÚcasting_dtypeÚis_param_float8_e4m3fns
   &&&       r   Ú_infer_parameter_dtypeÚ:fsdp2_load_full_state_dict.<locals>._infer_parameter_dtypeS  sÊ   € ð	=Ø×5Ñ5°jÓAˆIô %,¬E°?Ó$CÐ!ØˆØ!:×!gÐ!g¸{×?PÑ?PÔTY×TgÑTgÑ?gÐà×Ñ×.×.Ð.×7MØ%ŸO™OˆMà Ð$×BÐB¨×)@Ñ)@Ó)BÀMÐQÐQøô ô 	=à0:×0AÑ0AÀ#ÀqÓ0IÑ-ˆOØ×+Ñ+¨OÓ<ˆIÜ 	Ó<ŠIð		=ús   ‚B Â;CÃCc                 ób   € Ve   V P                  VR7      p V'       d   V P                  4       p V # )N)rñ   )ÚtoÚ
contiguous)ÚtensorÚto_contiguousrñ   s   &&&r   Ú_cast_and_contiguousÚ8fsdp2_load_full_state_dict.<locals>._cast_and_contiguouse  s.   € ØÒØ—Y‘Y U�YÓ+ˆFßØ×&Ñ&Ó(ˆFØˆr   zParameter 'zZ' found in sharded model state dict but missing from full state dict. Full state dict has z keys, sharded has z keys.)ÚsrcÚgroupÚcpu)rÄ   rñ   T)Úassign)Útorch.distributedre   Útorch.distributed.tensorré   rê   r0   r�   rÓ   ÚKeyErrorr­   Údevice_meshÚdetachrÿ   Údevice_typeÚ
isinstanceÚto_localÚ	broadcastr  ÚWORLDÚ
placementsra   ÚemptyÚsizerñ   r9   )ri   r1   ræ   rA   Údistré   rê   Úmeta_sharded_sdÚ
sharded_sdrü   r  rÚ   Úsharded_paramÚ
full_paramr  Úsharded_tensorr  rú   Úfull_tensors   &&&&               r   Úfsdp2_load_full_state_dictr  >  s'  € õ %ßCð ×&Ñ&Ó(€OØ€JòRò$ð ×"×"Ñ"Ø)8×)>Ñ)>×)@Ñ%ˆJØÔ(ÜØ! * ð .+Ü+.¨w«<¨.Ð8KÌCÐP_ÓL`ÐKaÐagðióð ð !Õ,ˆJØ'×3Ñ3ˆKØ#×*Ñ*Ó,×/Ñ/°×0GÑ0GÓHˆJÜ˜*×.Ò.ð (×0Ñ0Ó2�
Ø�N‰N˜:¨1°D·J±J×4DÑ4DˆNÔEÙ.¨zÈ×H`ÑH`ÓaˆNÙ+AØØØó,Ñ(ˆM˜=ñ
 2°.À-ÐQ^Ó_ˆNçØ!/×!2Ñ!2°5Ó!9�Ø%3�zÔ"ò3 *Að8 *9×)>Ñ)>Ö)@Ñ%ˆJØ'×3Ñ3ˆKÜŸ+š+ m×&8Ñ&8Ó&:À;×CZÑCZÐbo×buÑbuÔvˆKØ�N‰N˜;¨A°T·Z±Z×5EÑ5EˆNÔFÙ.¨{¸K×IaÑIaÓbˆNÙ+AØØØó,Ñ(ˆM˜=ñ
 2°.À-ÐQ^Ó_ˆNçØ!/×!2Ñ!2°5Ó!9�Ø%3�zÓ"ñ *Að" 
×Ñ˜*¨TÐÔ2Ø€Lr   c                óX   € V ^8„  d   QhR\         P                  P                  R\        /# )r�   r�   Úmapping)ra   r•   Ú	Optimizerrç   )r¤   s   "r   r¥   r¥   ž  s%   € ÷ 
ñ 
´·±×1FÑ1Fð 
ÔQUñ 
r   c                óÜ   € ^ RI Hp / pRW2&    V P                   F/  pVR,           Uu. uF  qQVP                  ,          NK  	  upVR&   K1  	  R# u upi   \         d    \	        R4      hi ; i)a’  
Switches the parameters of the optimizer to new ones (sharded parameters in usual case). This function modifies the
optimizer in-place.

Args:
    optimizer (`torch.optim.Optimizer`): Optimizer instance which contains the original model parameters
    mapping (`dict`): Mapping from the original parameter (specified by `data_ptr`) to the sharded parameter

Raises:
    KeyError:
        If a parameter in the optimizer couldn't be switched to its sharded version. This should never happen and
        indicates a bug. If we kept the original params instead of raising, the training wouldn't be numerically
        correct and weights wouldn't get updated.
)ré   Ú_local_tensorÚparamsz„A parameter in the optimizer couldn't be switched to its sharded version. This breaks the training. Please raise an issue on GitHub.N)r
  ré   Úparam_groupsÚdata_ptrr  )r�   r  ré   Úaccessor_mappingÚparam_groupÚps   &&    r   Ú!fsdp2_switch_optimizer_parametersr)  ž  s|   € õ 1àÐà /ÐÑð
Ø$×1Ô1ˆKØBMÈhÖBWÓ$XÑBW¸Q¨Q¯Z©Z×%8Ð%8ÑBWÑ$XˆK˜Ó!ó 2ùÚ$XøÜô 
ô ð Só
ð 	
ð
ús   ŽA ¨AÁ
A ÁA ÁA+c                óL   € V ^8„  d   QhR\         P                  P                  /# )r�   r1   rÌ   )r¤   s   "r   r¥   r¥   ½  s   € ÷ ñ ¤u§x¡x§¡ñ r   c                ó:  € ^ RI HpHp \        V P                  P
                  V4      p\        VRR7      RR  F^  w  rVV! V4      '       g   K  V! VRR7      pV P                  P
                  P                  '       d	   V! V4      pVP                  WW4       K`  	  V# )a  
Applies the activation checkpointing to the model.

Args:
    accelerator (`Accelerator`): The accelerator instance
    model (`torch.nn.Module`): The model to apply the activation checkpointing to

Returns:
    `torch.nn.Module`: The model with the activation checkpointing applied
)Úcheckpoint_wrapperÚoffload_wrapperT)Úreturn_fqnsNF)Úpreserve_rng_staterß   )	Ú;torch.distributed.algorithms._checkpoint.checkpoint_wrapperr,  r-  Úfsdp2_prepare_auto_wrap_policyrÁ   rI   r   Ú activation_checkpointing_offloadÚset_submodule)ri   r1   r,  r-  Úauto_wrap_policy_funcÚ
layer_nameÚlayerÚwrappeds   &&      r   Úfsdp2_apply_acr8  ½  s‘   € ÷ô
 ;¸;×;LÑ;L×;XÑ;XÐZ_Ó`Ðä:¸5ÈdÔSÐTWÐUWÓXÑˆ
Ù  ×'Ô'Ù(¨À5ÔIˆGØ× Ñ ×,Ñ,×M×MÐMñ *¨'Ó2�Ø×Ñ 
Ö4ñ Yð €Lr   c                óŽ   € V ^8„  d   QhR\         P                  P                  R\         P                  P                  R,          /# ©r�   r1   ÚreturnNrÌ   )r¤   s   "r   r¥   r¥   Ý  s/   € ÷ ñ œEŸH™HŸO™Oð ´·±·±À$Õ0Fñ r   c                ó  € \        V RR4      pV'       d   \        WR4      MT p\        V\        P                  P                  4      '       g   R# RpVP                  4        F#  w  rER\        V4      P                  9   g   K!  TpK%  	  V# )a  Find the final normalization layer before the output head.

The final norm is conventionally a direct child of the base model (e.g. `model.norm`
for Llama, `transformer.ln_f` for GPT-2), so we only scan the base model's direct
children. Returns the last norm found there, or None.
Úbase_model_prefixÚ NÚNorm)rG   r  ra   rÅ   rÆ   Únamed_childrenr}   Ú__name__)r1   Úbase_prefixÚ
base_modelÚ
final_normrR   rË   s   &     r   Ú_find_final_normrE  Ý  st   € ô ˜%Ð!4°bÓ9€Kß6A”˜¨TÔ2Àu€JÜ�j¤%§(¡(§/¡/×2Ò2ÙØ€JØ×.Ñ.Ö0‰	ˆØ”T˜&“\×*Ñ*Ö*ØŠJñ 1ð Ðr   c                ó€   € V ^8„  d   QhR\         P                  P                  R\         P                  P                  /# )r�   r1   r;  rÌ   )r¤   s   "r   r¥   r¥   ï  s.   € ÷ gñ g¬E¯H©H¯O©Oð gÄÇÁÇÁñ gr   c                óÆ  € ^ RI HpHpHp \	        W4      ;'       g*    \        V4      ;'       d    \	        VP                  V4      pV'       d   V# V P                  P                  pVP                  V4       \        V RR4      pRVP                  RVP                  RVP                  ;'       g    V! 4       RVe'   V\        V P                  P                   4      ,          MR/p\#        RR	4      '       d2   VP$                  e$   \'        VP$                  WP(                  4      VR
&   Rp	\+        4       p
VP-                  4        Fy  w  r¼VP.                  P0                  R8X  g   K"  Rp	VP2                  '       d   K8  VP5                  4       '       d   KP  VP7                  4       '       d   Kh  V
P9                  V4       K{  	  V
'       dv   \#        RR	4      '       dd   \+        VP;                  R
\+        4       4      4      pWÚ,          VR
&   V P<                  '       d$   \>        P@                  ! R\C        V
4       R24       V PD                  R8w  d×   V	'       gÏ   . pVP-                  4        Fy  w  r¼VP2                  '       g   K  VPF                  \H        PJ                  8w  g   K:  VPM                  V4       VPN                  PQ                  \H        PJ                  4      Vn'        K{  	  V P<                  '       d.   V'       d&   \R        PU                  R\C        V4       RV R24       VPW                  4       pVPX                  '       d¡   V	'       g™   \[        VRRR7      p\\        P^                  ! VPa                  4        UUu/ uF  w  ppVV9   g   K  VVbK  	  upp4      pVPQ                  \H        P(                  ! R4      4      p\c        VR4      '       d   VPe                  4        \g        Wa4      pVeC   \i        V4      RR   F0  pV! V4      '       g   K  \	        VV4      '       d   K'  V! V3/ VB  K2  	  \        VRR 4      ! 4       p\        VRR 4      ! 4       p\        VRR4      p\        VRR4      pVRJ;'       d    VVJ pV'       g    Ve   \	        VV4      '       g
   V! V3/ VB  \k        V4      pV'       d   VVV3pMVV3pV Uu. uF  pVf   K	  \	        VV4      '       d   K  VNK!  	  ppV'       d   V! V3/ / VCRR/CB  \	        W4      '       g8   VPm                  4        UUu/ uF  w  ppVR8w  g   K  VVbK  	  pppV! V3/ VB  VPX                  '       d1   V	'       g)   ^ RI H7p  \q        WV\	        VP                  V 4      R7       VPX                  '       d¦   V	'       gž   XPm                  4        Fg  w  p!p"V"PQ                  V P(                  4      p"RV!9   d(   V!Ps                  R^4      w  p#p$VPu                  V#4      p%MT!p$Tp%V%Pw                  V$V"RR7       Ki  	  \c        VR4      '       d   VPe                  4        V# u uppi u upi u uppi )!a
  Prepares the model for FSDP2 in-place. Also returns the model to avoid misuse of the original model.

Args:
    accelerator (`Accelerator`): The accelerator instance
    model (`torch.nn.Module`): The model to prepare

Returns:
    `torch.nn.Module`: Prepared model
)Ú
FSDPModuleÚMixedPrecisionPolicyÚfully_shardÚtorch_device_meshNÚreshard_after_forwardÚoffload_policyÚ	mp_policyÚmeshr·   z2.7.0Úignored_paramsFÚ
Params4bitTzFound zÑ non-floating frozen Params4bit. Excluding from FSDP2 sharding to prevent quant_state corruption.To enable memory-efficient sharding of 4-bit weights, setbnb_4bit_quant_storage to a floating dtype (e.g. bf16).ÚnozŒFSDP upcast of low precision parameters to fp32 (since mixed_precision != 'no') may affect the precision of model checkpoints. This effects z parameters: z...)rÏ   ÚfqnsÚmetaÚtie_weightsÚget_input_embeddingsc                  ó   € R # ©Nr   r   r   r   Ú<lambda>Ú%fsdp2_prepare_model.<locals>.<lambda>[  s   € Ár   Úget_output_embeddingsc                  ó   € R # rX  r   r   r   r   rY  rZ  \  s   € Á4r   Úweight)ÚCPUOffloadPolicy)rA   rÉ   )Ú
persistentrß   )<Útorch.distributed.fsdprH  rI  rJ  r  r   Ú	_orig_modrÁ   rI   Úset_auto_wrap_policyrG   rL  rA   Úmixed_precision_policyÚtupleÚparallelism_configÚfsdp_dim_namesr   Úignored_modulesÚget_parameters_from_modulesrÄ   ÚsetrÐ   Ú	__class__rA  Úrequires_gradrò   Ú
is_complexÚaddÚgetr�   ÚwarningsÚwarnr­   Úmixed_precisionrñ   ra   Úfloat32rÒ   Údatarÿ   r_   r`   r0   Úcpu_ram_efficient_loadingr   ÚcopyÚdeepcopyÚnamed_buffersrð   rU  r1  r   rE  rÓ   r^  r  rï   rá   Úregister_buffer)&ri   r1   rH  rI  rJ  Úis_type_fsdpÚfsdp2_pluginrO  Úfsdp2_kwargsÚmodel_has_params4bitÚincompatible_params4bitrƒ   r×   ÚignoredÚupcasted_paramsÚoriginal_sdÚnon_persistent_buffer_fqnsÚkÚvÚoriginal_non_persistent_buffersr4  rË   Úinput_embedÚoutput_embedÚinput_weightÚoutput_weightÚis_weights_tiedrD  Útail_modulesÚmÚtailÚroot_kwargsr^  ÚfqnÚbuffer_tensorÚ
parent_fqnÚlocal_buffer_nameÚparent_modules&   &&                                    r   Úfsdp2_prepare_modelr“  ï  s§  € ÷ UÑTä˜eÓ0÷ ð Ü˜5Ó!×MÐM¤j°·±À*Ó&Mð ÷ Øˆà×$Ñ$×0Ñ0€Là×%Ñ% eÔ,ä�;Ð 3°TÓ:€Dð 	  ×!CÑ!CØ˜,×2Ñ2à�\×8Ñ8×RÐRÑ<PÓ<RØÈdÒN^�”U˜;×9Ñ9×HÑHÓIÖJÐdhð€Lô ˜˜g×&Ò&¨<×+GÑ+GÒ+SÜ)DØ×(Ñ(¨%×1CÑ1Có*
ˆÐ%Ñ&ð !ÐÜ!›eÐØ×-Ñ-Ö/‰ˆð �?‰?×#Ñ# |Ö3Ø#'Ð ð ×'×'Ò'°%×2IÑ2I×2KÔ2KÐV[×VfÑVf×VhÔVhØ'×+Ñ+¨EÖ2ñ 0÷ Ô#3°D¸'×#BÒ#BÜ�l×&Ñ&Ð'7¼»Ó?Ó@ˆØ)0Õ)JˆÐ%Ñ&Ø×&×&Ð&Ü�MŠMØœÐ4Ó5Ð6ð 7Jð Jôð ×"Ñ" dÔ*×3GØˆØ ×1Ñ1Ö3‰KˆDØ×"×"Ò" u§{¡{´e·m±mÖ'CØ×&Ñ& tÔ,Ø"ŸZ™ZŸ]™]¬5¯=©=Ó9�–
ñ 4ð ×&×&Ð&¯?Ü�K‰Kð Ü # OÓ 4Ð5°]À?ÐBSÐSVðXôð ×"Ñ"Ó$€Kà×-×-Ð-×6Jô &@ÀÈtÐZ^Ô%_Ð"Ü*.¯-ª-Ø#×1Ñ1Ô3ÔWÑ3‘d�a˜°qÐ<VÑ7VŒTˆQ�ŠTÑ3ÒWó+
Ð'ð —‘œŸš fÓ-Ó.ˆô �5˜-×(Ò(Ø×ÑÔä:¸<ÓOÐØÒ(ä3°EÓ:¸3¸BÓ?ˆFÙ$ V×,Ô,´ZÀÈ
×5SÔ5SÙ˜FÑ3 lÔ3ñ @ô ˜%Ð!7¹ÔFÓH€KÜ˜5Ð"9¹<ÔHÓJ€LÜ˜;¨°$Ó7€LÜ˜L¨(°DÓ9€MØ"¨$Ð.×PÐP°<À=Ð3P€Oç˜{Ò6¼zÈ+ÐWa×?bÒ?bÙ�KÑ0 <Ò0ä! %Ó(€J÷
 Ø" K°Ð>‰à" LÐ1ˆÙ#ÓW‘|�! qŒA¼ZÈÈ:×=V�AˆA‘|€DÐWßÙ�DÑMÐL˜|ÐLÐ-DÀeÑLÒMä�e×(Ò(ð )5×(:Ñ(:Ô(<Ô]Ñ(<¡  1ÀÐE\Ñ@\”t�q˜!’tÑ(<ˆÑ]Ù�EÑ)˜[Ò)à×-×-Ð-×6Jõ 	<ä"Ø ¼ÀL×D\ÑD\Ð^nÓ9oõ	
ð ×-×-Ð-×6Jà"A×"GÑ"GÖ"IÑˆC�Ø)×,Ñ,¨[×-?Ñ-?Ó@ˆMà�cŒzØ03·
±
¸3ÀÓ0BÑ-�
Ð-Ø %× 3Ñ 3°JÓ ?‘à$'Ð!Ø %�à×)Ñ)Ð*;¸]ÐW\Ð)Ö]ñ #Jô  �5˜-×(Ò(Ø×ÑÔà€Lùó[ XùòH Xùó ^s*   ÎY
ÎY
ÓYÓYÓ0YÔ3YÕYc                ó²   € V ^8„  d   QhR\         P                  P                  R\        \         P                  P                  .\        3,          R,          /# r:  )ra   rÅ   rÆ   r   r£   )r¤   s   "r   r¥   r¥   ™  sC   € ÷ 3ñ 3¼¿¹¿¹ð 3ÌHÔV[×V^ÑV^×VeÑVeÐUfÔhlÐUlÕLmÐptÕLtñ 3r   c                ó¾  a a
€ ^ RI HpHp S P                  p\	        V\
        P                  4      '       d   VP                  pWCJ d†   \        VRR4      pVf   . p\        V4      pS P                  e   S P                  p\        4       o
V F2  p\        W4      pVf   \        RV R24      hS
P                  V4       K4  	  R V
3R llp	V	# WBJ d   R V 3R	 llp	V	# R# )
a¼  Prepares the auto wrap policy based on its type, done to mimic the behaviour of FSDP1 auto wrap policy.

Args:
    fsdp2_plugin (`FullyShardedDataParallelPlugin`):
        Instance of `FullyShardedDataParallelPlugin` containing the configuration options
    model (`torch.nn.Module`):
        The model to wrap

Returns:
    `Callable[[torch.nn.Module], bool] | None`:
        The auto wrap policy function to be applied to the model or `None`
)Úsize_based_auto_wrap_policyÚtransformer_auto_wrap_policyÚ_no_split_modulesNz+Could not find the transformer layer class z in the model.c                óX   € V ^8„  d   QhR\         P                  P                  R\        /# ©r�   rË   r;  ©ra   rÅ   rÆ   r£   )r¤   s   "r   r¥   Ú4fsdp2_prepare_auto_wrap_policy.<locals>.__annotate__¼  s&   € ÷ 	Fñ 	Fœ5Ÿ8™8Ÿ?™?ð 	F¬tñ 	Fr   c                 ó\   <€ S'       g   R # \        V RV 4      p \        V \        S4      4      # )FÚ_checkpoint_wrapped_module)rG   r  rd  )rË   Útransformer_cls_to_wraps   &€r   ÚpolicyÚ.fsdp2_prepare_auto_wrap_policy.<locals>.policy¼  s-   ø€ ß*Ùô ˜VÐ%AÀ6ÓJˆFÜ˜f¤eÐ,CÓ&DÓEÐEr   c                óX   € V ^8„  d   QhR\         P                  P                  R\        /# rš  r›  )r¤   s   "r   r¥   rœ  Æ  s&   € ÷ 	Cñ 	Cœ5Ÿ8™8Ÿ?™?ð 	C¬tñ 	Cr   c                 ób   <€ \        R  V P                  4        4       4      pVSP                  8„  # )c              3   ó@   "  € T F  qP                  4       x € K  	  R # 5irX  )Únumel)Ú.0r(  s   & r   Ú	<genexpr>ÚAfsdp2_prepare_auto_wrap_policy.<locals>.policy.<locals>.<genexpr>Ç  s   é € Ð#KÑ7J°!§G¡G§I IÓ7Jùs   ‚)ÚsumÚ
parametersÚmin_num_params)rË   Úmodule_num_paramsrz  s   & €r   r   r¡  Æ  s.   ø€ Ü #Ñ#K°v×7HÑ7HÔ7JÓ#KÓ KÐØ$ |×'BÑ'BÑBÐBr   )Útorch.distributed.fsdp.wrapr–  r—  Úauto_wrap_policyr  Ú	functoolsÚpartialÚfuncrG   r¯   Útransformer_cls_names_to_wrapri  r   r€   rm  )rz  r1   r–  r—  ÚfnÚno_split_modulesr²  Úlayer_classÚtransformer_clsr   rŸ  s   f&        @r   r1  r1  ™  sï   ù€ ÷ fà	×	&Ñ	&€Bä�"”i×'Ñ'×(Ò(Ø�W‰Wˆà	Ó)Ü" 5Ð*=¸tÓDÐØÒ#Ø!ÐÜ(,Ð-=Ó(>Ð%Ø×5Ñ5ÒAØ,8×,VÑ,VÐ)Ü"%£%Ðã8ˆKÜ8¸ÓLˆOØÒ&Ü Ð#NÈ{ÈmÐ[iÐ!jÓkÐkØ#×'Ñ'¨Ö8ñ	 9÷	Fð 	Fð  €Mð 
Ó	*÷	Cð 	Cð €Mñ r   c                 ó   € ^ RI Hp V! R/ V B # )z÷
Returns a `GradScaler` for FSDP2, as the current implementation of `get_grad_scaler` doesn't accept other args. We
need this as current `get_grad_scaler` accepts only `distributed_type` as arg, which doesn't differentiate between
FSDP1 and FSDP2
)Ú
GradScalerr   )Útorch.amp.grad_scalerr¸  )Úkwargsr¸  s   , r   Úget_fsdp2_grad_scalerr»  Ï  s   € õ 1áÑ˜ÑÐr   c                ó0   € V ^8„  d   QhR\         R\         /# )r�   Únamed_paramsr;  )rç   )r¤   s   "r   r¥   r¥   Ú  s   € ÷ ñ ¬4ð ´Dñ r   c                ó”  € V P                  4        UUu/ uF  w  rVP                  RR4      VbK  	  p ppV P                  4        UUu/ uF1  w  rVP                  R4      '       d   VP                  RR4      MTVbK3  	  p ppV P                  4        UUu/ uF  w  rVP                  RR4      VbK  	  p ppV # u uppi u uppi u uppi )a  Removes parameter name modifiers in order to map them back to their original names.

See huggingface/accelerate#3554 for more context.

Args:
    named_params (`dict`): The named parameters dictionary to canonicalize.

Returns:
    `dict`: The canonicalized named parameters dictionary
z._checkpoint_wrapped_moduler>  z
_orig_mod.z
._orig_mod)rÓ   r   Ú
startswith)r½  r‚  rƒ  s   &  r   Úfsdp2_canonicalize_namesrÀ  Ú  sÎ   € ð Q]×PbÑPbÔPdÔeÑPdÉÈ�A—I‘IÐ;¸RÓ@À!ÒCÑPd€LÑeàXd×XjÑXjÔXlôÙXlÑPTÐPQ q§|¡|°L×'AÒ'Aˆ�	‰	�, Ô#ÀqÈ!ÒKÑXlð ñ ð @L×?QÑ?QÔ?SÔTÑ?S±t°q�A—I‘I˜l¨BÓ/°Ò2Ñ?S€LÑTØÐùó fùóùó Us   ”B8Á7B>ÂCc                óÎ   € V ^8„  d   QhR\         \        \        P                  P                  ,          \
        3,          R\        \        P                  P                  ,          /# )r�   Úmodulesr;  )r	   r   ra   rÅ   rÆ   r¢   ri  Ú	Parameter)r¤   s   "r   r¥   r¥   í  sB   € ÷ ñ Ü”8œEŸH™HŸO™OÕ,¬cÐ1Õ2ðäŒ�‰×	Ñ	Õñr   c                ó¢  € V f   \        4       # . p\        V \        4      '       do   \        P                  ! V 4      p. pVP                  4        F@  w  rgVP                  V4      '       g   K  VP                  V4       VP                  V4       KB  	  Tp V  F+  pVP                  \        VP                  4       4      4       K-  	  \        V4      # )zâConverts modules to parameters where modules can be a string or list of torch.nn.Module

Args:
    modules (`Union[Iterable[torch.nn.Module], str]`): List of modules

Returns:
    `set[torch.nn.Parameter]`: List of parameters
)ri  r  r¢   ÚreÚcompileÚnamed_modulesÚ	fullmatchrÿ   rÒ   Úextendr¯   rª  )rÂ  r1   rÄ   rª  ÚregÚmapped_modulesrƒ   rË   s   &&&     r   rh  rh  í  sª   € ð ‚Ü‹uˆØ€Jä�'œ3×ÒÜ�jŠj˜Ó!ˆØˆØ!×/Ñ/Ö1‰LˆDØ�}‰}˜T×"Ô"Ø—	‘	˜&Ô!Ø×%Ñ% fÖ-ñ 2ð !ˆÛˆØ×Ñœ$˜v×0Ñ0Ó2Ó3Ö4ñ äˆz‹?Ðr   )FN)r   FT)r   T)T)TF)F)<ru  r¯  r   rÅ  r¼   ro  Úcollectionsr   Úcollections.abcr   Ú
contextlibr   Údataclassesr   Úpathlibr   Útypingr   r	   ra   Úloggingr
   Ú	constantsr   r   r   r   r   Úmodelingr   r   Úotherr   r   r   Úversionsr   rA  r_   r    r#   r4   r:   rJ   rt   r‰   r“   r›   r±   rÂ   rä   r  r)  r8  rE  r“  r1  r»  rÀ  rh  r   r   r   Ú<module>r×     sÍ   ðó Û Û 	Û 	Û Û Ý #Ý $Ý "Ý Ý ß "ã å  ß WÓ WÝ 3ß ?ß JÑ JÝ &ñ 
�HÓ	€ò:ò;ô"ô(1ò(ô"MCô`^ôBCQôLQ$÷h÷84õn+$÷\]õ@
õ>õ@õ$gõT3òl õ÷&r   