Ë
    ÄÓ^jY÷  ã                   ó|  — U d dl Z d dlZd dlZd dlZd dlmZmZmZ d dlm	Z	m
Z
mZ d dlmZ d dlmZmZmZ d dlZd dlmZ d dlmZ d dlmZ d dlmZmZmZmZmZm Z  d dl!m"Z" d d	l#m$Z$m%Z%m&Z'm(Z(m)Z)m*Z*m+Z+m,Z, d d
l-m.Z.m/Z/ d dl0m1Z1 d dl2m3Z3 d dl4m5Z5 d dl6m7Z8 d dl9m:Z: g d¢Z;dZ<dZ=dZ>dZ?e@eA   ZBe3ez  ej†                  z  eDz  eEz  eAz  ZFeFeGeF   z  eHeF   z  eIeAdf   z  ZJeIeAeJf   ZKeGeK   ZLeIeAeKeLz  f   ZM e@«       ZNe@e   eOd<   e j                   d„ «       ZQe
 G d„ d«      «       ZRe
 G d„ deR«      «       ZS	 	 	 dKdej¨                  deAdeAdeUd eUd!eBfd"„ZV G d#„ d$«      ZWdLd%„ZXddd&œdej¨                  d'eHej²                  j´                  d(f   d)eUd*e@ej¨                     dz  d+eRdz  d!eSfd,„Z[d-eIeAeJf   d.eMd/eSd!dfd0„Z\d1ej¨                  ej²                  j´                  z  d2eAd!efd3„Z]dej¨                  d/eSd!ej¼                  dz  fd4„Z_d5eIeAef   d/eSd!eIeAef   fd6„Z` ejÂ                  «       dej¨                  d/eSd!eIeAeJf   fd7„«       Zb ejÂ                  «       dej¨                  d5eIeAeJf   d/eSd!e5fd8„«       Zcd9ej²                  j´                  d!dfd:„Zdd5eMd!eIeAeJf   fd;„Zed9ej²                  j´                  d5eIeAeJf   d/eSd!eMfd<„Zf ejÂ                  «       dej¨                  d=eHej²                  j´                  d(f   d/eSd!eMfd>„«       Zgdej¨                  d9ej²                  j´                  d.eMd/eSd!eMf
d?„Zh ejÂ                  «       dej¨                  d=eHej²                  j´                  d(f   d5eMd/eSd!df
d@„«       Ziddd&œdej¨                  d*e@ej¨                     dz  d+eRdz  d!eIeAeJf   fdA„Zjddd&œdej¨                  d=ej²                  j´                  eej²                  j´                     z  d*e@ej¨                     dz  d+eRdz  d!eMf
dB„Zkddd&œdej¨                  d=ej²                  j´                  eej²                  j´                     z  d*e@ej¨                     dz  d+eRdz  d!eHeIeAeJf   eMf   f
dC„Zldej¨                  d5eIej¨                  eIeAeJf   f   eIeAeJf   z  d!eIeAeJf   fdD„ZmddEœdej¨                  d-eIeAeJf   d+eRdz  d!e5fdF„ZnddEœdej¨                  d=ej²                  j´                  eej²                  j´                     z  d.eMd+eRdz  d!df
dG„ZoddEœdej¨                  d=ej²                  j´                  eej²                  j´                     z  d-eIeAeJf   d.eMd+eRdz  d!e5fdH„ZpeddEœdej¨                  d+eRdz  d!dfdI„«       ZqeddEœdej¨                  d=eHej²                  j´                  d(f   d+eRdz  d!dfdJ„«       Zry)Mé    N)ÚCallableÚ	GeneratorÚIterable)ÚasdictÚ	dataclassÚfield)Úchain)ÚAnyÚcastÚno_type_check)ÚShardedTensor)Ú_broadcast_state_dictÚ_distribute_state_dictÚ_flatten_state_dictÚ_gather_state_dictÚ_offload_state_dict_to_cpuÚ_unflatten_state_dict)Ú_CHECKPOINT_PREFIX)ÚFullOptimStateDictConfigÚFullStateDictConfigÚFullyShardedDataParallelÚOptimStateDictConfigÚShardedOptimStateDictConfigÚShardedStateDictConfigÚStateDictConfigÚStateDictType)Ú._get_module_fsdp_state_if_fully_sharded_moduleÚFSDP_WRAPPED_MODULE)ÚHYBRID_SHARDING_STRATEGIES)ÚDTensor)Ú_IncompatibleKeys)ÚDistributedDataParallel)Útree_map_only)ÚFQNS_TÚPrimitiveTypeÚ	ValueTypeÚDictValueTypeÚListDictValueTypeÚOptimizerStateTypeÚStateDictOptionsÚget_model_state_dictÚget_optimizer_state_dictÚget_state_dictÚset_model_state_dictÚset_optimizer_state_dictÚset_state_dictÚ_flat_paramÚparam_groupsÚparamsÚstater&   Ú_patched_state_dictc               #   óÌ   K  — t        j                  «       } t        j                  «        	 d –— | rt        j                  «        y y # | rt        j                  «        w w xY w­w©N)ÚgcÚ	isenabledÚdisableÚenable)Ú
is_enableds    úr/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/distributed/checkpoint/state_dict.pyÚ_gc_contextr>   R   sD   è ø€ ä—‘“€JÜ‡J�J„LðÛáÜ�I‰I�Kð ø‰:Ü�I‰I�Kð üs   ‚)A$¬A °A$ÁA!Á!A$c                   ó‚   — e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	eed<   dZ
eed<   dZeed	<   dZeed
<   dZeed<   y)r*   ap  
    This dataclass specifies how get_state_dict/set_state_dict will work.

    - ``full_state_dict``: if this is set to True, all the tensors in the
      returned state_dict will be gathered. No ShardedTensor and DTensor
      will be in the returned state_dict.

    - ``cpu_offload``: offload all the tensors to cpu. To prevent CPU OOM, if
      ``full_state_dict`` is also true, then only the rank0 will get the
      state_dict and all other ranks will get empty state_dict.

    - ``ignore_frozen_params``: if the value is True, the returned state_dict
      won't contain any frozen parameters -- the ``requires_grad`` is False.
      The default value is False.

    - ``keep_submodule_prefixes`` (deprecated): when ``submodules`` is not None, this option
      indicates whether to keep the submodule prefixes from the state_dict keys.
      or example, if the submodule is ``module.pretrain`` and the full FQN of
      the parameter is ``pretrain.layer1.weight`` of the param. When this option
      is True, the parameter's key in the returned state_dict will be
      ``pretrain.layer1.weight``. If the options is False, the key will be
      ``layer1.weight``.
      Note that if ``keep_submodule_prefixes`` is False, there may be conflicted
      FQNs, hence there should be only one submodule in ``submodules``.

    - ``strict``: the ``strict`` option when ``set_state_dict`` calls
      model.load_state_dict().

    - ``broadcast_from_rank0``: when the option is True, rank0 should receive a
       full state_dict and will broadcast the tensors in the state_dict/
       optim_state_dict one by one to other ranks. Other ranks will receive
       the tensors and shard according to the local shards in the model and
       optimizer. ``full_state_dict`` must be set to True when using this option.
       This option currently only supports DTensor, not the legacy ShardedTensor.
    FÚfull_state_dictÚcpu_offloadÚignore_frozen_paramsTÚkeep_submodule_prefixesÚstrictÚbroadcast_from_rank0Úflatten_optimizer_state_dictÚ_fqn_modifiersÚdsd_fqn_modifiersN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r@   ÚboolÚ__annotations__rA   rB   rC   rD   rE   rF   rH   Ústr© ó    r=   r*   r*   ]   s_   … ñ"ðH "€O�TÓ!Ø€K�ÓØ!&Ð˜$Ó&Ø$(Ð˜TÓ(Ø€FˆDÓØ!&Ð˜$Ó&Ø).Ð  $Ó.Ø-Ð�sÔ-rQ   r*   c                   óX  — e Zd ZU  ee¬«      Zeeej                  z  e	ej                  z  f   e
d<    ee¬«      Zeeej                  z  e	ej                  z  f   e
d<    ee¬«      Zee   e
d<   dZee
d<   dZee
d<   ej$                  Zee
d<    ee¬«      Zeej0                     e
d	<   y
)Ú_StateDictInfo)Údefault_factoryÚfqn_param_mappingÚshared_params_mappingÚsubmodule_prefixesTÚhandle_modelÚhandle_optimÚfsdp_contextÚfsdp_modulesN)rI   rJ   rK   r   ÚdictrU   rO   ÚtorchÚTensorr$   rN   rV   ÚsetrW   rX   rM   rY   Ú
contextlibÚnullcontextrZ   r   Úlistr[   ÚnnÚModulerP   rQ   r=   rS   rS   �   sÃ   … ñ
 	˜dÔ#ð �tØˆe�l‰lÑØ�—‘Ñð	ñó $ñ 	˜dÔ#ð ˜4Øˆe�l‰lÑØ�—‘Ñð	ñó $ñ $)¸Ô#=Ð˜˜C™Ó=Ø€L�$ÓØ€L�$ÓØ'×3Ñ3€L�(Ó3Ù$)¸$Ô$?€L�$�r—y‘y‘/Ô?rQ   rS   ÚmodelÚnamerH   Úskip_ddp_prefixÚskip_compiler_prefixÚreturnc                 óê  — |j                  t        d«      }d|vr|hS |j                  d«      }g }| }t        |«      D �]  \  }}	t	        |t
        «      r5|	dk7  rt        d|	› d�«      ‚|j                  }|rŒ:|j                  |	«       ŒLt	        |t        «      r |t        |«      dz
  k  rW||dz      t        k(  rHdj                  |«      }
t        |t        «      }|
r|
› d�}
|j                  D �ch c]  }|
› |› �’Œ
 c}c S t        |t        «      }|	t        k7  sŒÞ|j                  |	«       t        ||	«      }Œüt	        |t         j"                  j$                  j&                  «      r7|	dk7  rt        d|	› d�«      ‚|j(                  }|r�ŒN|j                  |	«       �Œat+        ||«      r: t        ||«      «       j-                  |	«      x}rt+        ||«      rt        ||«      }|j                  |	«       |	t.        j0                  j                  j2                  k(  r|t        |«      dz
  k7  s�Œòt5        d	«      ‚t        ||	«      }�Œ dj                  |«      j                  t        d«      hS c c}w )
