
    Vh                     v    d dl mZ ddlmZ ddlmZmZmZmZm	Z	 	 e
eef   Zdedeeef   fdZdededefd	Zy
)    )STATE_DICT_TYPE   )_version)OBJ_PATHset_elementSTATE_DICT_ITEMtraverse_state_dicttraverse_state_dict_v_2_3
state_dictreturnc                     i i dt         dt        ddffd}t        j                  duxr t        j                  dk(  }|rt	        | |       fS t        | |       fS )a  
    Flatten ``state_dict`` made of nested dicts and lists into a top level dictionary.

    Use ``unflatten_state_dict`` to revert this process.
    Returns:
        A tuple with the flatten state_dict and a mapping from original to new state_dict.
    N.B. The new keys are derived from the object paths, joined by dot.
        For example: ``{ 'a': {'b':...}}`` results in the key `a.b`.
    pathvaluer   Nc                 |    dj                  t        t        |             }|v rt        d|       ||<   | |<   y )N.zduplicated flatten key )joinmapstr
ValueError)r   r   new_fqn	flattenedmappingss      Y/home/dcms/DCMS/lib/python3.12/site-packages/torch/distributed/checkpoint/_nested_dict.py	flat_copyz%flatten_state_dict.<locals>.flat_copy*   sF    ((3sD>*i6wi@AA"	'     2_3)r   r   r   _derived_versionr
   r	   )r   r   	use_v_2_3r   r   s      @@r   flatten_state_dictr      s     "$I "H! ! !T ! 	!!-T(2K2Ku2T  !*i8 h 	J	2hr   mappingc                 Z    i }| j                         D ]  \  }}t        |||   |        |S )zaRestore the original nested state_dict according to ``mapping`` and the flattened ``state_dict``.)itemsr   )r   r    nestedkeyr   s        r   unflatten_state_dictr%   >   s:     !F &&( 1
UFGCL%01Mr   N)%torch.distributed.checkpoint.metadatar    r   	_traverser   r   r   r	   r
   dictr   FLATTEN_MAPPINGtupler   r%    r   r   <module>r-      sj    B   sH}%  
?O+, F*9r   