aá  
    This API is used to convert the name of a parameter to the FQNs. For FSDP
    without `use_orig_params`, the name of FlatParameter can be mapped to
    multiple original parameters. As a result, the return type of this function
    is `set[str]`.

    Args:
        module (nn.Module): the root model.
        name (str): the name
        skip_ddp_prefix (bool): whether to skip DDP's `module` prefix

    Returns:
        The canonical FQNs based on the model traversal.
    Ú ú.ÚmodulezExpected 'module', got 'ú'é   Ú	_orig_modzExpected '_orig_mod', got 'z-Expect `_extra_state` to be the last obj name)Úreplacer   ÚsplitÚ	enumerateÚ
isinstanceÚDDPÚAssertionErrorrm   ÚappendÚFSDPÚlenÚ_FLAT_PARAMÚjoinÚgetattrÚ_fqnsr   r]   Ú_dynamoÚ
eval_frameÚOptimizedModulerp   ÚhasattrÚgetrc   ÚmodulesÚ_EXTRA_STATE_KEY_SUFFIXÚRuntimeError)re   rf   rH   rg   rh   Ú	obj_namesÚfqn_obj_namesÚcurr_objÚiÚcurr_obj_nameÚprefixÚ
flat_paramÚfqnÚremoved_fqns                 r=   Ú	_get_fqnsr�   ž   sS  € ð. �<‰<Ô*¨BÓ/€DØ
�$�Øˆvˆà—
‘
˜3“€IØ€MØ€HÜ% iÓ0ó &<Ñˆˆ=Ü�h¤Ô$Ø Ò(Ü$Ð'?À¸ÈaÐ%PÓQÐQØ—‘ˆHÚ"Ø×$Ñ$ ]Õ3Ü˜¤$Ô'Ø”3�y“> AÑ%Ò%¨)°A¸±EÑ*:¼kÒ*IØŸ™ -Ó0�Ü$ X¬{Ó;�
ÙØ &˜x q˜\�FØ4>×4DÑ4DÖE¨S˜6˜( 3 %Ò(ÒEÒEÜ˜xÔ)<Ó=ˆHØÔ 3Ó3Ø×$Ñ$ ]Ô3Ü" 8¨]Ó;‘Ü˜¤%§-¡-×":Ñ":×"JÑ"JÔKØ Ò+Ü$Ð'BÀ=À/ÐQRÐ%SÓTÐTØ×)Ñ)ˆHÛ'Ø×$Ñ$ ]Ö3ô �xÐ!2Ô3Ø"F¤'¨(Ð4EÓ"FÓ"H×"LÑ"LØ!ó#ð �;ð ô ˜x¨Ô5Ü#*¨8°[Ó#A˜Ø× Ñ  Ô/Ø¤§
¡
× 1Ñ 1× IÑ IÒIØœ˜I›¨Ñ*Ô*Ü&Ð'VÓWÐWä" 8¨]Ó;’ðM&<ðP �H‰H�]Ó#×+Ñ+Ô,>ÀÓCÐDÐDùò7 Fs   Ã0I0c                   ó   — e Zd Zy)Ú_EXTRA_STATEN)rI   rJ   rK   rP   rQ   r=   r‘   r‘   ç   s   „ ØrQ   r‘   c              #   ó”   ‡‡‡K  — t        «       Šdt        j                  dt        dt        fˆˆˆfd„Š ‰| d«      E d {  –—†  y 7 Œ­w)Nrm   Úcurr_fqnri   c              3   ó´  •K  — ‰j                  | «       |r|› d�nd}| j                  «       D ]T  \  }}|‰v rŒt        | ‰«      r'| t        | ‰«      «       j	                  «       v r|d d }n|› |› �} ‰||«      E d {  –—†  ŒV t        | j                  d¬«      | j                  d¬«      «      D ]   \  }}|| j                  v rŒ|› |› �}||f–— Œ" t        | j                  dt        j                  j                  «      t        j                  j                  k7  r7|› t        j                  j                  j                  › �}|t!        «       f–— y y 7 Œ×­w)Nrl   rk   éÿÿÿÿF)ÚrecurseÚget_extra_state)ÚaddÚnamed_childrenr�   r|   Úvaluesr	   Únamed_buffersÚnamed_parametersÚ_non_persistent_buffers_setÚ	__class__rc   rd   r—   rƒ   rm   r„   r‘   )	rm   r“   rf   Ú	submoduleÚnew_fqnÚobjrH   r–   Úvisited_moduless	         €€€r=   r–   z+_iterate_valid_model_state.<locals>.recurseî   sr  øè ø€ Ø×Ñ˜FÔ#á%-�h�Z˜q‘>°2ˆØ%×4Ñ4Ó6ò 	3‰OˆD�)Ø˜OÑ+Øô ˜Ð 1Ô2ØÐ>œG FÐ,=Ó>Ó@×GÑGÓIÑIð # 3 B˜-‘à%˜J t fÐ-�Ù˜y¨'Ó2×2Ñ2ð	3ô Ø× Ñ ¨Ð Ó/°×1HÑ1HÐQVÐ1HÓ1Wó
ò 	‰IˆD�#ð �v×9Ñ9Ñ9ØØ!˜
 4 &Ð)ˆGØ˜3�,Óð	ô �F×$Ñ$Ð&7¼¿¹×9RÑ9RÓSÜ�y‰y×(Ñ(ò)ð "˜
¤2§:¡:×#4Ñ#4×#LÑ#LÐ"MÐNˆGØœ<›>Ð)Ó)ð	)ð 3ús   ƒA;EÁ>EÁ?CErk   )r_   rc   rd   rO   r   )re   rH   r–   r¢   s    `@@r=   Ú_iterate_valid_model_stater£   ë   s?   úè ø€ Ü&)£e€Oð *œŸ	™	ð  *¬Sð  *´Y÷  *ñD �u˜bÓ!×!Ò!ús   …;AÁ AÁA)Ú
submodulesÚoptionsÚoptims.Ú
optim_onlyr¤   r¥   c                ó  — |rt        j                  dt        d¬«       |r|st        d«      ‚|xs
 t	        «       }i }i }t        | «      D ]—  \  }}t        |t        «      rŒt        | |«      }	|j                  |«      }
|
�2t        t        t           ||   «      j                  |	«       ||   ||<   n|	j                  «       ||<   |	D ]  }
t        |t        «      rŒ|||
<   Œ Œ™ t        |j!                  «       «      D ])  \  }}|D ]  }
t        t"        j$                  |«      ||
<   Œ! Œ+ t        «       }|ret        |«      }| j'                  «       D ]G  \  }}||vrŒt        | |«      }	t)        |	«      dk7  rt+        d«      ‚|j                  d„ |	D «       «       ŒI |j,                  r|j.                  st1        d«      ‚t3        j4                  | «      }|rÚ|j.                  rat7        |j8                  |j8                  ¬	«      }t;        |j8                  |j8                  xs |j,                  ¬	«      }t<        j>                  }n<tA        |j8                  ¬
«      }tC        |j8                  ¬
«      }t<        jD                  }tF        jH                  d„ «       }tK        jL                  || |||¬«      }ntF        jN                  }tQ        di tS        |«      ¤||||t        t        tT        jV                     |«      | t)        |«      dkD  dœ¤ŽS )zW
    Verify the model and options passed by the user and generates _StateDictInfo.
    z¼Getting submodules only model/optim state_dict is deprecated and will be removed in 2.5. This feature can be achieved by manually filtering out the state_dict returned from get_state_dict.é   ©Ú
stacklevelz;Optimizers are not passed in but optim_only is set to True.ro   z)Submodule FQN should only have 1 instancec              3   ó&   K  — | ]	  }|› d �–— Œ y­w)rl   NrP   )Ú.0r�   s     r=   ú	<genexpr>z"_verify_options.<locals>.<genexpr>L  s   è ø€ Ò%@°C¨¨¨Q¤iÑ%@ùs   ‚z?full_state_dict must be True when broadcast_from_rank0 is True.)Úoffload_to_cpuÚ
rank0_only)r¯   c              3   óú   K  — t        j                  «       5  t        j                  ddt        ¬«       t	        j
                  | |||¬«      5  d –— d d d «       d d d «       y # 1 sw Y   ŒxY w# 1 sw Y   y xY w­w)NÚignorezFSDP.state_dict_type)ÚmessageÚcategory©rm   Ústate_dict_typeÚstate_dict_configÚoptim_state_dict_config)ÚwarningsÚcatch_warningsÚfilterwarningsÚFutureWarningrx   r¶   rµ   s       r=   Ú$fsdp_state_dict_type_without_warningz=_verify_options.<locals>.fsdp_state_dict_type_without_warningj  sy   è ø€ ô ×(Ñ(Ó*ñ 
Ü×'Ñ'ØÐ&<Ä}õô ×)Ñ)Ø!Ø$3Ø&7Ø,Cô	ñ ó ÷÷	
ð 
÷ð ú÷	
ð 
üs4   ‚A;—6A/ÁA#ÁA/Á	A;Á#A,	Á(A/Á/A8Á4A;rµ   r   )rU   rV   rW   rZ   r[   rX   rY   rP   ),r¹   Úwarnr¼   r…   r*   r£   rt   r‘   r�   r‚   r   r_   rO   ÚupdateÚcopyrb   Úitemsr]   r^   Únamed_modulesry   rv   rE   r@   Ú
ValueErrorrx   r[   r   rA   r   r   ÚFULL_STATE_DICTr   r   ÚSHARDED_STATE_DICTr`   ÚcontextmanagerÚ	functoolsÚpartialra   rS   r   rc   rd   )re   r¦   r§   r¤   r¥   rU   rV   rf   ÚparamÚfqnsr�   Úparam_Úfqns_rW   rm   r[   r·   r¸   r¶   r½   rZ   s                        r=   Ú_verify_optionsrÍ     s#  € ñ Ü�‰ðIô Øõ	
ñ ™&ÜØIó
ð 	
ð Ò+Ô)Ó+€GàKMÐØOQÐÜ1°%Ó8ò /‰ˆˆeÜ�eœ\Ô*Øä˜ Ó%ˆØ×#Ñ# EÓ*ˆØˆ?Ü””S‘Ð,¨UÑ3Ó4×;Ñ;¸DÔAØ+<¸UÑ+CÐ! %Ò(ð (,§y¡y£{Ð˜eÑ$Øò 	/ˆCÜ˜e¤\Õ2Ø).Ð! #Ò&ñ	/ð/ô  Ð3×9Ñ9Ó;Ó<ò D‰ˆ�Øò 	DˆCÜ)-¬e¯l©l¸FÓ)CÐ! #Ò&ñ	DðDô $'£5ÐÙÜ˜“_ˆ
Ø!×/Ñ/Ó1ò 	A‰LˆD�&Ø˜ZÑ'ØÜ˜U DÓ)ˆDÜ�4‹y˜AŠ~Ü$Ð%PÓQÐQØ×%Ñ%Ñ%@¸4Ô%@Õ@ð	Að ×#Ò#¨G×,CÒ,CÜØMó
ð 	
ô ×$Ñ$ UÓ+€Lñ à×"Ò"Ü 3Ø&×2Ñ2¸w×?RÑ?Rô!Ðô '?Ø&×2Ñ2Ø#×/Ñ/ÒO°7×3OÑ3Oô'Ð#ô ,×;Ñ;‰Oä 6Ø&×2Ñ2ô!Ðô 'BØ&×2Ñ2ô'Ð#ô ,×>Ñ>ˆOä	×	"Ñ	"ñ	ó 
#ð	ô$ !×(Ñ(Ø0ØØ+Ø/Ø$;ô
‰ô "×-Ñ-ˆäñ 	Ü
�‹/ð	à+Ø3Ø-Ø!Üœ$œrŸy™y™/¨<Ó8Ø#�^Ü˜&“k A‘oó	ð 	rQ   Úmodel_state_dictÚoptim_state_dictÚinfoc                 ó  — |j                   D ]  }t        |«      }|�Œt        d«      ‚ |j                  rk| si|j                  s]|j
                  sQ|j                  r|j                  s9|j                  r-|j                  s!t        dt        j                  «       ›d�«      ‚|j                  r4|s2|j                  r|j                  s|j                  st        d|› �«      ‚| D ]  }t        |v sŒt        |› dt        › d�«      ‚ y )Nz)Expected a fsdp_state with a fsdp module.z}The option indicates that model state_dict is required to save or load, but model state_dict is empty.rank = dist.get_rank()=rl   zgThe option indicates that model state_dict is required to save, or load but optim state_dict is empty. z
 contains z6. This can happen if the model is not the root module.)r[   r   rv   rX   rW   rB   rA   r@   rD   rE   r…   ÚdistÚget_rankrY   rz   )rÎ   rÏ   rÐ   rm   Ú
fsdp_stateÚkeys         r=   Ú_verify_state_dictrÖ   “  s  € ð
 ×#Ñ#ò NˆÜCÀFÓKˆ
ØÑÜ Ð!LÓMÐMðNð 	×ÒÙ Ø×'Ò'Ø×)Ò)Ø×!Ò! d×&:Ò&:Ø�KŠKØ×)Ò)äð'ä—m‘m“oÐ' qð*ó
ð 	
ð ×Òá Ø×%Ò%¨$×*>Ò*>Ø×.Ò.äð:Ø:JÐ9KðMóð ð
  ò ˆÜ˜#ÒÜØ�%�z¤+ ð /*ð *óð ñrQ   r¡   Úapic                 ó„   — t        | |«      }|t        v r+t        j                  t        | j                  |«      | ¬«      }|S )N)Úself)r|   r5   rÇ   rÈ   rž   )r¡   r×   Úcalls      r=   Ú_state_dict_fnrÛ   Á  s9   € Ü�3˜Ó€DØÔ"Ñ"Ü× Ñ ¤¨¯©¸Ó!<À3ÔGˆØ€KrQ   c                 óâ   — t        | t        «      r| }n+|j                  rt        t        |j                  d   «      }ny |j                  t
        v ry |j                  }t        |t        «      ry |S )Nr   )rt   rx   r[   r   Úsharding_strategyr   Úprocess_groupÚtuple)re   rÐ   Úfsdp_modulerÞ   s       r=   Ú_get_fsdp_process_grouprá   È  sf   € ô �%œÔØ‰Ø	×	Ò	Üœ4 ×!2Ñ!2°1Ñ!5Ó6‰àà×$Ñ$Ô(BÑBØà×-Ñ-€MÜ�-¤Ô'ØØÐrQ   Ú
state_dictc                 óØ   — |j                   rF|j                  rt        j                  j	                  «       sdnd}t        | |j                  |¬«      S |j                  rt        | «      S | S )NrP   )r   )rA   Ú
ranks_only)r@   rA   r]   ÚdistributedÚis_initializedr   r   )râ   rÐ   rä   s      r=   Ú_maybe_full_or_cpu_state_dictrç   Û  sn   € ð ×Òð ×$Ò$¬E×,=Ñ,=×,LÑ,LÔ,Nñ àð 	ô
 "Ø D×$4Ñ$4Àô
ð 	
ð 
×	Ò	Ü)¨*Ó5Ð5àÐrQ   c           	      óf  — |j                   si S |j                  «       5   t        | d«      «       }d d d «       t        j	                  «       «      D ]‹  }t        | |«      }t        |«      dk7  rt        d|› dt        |«      › d|› �«      ‚t        t        |«      «      }||k7  sŒTdt        fd„} |||«      st        d|› d	|› �«      ‚|j                  |«      ||<   Œ� |j                  rYi }|D ]P  }|j                  D ]?  }|j                  |«      sŒ|j                  r	||   ||<   Œ*|t        |«      d  }	||   ||	<   ŒA ŒR |}|j                   rI| j#                  «       D ]6  \  }}
|
j$                  rŒt        | |«      }|D ]  }|j                  |«       Œ Œ8 t'        ||«      S # 1 sw Y   �ŒwxY w)
Nrâ   ro   úExpected 1 FQN for key 'ú', got z: ri   c                 ó  — t        |«      t        | «      k\  ry|j                  d«      }| j                  d«      }d}t        |«      D ]:  \  }}|||   k(  r'|dz  }|t        |«      k(  sŒ"|t        |«      dz
  k(  c S |dv rŒ: y y)NFrl   r   ro   )rm   rp   T)ry   rr   rs   )rÕ   r�   Ú	fqn_splitÚ	key_splitÚfqn_idxÚkey_idxÚkey_names          r=   Úverifyz%_get_model_state_dict.<locals>.verify  s—   € Ü�s“8œs 3›xÒ'Ø ØŸI™I c›N�	ØŸI™I c›N�	Ø�Ü)2°9Ó)=ò %Ñ%�G˜XØ 9¨WÑ#5Ò5Ø 1™˜Ø"¤c¨)£nÓ4Ø#*¬c°)«n¸qÑ.@Ñ#@Ò@Ø!Ð%<Ñ<Ø á$ð%ð rQ   zAn unexpected key, z, exists. FQN is )rX   rZ   rÛ   rb   Úkeysr�   ry   rv   ÚnextÚiterrM   r…   ÚpoprW   Ú
startswithrC   rB   rœ   Úrequires_gradrç   )re   rÐ   râ   rÕ   rÊ   r�   rñ   Únew_state_dictr‹   r    rÉ   s              r=   Ú_get_model_state_dictrù   í  sâ  € ð ×ÒØˆ	à	×	Ñ	Ó	ñ ;Ø8”^ E¨<Ó8Ó:ˆ
÷;ô �J—O‘OÓ%Ó&ò 2ˆÜ˜ Ó$ˆÜˆt‹9˜Š>Ü Ø*¨3¨%¨w´s¸4³y°kÀÀDÀ6ÐJóð ô ”4˜“:ÓˆØ�#‹:ð¤Dó ñ" ˜#˜sÔ#Ü"Ð%8¸¸Ð=NÈsÈeÐ#TÓUÐUØ(Ÿn™n¨SÓ1ˆJ�sŠOð=2ð@ ×ÒØ/1ˆàò 	>ˆCØ×1Ñ1ò >�Ø—~‘~ fÔ-ØØ×/Ò/Ø*4°S©/�N 3Ò'à!¤# f£+ -Ð0�GØ.8¸©o�N 7Ò+ñ>ð	>ð $ˆ
à× Ò Ø×0Ñ0Ó2ò 	$‰JˆC�Ø×"Ò"ØÜ˜U CÓ(ˆDØò $�Ø—‘˜sÕ#ñ$ð		$ô )¨°TÓ:Ð:÷s;ñ ;ús   ŸF&Æ&F0c           	      ó’  — |j                   r|s|j                  st        i i «      S i }t        | |j                  «      D ]«  \  }}t        | ||j                  «      }t        | ||j                  dd¬«      }t        ||«      D ]f  \  }}	|j                  rt        j                  «       dk(  r9||	k7  r4|j                  |d «      }
|
€|j                  rt        d|› d�«      ‚|
||	<   |||	<   Œh Œ­ d}|j                  s|j                  �rnt        «       }|j                  «       D ]G  }t        j                   |«      sŒ|j#                  «       dkD  sŒ-|j%                  |j&                  «       ŒI t        j&                  d«      |v r&|j)                  t        j&                  d«      «       d}t+        |«      dk(  r.|j%                  t        j,                  j/                  «       «       nt+        |«      dkD  rt1        d	«      ‚|j                  r3t3        |||j                  «       |j                  |j4                  ¬
«       n(|j                  rt7        |||j                  «       ¬«       |j9                  |«       |j;                  «       5  t=        t         t?        | d«      ||j                  |¬«      «      cd d d «       S # 1 sw Y   y xY w)NF)rg   rh   r   zMissing key: rl   ÚmetaTro   zMultiple devices found)ÚdevicerD   rA   ©rü   Úload_state_dict)râ   rD   Úassign) rX   rE   r!   r£   rH   r�   ÚziprÒ   rÓ   rõ   rD   r…   r@   r_   rš   r]   Ú	is_tensorÚdimr˜   rü   Úremovery   Údistributed_c10dÚ_get_pg_default_devicerÃ   r   rA   r   r¿   rZ   r   rÛ   )re   râ   rÐ   Úlocal_state_dictrÕ   ÚvaluerÊ   Úfqns_with_prefixr�   Úfqn_with_prefixÚ
load_valuerÿ   Údevicess                r=   Ú_load_model_state_dictr  0  sq  € ð ×Ò¡Z¸×8QÒ8QÜ   RÓ(Ð(àÐÜ0°¸×8NÑ8NÓOò 6‰
ˆˆUÜ˜  T×%;Ñ%;Ó<ˆÜ$ØØØ×"Ñ"Ø!Ø!&ô
Ðô %(¨Ð.>Ó$?ò 
	6Ñ ˆC�à×-Ò-´·±³ÀAÒ1EØ˜Ò(Ø'Ÿ^™^¨C°Ó6�
ØÐ%Ø—{’{Ü*¨]¸3¸%¸qÐ+AÓBÐBà2<�J˜Ñ/Ø05Ð˜_Ò-ñ
	6ð6ð, €FØ× Ò  D×$8Ó$8Ü“%ˆØ%×,Ñ,Ó.ò 	*ˆEÜ�‰˜uÕ%¨%¯)©)«+¸«/Ø—‘˜EŸL™LÕ)ð	*ô
 �<‰<˜Ó 7Ñ*Ø�N‰Nœ5Ÿ<™<¨Ó/Ô0ØˆFÜˆw‹<˜1ÒØ�K‰Kœ×-Ñ-×DÑDÓFÕGÜ�‹\˜AÒÜÐ5Ó6Ð6à×$Ò$Ü!ØØ Ø—{‘{“}Ø—{‘{Ø ×,Ñ,öð ×!Ò!Ü" :Ð/?ÈÏÉËÕVØ×ÑÐ*Ô+à	×	Ñ	Ó	ñ 
ÜÜØ4ŒN˜5Ð"3Ó4Ø%¨d¯k©kÀ&ôó
÷
÷ 
ò 
ús   Ê-J=Ê=KÚoptimc                 óh  — | j                   ry| j                  D ]  }|t           D ]  }|j                  €Œ  y Œ! | j                  D ]7  }|t           D ])  }|j                  sŒt        j                  |«      |_        Œ+ Œ9 g }| j                  D ]R  }d|v sŒ|j                  |d   «       t        |d   t
        j                  «      rt        j                  d«      nd|d<   ŒT | j                  d¬«       | j                  D ]  }d|v sŒ|j                  d«      |d<   Œ | j                  d¬«       y)zH
    Initialize optim states by calling the step() with zero grads.
    NÚlrg        )Úclosurer   T)Úset_to_none)r4   r2   Ú_PARAMSÚgradr÷   r]   Ú
zeros_likerw   rt   r^   ÚtensorÚsteprõ   Ú	zero_grad)r  Úparam_grouprÉ   Úlrss       r=   Ú_init_optim_stater  u  sB  € ð ‡{‚{àð ×)Ñ)ò ˆØ ¤Ñ)ò 	ˆEØ�z‰zÑ%Úñ	ðð
 ×)Ñ)ò 5ˆØ ¤Ñ)ò 	5ˆEØ×"Ó"Ü"×-Ñ-¨eÓ4�•
ñ	5ð5ð €CØ×)Ñ)ò ˆØ�;ÒØ�J‰J�{ 4Ñ(Ô)ô ˜k¨$Ñ/´·±Ô>ô —‘˜SÔ!àð ˜Òðð 
‡J�J�t€JÔð ×)Ñ)ò +ˆØ�;ÒØ #§¡¨£
ˆK˜Òð+ð 
‡O�O €OÕ%rQ   c           
      ó<  ‡	‡
— dt         t        t        f   dt        dt         t        t        f   fˆ	ˆ
fd„Š	d„ Š
i }t	        t
        | t           «      j                  «       D ]C  \  }}t        › d|› �}|j                   ‰	t	        t         t        t        f   |«      |«      «       ŒE t	        t        | t           «      D ]\  }|j                  t        «      }t	        t        t           |«      D ]+  }|j                  «       D ]  \  }}||t        › d|› d|› �<   Œ Œ- Œ^ |S )a3  
    This API flattens the optimizer state_dict to support optimizer resharding for
    MPMD, e.g., pipeline parallelism.

    Without the API, the original optimizer state_dict looks like:
    {
        "state": {
            "layer1.weight": {
                "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor
            },
            "layer2.weight": {
                "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor
            },
        },
        "param_groups": [
            {
                "lr": 0.0,
                "betas": (0.9, 0.95), ...,
                "params": ["layer1.weight", "layer2.weight"]
            }
        ]
    }

    With this API, the optimizer state_dict looks like:
    {
        "state.layer1.weight.step": 10,
        "state.layer2.weight.step": 10,
        "state.layer1.weight.exp_avg": SomeTensor,
        "state.layer2.weight.exp_avg": SomeTensor,
        "state.layer1.weight.exp_avg_sq": SomeTensor,
        "state.layer2.weight.exp_avg_sq": SomeTensor,
        "param_groups.layer1.weight.lr": 0.1,
        "param_groups.layer2.weight.lr": 0.1,
        "param_groups.layer1.weight.betas": (0.9, 0.95),
        "param_groups.layer2.weight.betas": (0.9, 0.95),
    }

    The "state" section supports arbitrary levels of nesting for optimizers like Shampoo.
    Únested_dictr‹   ri   c                 óÔ   •— i }| j                  «       D ]Q  \  }}t        |«      }|r|› d|› �n|}t        |t        «      r|j	                   ‰||«      «       ŒE ‰|«       |||<   ŒS |S )a  
        Recursively flatten a nested dictionary with dot-separated keys.

        Args:
            nested_dict: The dictionary to flatten
            prefix: The prefix to prepend to all keys

        Returns:
            Flattened dictionary with dot-separated keys
        rl   )rÁ   rO   rt   r\   r¿   )	r  r‹   Ú	flattenedrÕ   r  Ústr_keyÚfull_keyÚ_flatten_state_nested_dictÚ_raise_if_type_not_supporteds	          €€r=   r!  z=_flatten_optim_state_dict.<locals>._flatten_state_nested_dictÈ  s   ø€ ð +-ˆ	à%×+Ñ+Ó-ò 	,‰JˆC�ä˜#“hˆGÙ06˜&˜  7 )Ñ,¸GˆHä˜%¤Ô&à× Ñ Ñ!;¸EÀ8Ó!LÕMñ -¨UÔ3Ø&+�	˜(Ò#ð	,ð ÐrQ   c                 óˆ   — t        | t        j                  t        t        t
        f«      st        dt        | «      › d�«      ‚y )Nz[Flattening optimizer state_dict only supports tensor, int, float, dict states now. Type is rl   )rt   r]   r^   ÚintÚfloatr\   ÚNotImplementedErrorÚtype)Úvs    r=   r"  z?_flatten_optim_state_dict.<locals>._raise_if_type_not_supportedæ  s@   € Ü˜!œeŸl™l¬C´¼Ð=Ô>Ü%ðä ›7˜) 1ð&óð ð ?rQ   rl   )r\   rO   r
   r&   r   r'   Ú_STATErÁ   r¿   r(   Ú_PGrõ   r  rb   )râ   Úretr�   r4   Ústate_prefixr  rÊ   Úkr(  r!  r"  s            @@r=   Ú_flatten_optim_state_dictr.  Ÿ  s   ù€ ðRÜœ#œs˜(‘^ðÜ-0ðä	Œc”9ˆnÑ	öò<ð !#€Cô œ=¨*´VÑ*<Ó=×CÑCÓEò 
‰
ˆˆUÜ ˜  3 %Ð(ˆØ�
‰
Ù&¤t¬D´´c°©N¸EÓ'BÀLÓQõ	
ð
ô Ô-¨z¼#©Ó?ò ,ˆØ�‰œwÓ'ˆÜœœS™	 4Ó(ò 	,ˆCØ#×)Ñ)Ó+ò ,‘��1Ø*+�”s�e˜1˜S˜E  1 #Ð&Ò'ñ,ñ	,ð,ð €JrQ   c                 ó  — dt         dt        t         t        f   dt        t         t        f   fd„}i }g }t        |t        |i}| j
                  D �]®  }|j                  t        g i«       |t           D �]  }|j                  |   D ]ó  }	|	|j                  v r)d}
|D ]!  }|t        k(  rŒt        › d|	› d|› �}||v rd}
 n nd}
|
sŒ?|d   t           }t        |t        «      st        d	t        |«      › �«      ‚|j                  |	«       |j                  sŒ�i ||	<   | j                  |   D ]M  }t        › d|	› d|› �}||vr  |||«      }|t!        t"        ||	   «      |<   Œ5||   t!        t"        ||	   «      |<   ŒO Œõ �Œ t!        t        t            |d   t           «      d
   }|D ]V  }|t        k(  rŒ|t        › d|› d|› �   }||d   vr	||d   |<   Œ.|d   |   |k7  sŒ:t%        d|› d|› d|› d|d   |   › d�	«      ‚ �Œ± |S )zý
    This API unflattens the state_dict generated by _flatten_optim_state_dict().
    Supports arbitrary levels of nesting in the state section through recursive reconstruction.

    See the docstring of _flatten_optim_state_dict() for more detail.
    Úflattened_keyÚflattened_dictri   c                 ó  — | › d�}i }|j                  «       D ]q  \  }}|j                  |«      sŒ|t        |«      d }|j                  d«      }|}|dd D ])  }	|	|vri ||	<   t	        ||	   t
        «      st        ‚||	   }Œ+ |||d   <   Œs |S )zØ
        Reconstructs a potentially nested value from flattened keys.
        For non-nested values, returns the value directly.
        For nested values, reconstructs the nested structure with string keys.
        rl   Nr•   )rÁ   rö   ry   rr   rt   r\   rv   )
r0  r1  r‹   r  rÕ   r  Úremaining_keyÚpartsÚcurrentÚparts
             r=   Ú_reconstruct_nested_dictz=_unflatten_optim_state_dict.<locals>._reconstruct_nested_dict  sË   € ð "�? !Ð$ˆà&(ˆð )×.Ñ.Ó0ò 	'‰JˆC�ð —>‘> &Ô)àð  ¤ F£ Ð.ˆMð "×'Ñ'¨Ó,ˆEà!ˆGð ˜c˜r˜
ò (�à˜wÑ&Ø$&�G˜D‘Mä! '¨$¡-´Ô6Ü(Ð(Ø! $™-‘ð(ð "'ˆG�E˜"‘IÒð;	'ð@ ÐrQ   Frl   Tr•   úExpected list, got r   zaAll the parameters in the same parameter group should have the same saved param_group value. But z is z while other(s) is )rO   r\   r&   r)  r*  r2   rw   r  rU   rV   rt   rb   rv   r'  r÷   r4   r   r'   r…   )r  râ   rÐ   r7  r4   Úpg_stateÚ
return_osdr  rÉ   r�   Ú	in_paramsr-  Úflatten_keyr3   Ú
state_nameÚflattened_state_keyÚreconstructed_valueÚfirst_param_fqnr  s                      r=   Ú_unflatten_optim_state_dictrA    s£  € ð0Üð0Ü,0´´i°Ñ,@ð0ä	Œc”9ˆnÑ	ó0ðd €EØ"$€HÜ&,¨e´S¸(Ð%C€Jà×)Ñ)ó AˆØ�‰œ "˜Ô&Ø ¤Ñ)ó 1	ˆEØ×-Ñ-¨eÑ4ò 0�ð ˜$×4Ñ4Ñ4Ø %�IØ(ò ˜Ø¤š<Ø$Ü),¨¨Q¨s¨e°1°Q°CÐ&8˜Ø&¨*Ñ4Ø(,˜IÙñð !%�Iá Øà! "™¤gÑ.�Ü! &¬$Ô/Ü(Ð+>¼tÀF»|¸nÐ)MÓNÐNØ—‘˜cÔ"ð ×*Ò*Øð  ��c‘
Ø"'§+¡+¨eÑ"4ò �JÜ-3¨H°A°c°U¸!¸J¸<Ð*HÐ'à*°*Ñ<á.FØ/°ó/Ð+ð
 0ô œ]¨E°#©JÓ7¸
ÒCð GQØ/ñGœœ]¨E°#©JÓ7¸
ÒCñò?0ð1	ôf œt¤C™y¨(°2©,´wÑ*?Ó@ÀÑCˆØò 	ˆAØ”GŠ|ØØ¤#  a¨Ð'8¸¸!¸Ð=Ñ>ˆEØ˜ ™Ñ$Ø"'�˜‘˜Q’Ø˜"‘˜a‘ EÓ)Ü"ð=Ø=LÐ<MÈQÈqÈcð RØ˜Ð 3°H¸R±LÀ±OÐ3DÀAðGóð ò	ðmAðF ÐrQ   Ú
optimizersc                 ó*  — |j                   si S t        i t        g i}|D �]ª  }t        |«        t	        |d«      «       }|j
                  rÚ|j                  «       5  t        j                  | ||t        | |«      ¬«      }d d d «       |sŒkt        |t           j                  «       «      D ]9  }d|v sŒ|t           j                  |«      |t           |j                  dd«      <   Œ; |t           D ]1  }|t           D �cg c]  }|j                  dd«      ‘Œ }}||t        <   Œ3 �nGt        t        j                   d„ |j"                  D «       «      «      }t%        t'        |t)        t+        |«      «      «      «      }	i }
| j-                  «       D ]a  \  }}t/        | |«      }t+        |«      dk7  rt1        d|› d	t+        |«      › �«      ‚t3        t5        |«      «      }||	vrŒS|	|   }||
|<   ||
|<   Œc t        |t           j                  «       «      D ])  }|
|   }|t           j                  |«      |t           |<   Œ+ |t           D ]#  }|t           D �cg c]  }|
|   ‘Œ	 c}|t        <   Œ% |s�ŒQt7        t8        |t           «      j;                  |t           «       t7        t<        |t           «      j?                  |t           «       �Œ­ |j@                  rt7        tB        tE        |«      «      }tG        ||«      S # 1 sw Y   �Œ�xY wc c}w c c}w )
Nrâ   ©Úgrouprp   z
_orig_mod.rk   c              3   ó.   K  — | ]  }|t            –— Œ y ­wr7   )r  )r­   Úgs     r=   r®   z(_get_optim_state_dict.<locals>.<genexpr>¬  s   è ø€ Ò-U¸Q¨a´­jÑ-Uùs   ‚ro   ré   rê   )$rY   r)  r*  r  rÛ   r[   rZ   rx   rÏ   rá   rb   rò   rõ   rq   r  r	   Úfrom_iterabler2   r\   r   Úrangery   rœ   r�   rv   ró   rô   r   r'   r¿   r(   ÚextendrF   r)   r.  rç   )re   rB  rÐ   rÏ   r  Úosdr-  rG  r3   Úparam_pid_mappingÚfqn_pid_mappingrÕ   rÉ   rÊ   r�   ÚpidrE  s                    r=   Ú_get_optim_state_dictrO  ‰  s  € ð ×ÒØˆ	ä,2°B¼¸RÐ+@ÐØó 9HˆÜ˜%Ô Ø1Œn˜U LÓ1Ó3ˆØ×ÒØ×"Ñ"Ó$ñ Ü×+Ñ+ØØØÜ1°%¸Ó>ô	�÷ñ ØÜ˜#œf™+×*Ñ*Ó,Ó-ò R�Ø !Ò#Ø?BÄ6¹{¿¹ÈqÓ?Q�Cœ‘K §	¡	¨,¸Ó ;Ò<ðRð œ‘Xò $�Ø?@Ä¹zÖJ¸!˜!Ÿ)™) L°"Õ5ÐJ�ÐJØ#�”'’
ò$ô œ%×-Ñ-Ñ-UÀ%×BTÑBTÔ-UÓUÓVˆFÜ $¤S¨´´s¸6³{Ó1CÓ%DÓ EÐØ ˆOØ#×4Ñ4Ó6ò +‘
��UÜ  ¨Ó,�Ü�t“9 ’>Ü(Ø2°3°%°w¼sÀ4»y¸kÐJóð ô œ4 ›:Ó&�ØÐ 1Ñ1Øà'¨Ñ.�Ø'*� Ñ$à'*� Ò$ð+ô  ˜C¤™K×,Ñ,Ó.Ó/ò 8�Ø% cÑ*�ð $'¤v¡;§?¡?°3Ó#7�”F‘˜CÒ ð	8ð œS™ò R�ØBGÌÁ.Ö!Q¸3 /°#Ó"6Ò!Q�”g’ðRñ ÙäŒ]Ð,¬VÑ4Ó5×<Ñ<¸SÄ¹[ÔIÜÔÐ 0´Ñ 5Ó6×=Ñ=¸cÄ#¹hÖGðs9Hðv ×(Ò(ÜÜÔ 9Ð:JÓ Kó
Ðô )Ð)9¸4Ó@Ð@÷yñ üò$ Kùò: "Rs   Á$K>Ã=LÉLË>L	c           
      óV  — i }g }t         |t        |i}i }t        d„ t        t        |t            «      D «       «      r|S |j
                  D �]t  }|j                  t        g i«       |t           D �]o  }	|j                  |	   D �]Y  }
|
|j                  v rCd}t        t        |t           «      D ]&  }|
t        t        t           |t           «      v sŒ$d} n nd}|sŒZ|d   t           }t        |t        «      st        dt        |«      › �«      ‚|j                  |
«       |	j                   rR|
t        t        |t            «      v rt        t        |t            «      |
   ||
<   n|j"                  rt%        d|
› d�«      ‚t        t        |t           «      D ]D  }|
t        t        t           |t           «      v sŒ$t'        |t           «      dz
  |t)        |«      <   ŒF �Œ\ �Œr t'        |t           «      d	k(  s�Œ®g }t        t        |t           «      D ]>  }t'        t        t        t           |t           «      «      d	k(  sŒ.|j                  |«       Œ@ t'        |«      dk7  rt+        d
«      ‚t'        |t           «      t'        |j
                  «      k7  rt+        d«      ‚t'        |t           «      dz
  |t)        «      <   �Œw t        t        |t           «      D ]M  }|j-                  t)        |«      d«      }|dk(  rŒ$|j/                  «       D ]  \  }}|t        k(  rŒ|||   |<   Œ ŒO |S )að  
    Extract the corresponding optim state_dict from ``optim_state_dict`` for
    ``optim`` and return the result optim state_dict.

    Args:
        model (nn.Module): the root model.
        optim (torch.optim.Optimizer): the optimizer.
        optim_state_dict (Dict[str, ValueType]): the superset optim state_dict that
            contains the optim state_dict of ``optim``.
        info (_StateDictInfo): state dict information.

    Returns:
        The optim state_dict of ``optim``.
    c              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­wr7   )rt   r$  )r­   r-  s     r=   r®   z*_split_optim_state_dict.<locals>.<genexpr>ð  s   è ø€ Ò
U !Œ:�aœ×Ñ
Uùs   ‚FTr•   r8  z'Missing optimizer state for parameter 'z‡' in checkpoint. The parameter requires gradients but has no saved optimizer state. To load anyway, use StateDictOptions(strict=False).ro   r   zÛThere are param groups that have zero parameters. In such a case, DSD only support exactly one param group with zero parameters.But the loaded state_dict has zero or more than one param groups that have zero parameters.z`When there is a parameter group that has zero parameters, multiple optimizers are not supported.)r)  r*  Úallr   r'   r2   rw   r  rU   rV   r(   rb   rO   rt   rv   r'  r÷   rD   r…   ry   ÚidrÃ   r‚   rÁ   )re   r  rÏ   rÐ   r4   r9  r:  Ú
pg_mappingr  rÉ   r�   r;  Úloaded_param_groupr3   r+  Úpg_idxrÕ   r  s                     r=   Ú_split_optim_state_dictrW  Ö  sI  € ð* €EØ"$€HÜ&,¨e´S¸(Ð%C€JØ!#€Jä
Ñ
U¤t¬MÐ;KÌFÑ;SÓ'TÔ
UÔUØÐà×)Ñ)ó 7JˆØ�‰œ "˜Ô&Ø ¤Ñ)ó  	VˆEØ×-Ñ-¨eÑ4ó V�Ø˜$×4Ñ4Ñ4Ø %�IÜ.2Ü)Ð+;¼CÑ+@ó/ò "Ð*ð ¤$¤t¬C¡yÐ2DÄWÑ2MÓ"NÒNØ(,˜IÙ!ñ"ð !%�IÙ Øà! "™¤gÑ.�Ü! &¬$Ô/Ü(Ð+>¼tÀF»|¸nÐ)MÓNÐNØ—‘˜cÔ"Ø×&Ò&Øœd¤=Ð2BÄ6Ñ2JÓKÑKÜ%)¬-Ð9IÌ&Ñ9QÓ%RÐSVÑ%W˜˜cš
ØŸšÜ*ØEÀcÀUð KRð Róð ô
 +/Ü%Ð'7¼Ñ'<ó+ò VÐ&ð œd¤4¬¡9Ð.@ÄÑ.IÓJÒJÜ=@ÀÌCÁÓ=QÐTUÑ=U˜
¤2Ð&8Ó#9Ò:ò	Vò7Vð 	VôD ˆ{œ7Ñ#Ó$¨Ô)àˆCÜ&*Ô+<Ð>NÌsÑ>SÓ&Tò 3Ð"Ü”tœD¤™IÐ'9¼'Ñ'BÓCÓDÈÓIØ—J‘JÐ1Õ2ð3ô �3‹x˜1Š}Ü ð1óð ô Ð#¤CÑ(Ó)¬S°×1CÑ1CÓ-DÒDÜ ð=óð ô 25°ZÄ±_Ó1EÈÑ1IˆJ”rÐ,Ó-Ó.ðo7Jôr Ô-Ð/?ÄÑ/DÓEò 	*ˆØ—‘¤ ;£°Ó4ˆØ�RŠ<Øà%×+Ñ+Ó-ò 	*‰JˆC�Ø”gŠ~Øà$)ˆH�VÑ˜SÒ!ñ		*ð	*ð ÐrQ   c                 óH  ‡— |j                   sy |D �]ý  }t        |«       |r@t        |v rt        | |||«      }n+t	        |t        t        t        t        f   |«      |«      }ni }|j                  �rx| j                  «       D �]&  \  }}t        | |«      }t        | |d¬«      }	||	k(  rŒ't        |«      dk7  rt        d|› dt        |«      › �«      ‚|j                  «       }
|	j                  «       }|t           D ]N  }t        t        t        t         f   |«      }|t"           D �cg c]  }|j%                  |
|«      ‘Œ }}||t"        <   ŒP t        t&        |t           «      }t)        |j+                  «       «      D ]+  }|
|v sŒ|j                  |«      ||j%                  |
|«      <   Œ- �Œ) |j-                  «       5  t/        j0                  | ||t3        | |«      ¬«      }d d d «       �n|j4                  �rd|_        t7        | |f|«      }d|_        d Šˆfd„}t9        t:        j<                  ||«      }‰€t        d	«      ‚t?        |«      \  }}t?        |«      \  }}|j@                  rtC        ||‰¬
«       ntE        ||‰¬
«       |D ]*  }||vsŒ||vrt        d|› d�«      ‚||   ||<   ||   ||<   Œ, tG        ||«      }|t           D ]/  }t"        |vsŒg t        t        t        t        f   |«      t"        <   Œ1  tI        |d«      |¬«       �Œ  y c c}w # 1 sw Y   Œ%xY w)NF)rh   ro   zExpected 1 FQN for 'rê   rD  Tc                 ó‚   •— | j                  «       dkD  r*‰€| j                  Š| S ‰| j                  k7  rt        d«      ‚| S )Nr   zDevice mismatch)r  rü   rÃ   )Útrü   s    €r=   Ú_devicez'_load_optim_state_dict.<locals>._devicez  sD   ø€ Ø—5‘5“7˜Q’;à�~Ø!"§¡˜ð �ð   1§8¡8Ò+Ü(Ð):Ó;Ð;Ø�rQ   zExpected device to be setrý   zExpected key 'z' in osd_mappingrþ   )râ   )%rY   r  r)  rW  rA  r   r\   rO   r&   r[   rœ   r�   ry   rv   rõ   r*  r
   r  rq   r'   rb   rò   rZ   rx   Úoptim_state_dict_to_loadrá   r@   rO  r#   r]   r^   r   rE   r   r   r   rÛ   )re   rB  râ   rÐ   r  rÏ   Úoriginal_fqnÚ_rÊ   Úfqns_with_compilerr�   Úfqn_with_compilerrG  ÚvalrÕ   r3   Ú	osd_stater-  r  r[  Úflatten_osdÚosd_mappingÚflatten_local_osdÚlocal_osd_mappingÚ	optim_keyÚpgrü   s                             @r=   Ú_load_optim_state_dictri  :  s  ø€ ð ×ÒØàó ^NˆÜ˜%Ô ÙÜ˜Ñ#Ü#:Ø˜5 *¨dó$Ñ ô $?Øœ4¤¤S¬) ^Ñ 4°jÓAÀ4ó$Ñ ð  "ÐØ×Óð $)×#9Ñ#9Ó#;ó X‘�˜aÜ  ¨Ó5�Ü%.Ø˜<¸eô&Ð"ð Ð-Ò-Øä�t“9 ’>Ü(Ø.¨|¨n¸GÄCÈÃIÀ;ÐOóð ð —h‘h“j�Ø$6×$:Ñ$:Ó$<Ð!Ø)¬#Ñ.ò *�AÜœt¤C¬ H™~¨qÓ1�CàGJÌ7Á|öØ@C˜Ÿ™ CÐ):Õ;ð�Fð ð $*�Cœ’Lð*ô !¤Ð0@ÄÑ0HÓI�	Ü˜iŸn™nÓ.Ó/ò X�AØ˜a’xØGPÇ}Á}ÐUVÓGW˜	 !§)¡)¨CÐ1BÓ"CÒDòXð+Xð2 ×"Ñ"Ó$ñ Ü#'×#@Ñ#@ØØØ$Ü1°%¸Ó>ô	$Ð ÷ñ ð ×!Ó!Ø#(ˆDÔ Ü4°U¸U¸HÀdÓKÐØ#'ˆDÔ ØˆFôô œeŸl™l¨GÐ5EÓFˆAØˆ~Ü$Ð%@ÓAÐAÜ':Ð;KÓ'LÑ$ˆK˜Ü3FÐGWÓ3XÑ0ÐÐ0Ø×(Ò(Ü% kÐ3DÈVÖTä& {Ð4EÈfÕUð
 )ò J�	ØÐ$5Ò5Ø ¨Ñ3Ü,Ø,¨Y¨KÐ7GÐHóð ð 4?¸yÑ3IÐ% iÑ0Ø3>¸yÑ3IÐ% iÒ0ðJô  5Ø!Ð#4ó Ðð '¤sÑ+ò A�Ü "Ò$Ø>@”Dœœc¤9˜nÑ-¨rÓ2´7Ò;ðAð 	1Œ�uÐ/Ó0Ð<L×Mñ}^Nùò@÷ð ús   Ä$L
Æ;$LÌL!	c                ó˜   — t        «       5  t        | dd||¬«      }t        | |«      }t        |i |«       |cddd«       S # 1 sw Y   yxY w)aH  
    Return the model state_dict of ``model``.

    See ``get_state_dict`` for the detail usage.

    Args:
        model (nn.Module): the nn.Module to the model.
        submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters
            that belong to the submodules.
        options (StateDictOptions): the options to control how
            model state_dict and optimizer state_dict should be returned. See
            `StateDictOptions` for the details.

    Returns:
        The state_dict for ``model``.

    :rtype: typing.Dict[str, ValueType]
    rP   F©r§   r¤   r¥   N)r>   rÍ   rù   rÖ   )re   r¤   r¥   rÐ   rÎ   s        r=   r+   r+   ¥  sV   € ô0 
‹ñ 
 ÜØØØØ!Øô
ˆô 1°¸Ó=ÐÜÐ+¨R°Ô6Ø÷
 ÷ 
 ò 
 ús   ‹+A Á A	c                óþ   — t        «       5  t        |t        j                  j                  «      r|fn
t        |«      }t        | |d||¬«      }t        | ||«      }t        i ||«       |cddd«       S # 1 sw Y   yxY w)aË  
    Return the combined state_dict for optimizers.

    See ``get_state_dict`` for the detail usage.

    Args:
        model (nn.Module): the nn.Module to the model.
        optimizers (Union[None, Optimizer, Iterable[Optimizer]]):
            The optimizers that are used to optimize ``model``.
        submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters
            that belong to the submodules.
        options (StateDictOptions): the options to control how
            model state_dict and optimizer state_dict should be returned. See
            `StateDictOptions` for the details.

    Returns:
        The state_dict for ``optimizers``.

    :rtype: OptimizerStateType
    Trk  N)	r>   rt   r]   r  Ú	Optimizerrß   rÍ   rO  rÖ   )re   rB  r¤   r¥   rÐ   rÏ   s         r=   r,   r,   Ê  s„   € ô6 
‹ñ  ô ˜*¤e§k¡k×&;Ñ&;Ô<ð ‰Mä�zÓ"ð 	ô
 ØØØØ!Øô
ˆô 1°¸
ÀDÓIÐÜ˜2Ð/°Ô6Ø÷ ÷  ò  ús   ‹AA3Á3A<c                ó  — t        «       5  t        |t        j                  j                  «      r|fn
t        |«      }t        | |d||¬«      }t        | |«      }t        | ||«      }t        |||«       ||fcddd«       S # 1 sw Y   yxY w)aô  
    Return the model state_dict and optimizers state_dict.

    ``get_state_dict`` can process any module that is parallelized by PyTorch
    FSDP/fully_shard, DDP/replicate, tensor_parallel/parallelize_module, and any
    combination of these parallelisms. The main functions of ``get_state_dict``
    are: 1.) returning a model and optimizer state_dict that can be resharded
    with a different number of trainers and/or different parallelisms.
    2.) hiding the parallelism-specific state_dict APIs. Users don't have to call
    these APIs.
    3.) sanity checking the result state_dict.

    The keys of the result state dictionary are the canonical FQNs (Fully
    Qualified Names).  A canonical FQN refers to the FQN based on a parameter's
    position in an nn.Module hierarchy. More specifically, a canonical FQN to a
    parameter is the FQN returned by ``module.named_parameters()`` or
    ``module.named_buffers()`` when the module is not distributed by any
    parallelisms. Since the optimizer internally uses parameter IDs to represent
    a parameter, there will be a conversion from the parameter IDs to the
    canonical FQNs when calling this API.

    ``get_state_dict`` can also process a module that is not parallelized. In
    such a case, ``get_state_dict`` only performs one function -- converting the
    optimizer parameter IDs to the canonical FQNs.

    Example:
        >>> # xdoctest: +SKIP
        >>> import torch
        >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
        >>> from torch.nn.parallel import DistributedDataParallel as DDP
        >>> from torch.distributed.checkpoint.state_dict import get_state_dict

        >>> fsdp_model = FSDP(copy.deepcopy(model))
        >>> fsdp_optim = torch.optim.Adam(model.parameters(), lr=1e-3)
        >>> ddp_model = DDP(copy.deepcopy(model))
        >>> ddp_optim = torch.optim.Adam(model.parameters(), lr=1e-3)


        >>> ddp_state_dict, ddp_optim_state_dict = get_state_dict(ddp_model, ddp_optim)
        >>> fsdp_state_dict, fsdp_optim_state_dict = get_state_dict(
        ...     fsdp_model, fsdp_optim
        ... )

        >>> # if we simply call ddp_model.state_dict() and fsdp_model.state_dict(),
        >>> # the asserts will fail.
        >>> assert ddp_state_dict == fsdp_state_dict
        >>> assert ddp_optim_state == fsdp_optim_state_dict


    Args:
        model (nn.Module): the nn.Module to the model.
        optimizers (Union[None, Optimizer, Iterable[Optimizer]]):
            The optimizers that are used to optimize ``model``.
        submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters
            that belong to the submodules.
        options (StateDictOptions): the options to control how
            model state_dict and optimizer state_dict should be returned. See
            `StateDictOptions` for the details.

    Returns:
        ``Tuple`` that contain model state_dict and optimizer state_dict.

    :rtype: typing.Tuple[typing.Dict[str, ValueType], OptimizerStateType]
    Frk  N)
r>   rt   r]   r  rm  rß   rÍ   rù   rO  rÖ   )re   rB  r¤   r¥   rÐ   rÎ   rÏ   s          r=   r-   r-   ÷  s™   € ôP 
‹ñ 2ô ˜*¤e§k¡k×&;Ñ&;Ô<ð ‰Mä�zÓ"ð 	ô
 ØØØØ!Øô
ˆô 1°¸Ó=ÐÜ0°¸
ÀDÓIÐÜÐ+Ð-=¸tÔDØÐ!1Ð1÷!2÷ 2ò 2ús   ‹A,BÂB
c           
      ó¼  — |si S t        t        t        |j                  «       «      «      t        j
                  «      rüt        j                  dt        d¬«       t        t        t        j
                  t        t        t        f   f   |«      }i }|j                  «       D ]•  \  }}| j                  «       D ]}  \  }}||k7  rŒt        | |«      }t!        |«      dk7  rt#        d«      ‚t        t        |«      «      › d�}	|j%                  |j                  «       D �
�ci c]  \  }
}|	|
z   |“Œ c}}
«       Œ Œ— |S t        t        t        t        f   |«      S c c}}
w )NzÎPassing model_state_dict as a ``Dict[nn.Module, Dict[str, Any]]``is deprecated and will be removed in 2.5. If you need this feature, please preprocess the model_state_dict to achieve the same functionality.r©   rª   ro   z/FQNs for a submodule should only have 1 elementrl   )rt   ró   rô   rò   rc   rd   r¹   r¾   r¼   r   r\   rO   r&   rÁ   rÂ   r�   ry   rv   r¿   )re   râ   Úcast_state_dictrø   rŸ   Úsub_state_dictrf   ÚmrÊ   r‹   Úsubfqnr  s               r=   Ú_unflatten_model_state_dictrt  R  sF  € ñ Øˆ	ä”$”t˜JŸO™OÓ-Ó.Ó/´·±Ô;Ü�‰ð"ô Øõ	
ô œt¤B§I¡I¬t´C¼°NÑ/CÐ$CÑDÀjÓQˆØ/1ˆØ)8×)>Ñ)>Ó)@ò 	Ñ%ˆI�~Ø ×.Ñ.Ó0ò ‘��aØ˜	’>Øä  ¨Ó-�Ü�t“9 ’>Ü(ØIóð ô !¤ d£Ó,Ð-¨QÐ/�Ø×%Ñ%ØAO×AUÑAUÓAW×X±°¸�V˜f‘_ eÑ+ÓXõñð	ð Ðä”Dœœi˜Ñ(¨*Ó5Ð5ùó	 Ys   ÄE)r¥   c                ó¬   — t        | |«      }t        «       5  t        | dd|¬«      }t        |i |«       t	        | ||«      cddd«       S # 1 sw Y   yxY w)a=  Load the model state_dict.

    The counterpart of ``get_model_state_dict`` to set the state_dict to the
    model. See ``set_state_dict`` for the detail usage.

    Args:
        model (nn.Module): the nn.Module to the model.
        model_state_dict: (Dict[str, ValueType]):
           the model state_dict to load. If the key of the ``model_state_dict``
           is nn.Module, the key is a submodule of ``model`` and the value should
           be the state_dict of the submodule. When loading the state_dict,
           the prefix of the submodule will be append to the state_dict.
        options (StateDictOptions): the options to control how
            model state_dict and optimizer state_dict should be loaded. See
            `StateDictOptions` for the details.

    Returns:
        ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
            * **missing_keys** is a list of str containing the missing keys
            * **unexpected_keys** is a list of str containing the unexpected keys

    :type model_state_dict: typing.Dict[str, ValueType]
    rP   F©r§   r¥   N)rt  r>   rÍ   rÖ   r  )re   rÎ   r¥   rÐ   s       r=   r.   r.   w  s`   € ô: .IØÐó.Ðô 
‹ñ EÜ˜u b°UÀGÔLˆäÐ+¨R°Ô6Ü% eÐ-=¸tÓD÷	E÷ Eò Eús   —)A
Á
Ac                óú   — t        «       5  t        |t        j                  j                  «      r|fn
t        |«      }t        | |d|¬«      }t        i ||«       t        | |||«       ddd«       y# 1 sw Y   yxY w)a¬  Load the optimizers state_dict.

    The counterpart of ``get_optimizer_state_dict`` to set the state_dict to the
    optimizers. See ``set_state_dict`` for the detail usage.

    WARN: ``set_optimizer_state_dict`` can only be called before ``backward()`` or after
        ``step()`` is called on the optimizers. Otherwise, the optimizer states won't be
        initialized correctly.

    Args:
        model (nn.Module): the nn.Module to the model.
        optimizers (Union[Optimizer, Iterable[Optimizer]]):
            The optimizers that are used to optimize ``model``.
        optim_state_dict: OptimizerStateType:
            the optimizer state_dict to load.
        options (StateDictOptions): the options to control how
            model state_dict and optimizer state_dict should be loaded. See
            `StateDictOptions` for the details.

    Returns:
        None

    :type optim_state_dict: typing.OptimizerStateType
    Trv  N)	r>   rt   r]   r  rm  rß   rÍ   rÖ   ri  )re   rB  rÏ   r¥   rÐ   s        r=   r/   r/   ž  sz   € ô> 
‹ñ 	Jô ˜*¤e§k¡k×&;Ñ&;Ô<ð ‰Mä�zÓ"ð 	ô
 ˜u j¸TÈ7ÔSˆä˜2Ð/°Ô6Ü˜u jÐ2BÀDÔI÷	J÷ 	Jñ 	Jús   ‹AA1Á1A:c                ó.  — t        | |«      }t        «       5  t        |t        j                  j
                  «      r|fn
t        |«      }t        | || |¬«      }t        |||«       t        | |||«       t        | ||«      cddd«       S # 1 sw Y   yxY w)aü  Load the model state_dict and optimizers state_dict.

    The counterpart of ``get_state_dict`` to set the state_dict to the model and
    optimizers.  The given ``model_state_dict`` and ``optim_state_dict`` do not
    have to be returned by ``get_state_dict`` but must meet the following
    requirements: 1) all FQNs are canonical FQNs as defined in ``get_state_dict``,
    2) if a tensor is sharded, it must be either a ShardedTensor or DTensor,
    3) optimizer state_dict cannot contain the parameter IDs; the keys should be
    the canonical FQNs.

    WARN: ``set_state_dict`` can only be called before ``backward()`` or after ``step()``
        is called on the optimizers. Otherwise, the optimizer states won't be initialized
        correctly.

    Args:
        model (nn.Module): the nn.Module to the model.
        optimizers (Union[Optimizer, Iterable[Optimizer]]):
            The optimizers that are used to optimize ``model``.
        model_state_dict: (Union[Dict[nn.Module, Dict[str, ValueType]], Dict[str, ValueType]]):
           the model state_dict to load. If the key of the ``model_state_dict``
           is nn.Module, the key is a submodule of ``model`` and the value should
           be the state_dict of the submodule. When loading the state_dict,
           the prefix of the submodule will be append to the state_dict.
        optim_state_dict: OptimizerStateType:
            the optimizer state_dict to load.
        options (StateDictOptions): the options to control how
            model state_dict and optimizer state_dict should be loaded. See
            `StateDictOptions` for the details.

    Returns:
        ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
            * **missing_keys** is a list of str containing the missing keys of the model state_dict.
            * **unexpected_keys** is a list of str containing the unexpected keys of the model state_dict.

    :type model_state_dict: typing.Dict[str, ValueType]
    :type optim_state_dict: typing.OptimizerStateType
    rv  N)rt  r>   rt   r]   r  rm  rß   rÍ   rÖ   ri  r  )re   rB  rÎ   rÏ   r¥   rÐ   s         r=   r0   r0   É  s¦   € ô\ .IØÐó.Ðô 
‹ñ Eô ˜*¤e§k¡k×&;Ñ&;Ô<ð ‰Mä�zÓ"ð 	ô
 Ø�:Ð.>Ð*>Èô
ˆô 	Ð+Ð-=¸tÔDÜ˜u jÐ2BÀDÔIÜ% eÐ-=¸tÓD÷E÷ Eò Eús   —A*BÂBc                ó$  ‡‡— t        j                  t        | |¬«      Šˆfd„}|| _        t        j                  t        | |¬«      Šdt
        t        t        f   fˆfd„}|| _        t        j                  |«       t        j                  |«       y)aó  Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model``.

    Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model`` to
    be a partial function to call ``get_state_dict`` and ``set_state_dict``.

    Example:
        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
        from torch.distributed.checkpoint.state_dict import patch_model_state_dict

        model = fsdp(model)
        patch_model_state_dict(model)

    Args:
        model (nn.Module): the nn.Module to the model.
        options (StateDictOptions): the options to control how
            model state_dict and optimizer state_dict should be loaded. See
            `StateDictOptions` for the details.
    Returns:
        None
    )re   r¥   c                  ó   •—  ‰ «       S r7   rP   ©Ú_state_dict_calls   €r=   Ústate_dict_callz0_patch_model_state_dict.<locals>.state_dict_call,  ó   ø€ ÙÓ!Ð!rQ   râ   c                 ó   •—  ‰| ¬«       y )N)rÎ   rP   ©râ   Ú_load_state_dict_calls    €r=   Úload_state_dict_callz5_patch_model_state_dict.<locals>.load_state_dict_call7  ó   ø€ Ù¨zÖ:rQ   N)rÇ   rÈ   r+   râ   r.   r\   rO   r
   rþ   r5   r˜   )re   r¥   r}  r‚  r�  r|  s       @@r=   Ú_patch_model_state_dictr„    sƒ   ù€ ô6 !×(Ñ(ÜØØôÐô"ð '€EÔä%×-Ñ-ÜØØôÐð;¬¬c´3¨h©õ ;ð 1€EÔä×Ñ˜OÔ,Ü×ÑÐ0Õ1rQ   c                óš  ‡‡— t        j                  t        | ||¬«      Šˆfd„}t        j                  t        | ||¬«      Šdt        t
        t        f   fˆfd„}t        j                  |«       t        j                  |«       t        |t        j                  j                  «      r|fn
t        |«      }|D ]  }||_        ||_        Œ y)a¤  Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers``.

    Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers`` to
    be a partial function to call ``get_state_dict`` and ``set_state_dict``.

    Note that if there are multiple optimizers, all of the optimizers will be patched.
    So users only need to call one of the state_dict() to get the full result.

    Example:
        from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
        from torch.distributed.checkpoint.state_dict import patch_model_state_dict

        model = fsdp(model)
        patch_model_state_dict(model)

    Args:
        model (nn.Module): the nn.Module to the model.
        options (StateDictOptions): the options to control how
            model state_dict and optimizer state_dict should be loaded. See
            `StateDictOptions` for the details.
    Returns:
        None
    )re   rB  r¥   c                  ó   •—  ‰ «       S r7   rP   r{  s   €r=   r}  z4_patch_optimizer_state_dict.<locals>.state_dict_callh  r~  rQ   râ   c                 ó   •—  ‰| ¬«       y )N)rÏ   rP   r€  s    €r=   r‚  z9_patch_optimizer_state_dict.<locals>.load_state_dict_callr  rƒ  rQ   N)rÇ   rÈ   r,   r/   r\   rO   r
   r5   r˜   rt   r]   r  rm  rß   râ   rþ   )re   rB  r¥   r}  r‚  r  r�  r|  s         @@r=   Ú_patch_optimizer_state_dictrˆ  B  sÄ   ù€ ô> !×(Ñ(Ü ØØØô	Ðô"ô &×-Ñ-Ü ØØØô	Ðð;¬¬c´3¨h©õ ;ô ×Ñ˜OÔ,Ü×ÑÐ0Ô1ô �j¤%§+¡+×"7Ñ"7Ô8ð 
‰ä�:Óð ð
 ò 5ˆØ*ˆÔØ 4ˆÕñ5rQ   )rG   TT)rG   )sr`   rÇ   r8   r¹   Úcollections.abcr   r   r   Údataclassesr   r   r   Ú	itertoolsr	   Útypingr
   r   r   r]   Útorch.distributedrå   rÒ   Útorch.nnrc   Ú'torch.distributed._shard.sharded_tensorr   Ú#torch.distributed._state_dict_utilsr   r   r   r   r   r   Ú;torch.distributed.algorithms._checkpoint.checkpoint_wrapperr   Útorch.distributed.fsdpr   r   r   rx   r   r   r   r   r   Ú$torch.distributed.fsdp._common_utilsr   r   Ú"torch.distributed.fsdp._init_utilsr   Útorch.distributed.tensorr    Útorch.nn.modules.moduler!   Útorch.nn.parallelr"   ru   Útorch.utils._pytreer#   Ú__all__rz   r*  r  r)  r_   rO   r$   r^   r$  r%  r%   rb   rß   r\   r&   r'   r(   r)   r5   rN   rÆ   r>   r*   rS   rd   rM   r�   r‘   r£   r  rm  rÍ   rÖ   rÛ   ÚProcessGrouprá   rç   Úno_gradrù   r  r  r.  rA  rO  rW  ri  r+   r,   r-   rt  r.   r/   r0   r„  rˆ  rP   rQ   r=   ú<module>rœ     s¡  ðä Û Û 	Û ß 9Ñ 9ß 0Ñ 0Ý ß +Ñ +ã Ý  Ý Ý A÷÷ õ÷	÷ 	ó 	÷õ JÝ ,Ý 5Ý <Ý -ò€ð" €Ø€Ø
€Ø	€à	ˆS‰€Ø˜-Ñ'¨%¯,©,Ñ6¸Ñ<¸uÑDÀsÑJ€à�D˜Ñ'Ñ'¨%°Ñ*>Ñ>ÀÀcÈ;ÐFVÑAWÑWð 
ð �S˜)�^Ñ$€Ø˜Ñ'Ð Ø˜#˜}Ð/@Ñ@Ð@ÑAÐ ñ &)£UÐ �S˜‘]Ó *ð ×Ññó ðð ÷,.ð ,.ó ð,.ð^ ô@Ð%ó @ó ð@ð& .Ø Ø!%ñFEØ�9‰9ðFEà
ðFEð ðFEð ð	FEð
 ðFEð óFE÷R	ñ 	ó%"ðZ )-Ø'+ò}Ø�9‰9ð}à�%—+‘+×'Ñ'¨Ð,Ñ-ð}ð ð}ð
 �B—I‘I‘ Ñ%ð}ð  Ñ$ð}ð ó}ð@+Ø˜3 	˜>Ñ*ð+à(ð+ð ð+ð 
ó	+ð\˜Ÿ	™	 E§K¡K×$9Ñ$9Ñ9ð Àð Èó ðØ�9‰9ðØ*ðà	×Ñ˜Ñóð&Ø�S˜#�X‘ðØ&4ðà	ˆ#ˆsˆ(�^óð$ €‡�ƒð?;Ø�9‰9ð?;Ø*ð?;à	ˆ#ˆyˆ.Ñò?;ó ð?;ðD €‡�ƒðA
Ø�9‰9ðA
à�S˜)�^Ñ$ðA
ð ðA
ð ò	A
ó ðA
ðH'&˜UŸ[™[×2Ñ2ð '&°tó '&ðT_Ð*<ð _ÀÀcÈ9ÀnÑAUó _ðDEØ�;‰;× Ñ ðEà�S˜)�^Ñ$ðEð ðEð ó	EðP €‡�ƒðIAØ�9‰9ðIAà�e—k‘k×+Ñ+¨SÐ0Ñ1ðIAð ðIAð ò	IAó ðIAðXaØ�9‰9ðaà�;‰;× Ñ ðað )ðað ð	að
 óaðH €‡�ƒðgNØ�9‰9ðgNà�e—k‘k×+Ñ+¨SÐ0Ñ1ðgNð #ðgNð ð	gNð
 
ògNó ðgNðZ )-Ø'+ò	" Ø�9‰9ð" ð �B—I‘I‘ Ñ%ð" ð  Ñ$ð	" ð
 
ˆ#ˆyˆ.Ñó" ðR )-Ø'+ò* Ø�9‰9ð* à—‘×%Ñ%¨°·±×1FÑ1FÑ(GÑGð* ð �B—I‘I‘ Ñ%ð	* ð
  Ñ$ð* ð ó* ðb )-Ø'+òX2Ø�9‰9ðX2à—‘×%Ñ%¨°·±×1FÑ1FÑ(GÑGðX2ð �B—I‘I‘ Ñ%ð	X2ð
  Ñ$ðX2ð ˆ4��Y�ÑÐ!3Ð3Ñ4óX2ðv"6Ø�9‰9ð"6à�R—Y‘Y  S¨) ^Ñ 4Ð4Ñ5¸¸SÀ)¸^Ñ8LÑLð"6ð 
ˆ#ˆyˆ.Ñó"6ðR (,ò	$EØ�9‰9ð$Eà˜3 	˜>Ñ*ð$Eð  Ñ$ð	$Eð
 ó$EðX (,ò(JØ�9‰9ð(Jà—‘×%Ñ%¨°·±×1FÑ1FÑ(GÑGð(Jð )ð(Jð
  Ñ$ð(Jð 
ó(Jðb (,ò=EØ�9‰9ð=Eà—‘×%Ñ%¨°·±×1FÑ1FÑ(GÑGð=Eð ˜3 	˜>Ñ*ð	=Eð
 )ð=Eð  Ñ$ð=Eð ó=EðD ð (,ò12Ø�9‰9ð12ð  Ñ$ð12ð 
ò	12ó ð12ðl ð
 (,ò	;5Ø�9‰9ð;5ð �e—k‘k×+Ñ+¨SÐ0Ñ1ð;5ð  Ñ$ð	;5ð
 
ò;5ó ñ;5rQ   