U
    Jc                  
   @   s  d dl Z d dlZd dlZd dlmZmZmZmZmZm	Z	m
Z
mZmZmZmZ d dlZd dlmZ d dlm  m  mZ d dlmZ d dlmZ d dlmZ d dlmZmZ d dl m!Z! ee"ef eee"ef  ddd	Z#G d
d dZ$G dd de	Z%G dd de	Z&eee"ef e'e'eee"ef  dddZ(eee"ef e'e$dddZ)ee$e'eee"ef  dddZ*ee"ef ejj+e'ee"ef dddZ,ee"ee"ef f ee" ee'ee"ef dddZ-e"eej. ee" eej/ eej.dd d!Z0e"eej. ee" ej.d"d#d$Z1e"ee ee" ed%d&d'Z2ee"ef e3ee"ef d(d)d*Z4e
ee"ef  e3ee"ef d+d,d-Z5ee"ef e
ee"ef  e3e3ej6ee"ef d.d/d0Z7e
ej. ee"ef e"ej/ej8ej6e3e3dd1	d2d3Z9e
ej. ee"ef e"ej/ej8ej6e3dd4d5d6Z:ee"ef ejj+ej;j<e
eeee"ef  eejj= f  e'ee"ef d7d8d9Z>ejj+d:d;d<Z?ej;j<d=d>d?Z@dQejj+e
eeee"ef  eejj= f  eejj= d@dAdBZAej;j<eejj=e3f dCdDdEZBdRejj+e
eeee"ef  eejj= f  eejj=e3f d@dFdGZCee3ee3 f ee3 dHdIdJZDee'dKdLdMZEejj+ej;j<e
eeee"ef  eejj= f  e'e'e
ejF e'ee"ef dNdOdPZGdS )S    N)AnyDictIterableIteratorList
NamedTupleOptionalSequenceTupleUnioncast)ShardedTensor)_gather_state_dict)FlatParameterFlatParamHandle)_ext_chunk_tensor)
dictionaryreturnc                 c   s(   t |  }|D ]}|| | fV  qd S N)sortedkeys)r   r   k r   G/tmp/pip-unpacked-wheel-gikjz4vx/torch/distributed/fsdp/_optim_utils.pysorted_items   s    r   c                   @   sR   e Zd ZU dZi Zeeejf e	d< i Z
eeejf e	d< i Zeeef e	d< dS )_ConsolidatedOptimStateau  
    This holds the consolidated optimizer state on the target rank. Positive-
    dimension tensor state is communicated across ranks, while zero-dimension
    tensor state and non-tensor state is taken directly from the target rank.

    PyTorch version 1.12 moved to using zero-dimension tensors for scalar
    values, but user implemented optimizers may still use float (i.e. a
    non-tensor). Thus, we support both and handle them identically.

    Attributes:
        tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension
            tensor state name to the unsharded flattened tensor representing
            the state.
        zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero-
            dimension tensor state name to its value.
        non_tensor_state (Dict[str, Any]): Mapping from non-tensor state
            name to its value.
    tensor_statezero_dim_tensor_statenon_tensor_stateN)__name__
__module____qualname____doc__r   r   strtorchTensor__annotations__r   r   r   r   r   r   r   r   #   s   
r   c                   @   s&   e Zd ZU dZejed< ejed< dS )_PosDimTensorInfoa  
    Meatadata for positive-dimension tensors used internally for
    :meth:`scatter_full_optim_state_dict`.

    Attributes:
        shape (torch.Size): Sharded tensor shape (which is equal to the
            unsharded tensor shape if the tensor is optimizer state for a
            non-FSDP parameter and is hence not sharded).
        dtype (torch.dtype): Data type of the tensor.
    shapedtypeN)r   r    r!   r"   r$   Sizer&   r)   r   r   r   r   r'   <   s   

r'   c                   @   s*   e Zd ZU dZeedf ed< eed< dS )_OptimStateKeyz
    This represents an optimizer state key that may be used commonly across
    ranks. It is based on the unflattened parameter names rather than parameter
    IDs to make it indepenendent of each rank's own optimizer construction.
    .unflat_param_namesis_flat_paramN)r   r    r!   r"   r
   r#   r&   boolr   r   r   r   r+   L   s   
r+   )
flat_paramflat_param_stateto_saveshard_stater   c           
      C   sl   t | |||}|s|r$t|| ||ng }|rh|D ]6}t| D ]$}|| }	t|	tjr@|	 ||< q@q0|S )a  
    Unflattens the optimizer state, consisting of the "state" part and the
    "param_groups" part. Unflattening the "state" part involves consolidating
    the state on the target rank and remapping from flattened to unflattened
    parameter IDs, and the "param_groups" part only involves remapping from
    flattened to unflattened parameter IDs.

    Args:
        flat_param (FlatParameter): The flattened parameter.
        flat_param_state (Dict[str, Any]): Entry for the flattened parameter
            in the "state" part of the optimizer state dict.
        fsdp_module (FullyShardedDataParallel): FSDP module that owns
            ``flat_param``, i.e. holds it in ``self.params``.
        to_save (bool): Whether to save the state on this rank.

    Returns:
        List[Dict[str, Any]]: A :class:`list` holding the entries in the
        "state" part of the optimizer state dict corresponding to the
        unflattened parameters comprising the flattened parameter
        ``flat_param`` if on the target rank or an empty :class:`list`
        otherwise. The final optimizer state dict will need to map these
        entries using the proper unflattened parameter IDs.
    )_communicate_optim_state#_unflatten_communicated_optim_statelistr   
isinstancer$   r%   cpu)
r/   r0   fsdp_moduler1   r2   Zconsolidated_stateunflat_param_stateoptim_statekeystater   r   r   _unflatten_optim_stateW   s0    
r=   )r/   r0   r1   r   c                 C   s   t  }|j|j|j  }}}|j}t|D ]\}	}
t|
r|
 dkr|j	dks`|j
tjjkrj|
||	< q*|
js||
|j}
| j }|
j| }tj||
|d tj  |r| j }|d| ||	< q*|r*t|
r|
||	< q*|
||	< q*|S )a  
    Communicates the optimizer state for a flattened parameter ``flat_param``
    across ranks so that the target rank holds the entire non-sharded optimizer
    state.

    If ``N`` is the number of tensor optimizer states in the optimizer state
    dict, then the communication complexity is 0 if ``N = 0`` and ``N + 1``
    otherwise (where the plus 1 comes from all-gathering the padding per rank).

    Args:
        flat_param (FlatParameter): The flattened parameter.
        flat_param_state (Dict[str, Any]): The entry in the "state" part of the
            optimizer state dict corresponding to the flattened parameter.
        fsdp_module (FullyShardedDataParallel): FSDP module that owns
            ``flat_param``, i.e. holds it in ``self.params``.
        to_save (bool): Whether to save the state on this rank.

    Returns:
        ConsolidatedOptimState: Consolidated optimizer state for
        ``flat_param``; the state is not populated for non-target ranks.
    r      groupN)r   r   r   r   process_groupr   r$   	is_tensordim
world_sizeZsharding_strategyFSDPZShardingStrategyZNO_SHARDZis_cudatoZcompute_deviceZ_full_param_paddedsizeZ	new_zerosdistZ_all_gather_basecudaZsynchronize_unpadded_unsharded_sizeZnumel_is_zero_dim_tensor)r/   r0   r8   r1   r<   r   r   r   r@   
state_namevaluebuffer_sizeZtensor_bufferZunpadded_numelr   r   r   r3      s8    






r3   )r/   r<   r2   r   c                 C   s   g }i }|j }|j|j|j  }}}	t|D ]}
i }t|D ]b\}}||k}|sft||}|||< n|| }t|}|rt	|| j
| jtj | j}|||< q<t|D ]\}}|||< qt|	D ]\}}|||< q|| q,|S )a  
    Unflattens the communicated optimizer state (given by ``tensor_state``,
    ``non_tensor_state``, and ``zero_dim_tensor_state``) for a single flattened
    parameter ``flat_param``. This should only be called on the target rank.

    Args:
        flat_param (FlatParameter): The flattened parameter.
        state (_ConsolidatedOptimState): Consolidated optimizer state.

    Returns:
        List[Dict[str, Any]]: A :class:`list` holding the entries in the
        "state" part of the optimizer state dict corresponding to the
        unflattened parameters comprising the flattened parameter
        ``flat_param``. The final optimizer state dict will need to map these
        entries using the proper unflattened parameter IDs.
    )Z_num_paramsr   r   r   ranger   r   Z_get_unflat_viewsnextr   rankrD   r$   rI   Zdevice_countrA   append)r8   r/   r<   r2   r9   Zflat_param_viewsnum_unflat_paramsr   r   r   _Zunflat_state_paramrL   flat_tensorZviews_generatedZviewsr:   Zzero_dim_tensor
non_tensorr   r   r   r4      s>    




r4   )optim_state_dictmodelr2   r   c                 C   s   | }d|ksd|krt dt|}t|}i }|d }| D ]\}}	t|tr||ksjtd| || }
t||	|
||}t	t
|	d}|||< qBt|	dkst|	d }||krqBt	t
|	d}t|| ||< qBt|d }||d	S )
a:  
    Flattens the full optimizer state dict, still keying by unflattened
    parameter names. If ``shard_state=True``, then FSDP-managed
    ``FlatParameter`` 's optimizer states are sharded, and otherwise, they are
    kept unsharded.

    Returns:
        Dict[str, Any]: The flattened optimizer state dict.
    r<   param_groupszc`optim_state_dict` must have the keys "state" and "param_groups" to be a valid optimizer state dictz:Check the `flat_param_to_fsdp_module` construction
param: Tr>   r   Fr<   rY   )
ValueError_get_flat_param_to_fsdp_modulerE    _get_param_to_unflat_param_namesitemsr6   r   AssertionError_flatten_optim_stater+   tuplelencopydeepcopy)rW   rX   r2   Z
unflat_osdflat_param_to_fsdp_moduleparam_to_unflat_param_namesZflat_osd_stateunflat_osd_stateparamr,   r8   
flat_stater;   unflat_param_nameZflat_osd_param_groupsr   r   r   _flatten_optim_state_dict  s@    



rk   )rg   r,   r/   r2   r   c                    s  t |}|dkstd|j}t |}||ksBtd| d| fdd|D }t|s`i S  fdd|D }	d}
|	D ]B}|dkrq||
dkrt| }
q||
t| kr|td	| q||
dk	sti }|
D ]8fd
d|	D }dd |D }d } }}|D ]>}|t|o&|	 dkM }|t
|M }|t| M }q
tdd |D }t |dks||s|s|std d| d| |rt||||}|rt| j j\}}||< n||< q|rt|||< q|stt|||< q|S )ax  
    Flattens the optimizer state in ``full_optim_state_dict`` for a single
    flattened parameter ``flat_param`` in ``fsdp_module`` corresponding to
    the unflattened parameter names in ``unflat_param_names``.

    Args:
        unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the
            optimizer state dict corresponding to the unflattened parameters.
        unflat_param_names (List[str]): A :class:`list` of unflattened
            parameter names corresponding to the flattened parameter
            ``flat_param``.
        fsdp_module (FullyShardedDataParallel): FSDP module owning the
            flattened parameter.
        flat_param (FlatParameter): The flattened parameter.
        shard_state (bool): Whether to shard flattened positive-dimension
            tensor state; if ``False``, then the full flattened tensor is
            kept in the returned :class:`dict.

    Returns:
        Dict[str, Any]: A :class:`dict` mapping state names to their values for
        a particular flattened parameter. The sharded optimizer state dict's
        "state" part will map a key to this returned value.
    r   zSExpects at least one unflattened parameter corresponding to the flattened parameterzExpects z shapes but got c                    s   g | ]}t | kqS r   )r.   .0rj   )rg   r   r   
<listcomp>t  s   z(_flatten_optim_state.<locals>.<listcomp>c                    s*   g | ]"}|kr"t |  jd ndqS ))ZpgN)r   rA   rl   )r8   rg   r   r   rn   ~  s    Nz@Differing optimizer state names for the unflattened parameters: c                    s    g | ]}|d k	r|  nd qS r   r   )rm   r9   )rL   r   r   rn     s   c                 S   s   g | ]}|d k	r|qS r   r   rm   vr   r   r   rn     s      Tc                 s   s   | ]}t |V  qd S r   )typero   r   r   r   	<genexpr>  s     z'_flatten_optim_state.<locals>.<genexpr>r>   z*Differing optimizer state types for state z	, values z", and unflattened parameter names )rb   r_   Z_shapesanysetr   r[   r$   rB   rC   rK   _flatten_tensor_optim_stater   
_get_shardrQ   rD   $_flatten_zero_dim_tensor_optim_state_flatten_non_tensor_optim_state)rg   r,   r8   r/   r2   rS   unflat_param_shapesZnum_unflat_param_shapesZ	has_stateZunflat_param_statesZstate_namesr9   ri   Zstate_valuesZnon_none_state_valuesZare_pos_dim_tensorsZare_zero_dim_tensorsZare_non_tensorsrp   typesrU   Zsharded_flat_tensorrT   r   )r8   rL   rg   r   r`   J  s    

	






r`   )rL   pos_dim_tensorsr,   ry   r/   r   c                    s  dd |D }t dd |D }t|dkrFtd| d|  d| tt|t||D ]N\}}|d	krt|d
krtdq\|d	k	r\|j|kr\td|j d| q\td  fddt||D }	t	|	}
|j
}|
j|kstd|
j d| |
S )aW  
    Flattens the positive-dimension tensor optimizer state given by the values
    ``tensors`` for the state ``state_name`` for a single flattened parameter
    ``flat_param`` corresponding to the unflattened parameter names
    ``unflat_param_names`` and unflatted parameter shapes
    ``unflat_param_shapes``. This flattens each unflattened parameter's tensor
    state into one tensor.

    NOTE: We use zero tensors for any unflattened parameters without state
    since some value is required to fill those entries. This assumes that the
    zero tensor is mathematically equivalent to having no state, which is true
    for Adam's "exp_avg" and "exp_avg_sq" but may not be true for all
    optimizers.

    Args:
        state_name (str): Optimizer state name.
        pos_dim_tensors (List[torch.Tensor]): Positive-dimension tensor
            optimizer state values for the unflattened parameters corresponding
            to the single flattened parameter.
        unflat_param_names (List[str]): A :class:`list` of unflattened
            parameter names corresponding to the single flattened parameter.
        unflat_param_shapes (List[torch.Size]): Unflattened parameter shapes
            corresponding to the single flattened parameter.
        flat_param (FlatParameter): The flattened parameter.

    Returns:
        torch.Tensor: A flattened tensor containing the optimizer state
        corresponding to ``state_name`` constructed by concatenating the
        unflattened parameter tensor states in ``pos_dim_tensors`` (using zero
        tensors for any unflattened parameters without the state).
    c                 S   s   g | ]}|d k	r|qS r   r   rm   tr   r   r   rn     s      z/_flatten_tensor_optim_state.<locals>.<listcomp>c                 s   s   | ]}|j V  qd S r   r)   r|   r   r   r   rr     s     z._flatten_tensor_optim_state.<locals>.<genexpr>r>   zAll unflattened parameters comprising a single flattened parameter must have positive-dimension tensor state with the same dtype but got dtypes  for state ! and unflattened parameter names Nr   z6Flattening a zero-dimension parameter is not supportedzBTensor optimizer state does not have same shape as its parameter:  r7   c              	      s>   g | ]6\}}|d k	r$t | nt t j| dqS )N)rG   r)   device)r$   flattenrF   zeros)rm   Zstate_valuer(   Z
cpu_devicer)   r   r   rn     s   
ztensor optim state: z flattened parameter: )rt   rb   r[   rP   iterzipr(   r$   r   catrJ   r_   )rL   r{   r,   ry   r/   non_none_tensorsdtypestensorr(   ZtensorsrU   Zflat_param_shaper   r   r   ru     s0    &



ru   )rL   zero_dim_tensorsr,   r   c              	   C   s   dd |D }t dd |D }t dd |D }t|t|ksZt|dksZt|dkrztd| d| d	|  d
| tt|}tt|}tj||tddS )a  
    Flattens the zero-dimension tensor optimizer state given by the values
    ``zero_dim_tensors`` for the state ``state_name`` for a single flattened
    parameter corresponding to the unflattened parameter names
    ``unflat_param_names`` by enforcing that all tensors are the same and using
    that common value.

    NOTE: The requirement that the tensors are the same across all unflattened
    parameters comprising the flattened parameter is needed to maintain the
    invariant that FSDP performs the same computation as its non-sharded
    equivalent. This means that none of the unflattened parameters can be
    missing this state since imposing a value may differ from having no value.
    For example, for Adam's "step", no value means maximum bias correction,
    while having some positive value means less bias correction.

    Args:
        state_name (str): Optimizer state name.
        zero_dim_tensors (List[torch.Tensor]): Zero-dimension optimizer state
            for the unflattened parameters corresponding to the single
            flattened parameter.
        unflat_param_names (List[str]): A :class:`list` of unflattened
            parameter names corresponding to the single flattened parameter.

    Returns:
        torch.Tensor: A zero-dimensional tensor giving the value of the state
        ``state_name`` for all unflattened parameters corresponding to the
        names ``unflat_param_names``.
    c                 S   s   g | ]}|d k	r|qS r   r   r|   r   r   r   rn   C  s      z8_flatten_zero_dim_tensor_optim_state.<locals>.<listcomp>c                 s   s"   | ]}|d k	r|  nd V  qd S r   )itemr|   r   r   r   rr   E  s     z7_flatten_zero_dim_tensor_optim_state.<locals>.<genexpr>c                 s   s    | ]}|d k	r|j nd V  qd S r   r~   r|   r   r   r   rr   F  s     r>   All unflattened parameters comprising a single flattened parameter must have scalar state with the same value and dtype but got values z and dtypes r   r   r7   r)   r   )rt   rb   r[   rP   r   r$   r   r   )rL   r   r,   r   Z
values_setr   rM   r)   r   r   r   rw   "  s    !

rw   )rL   non_tensorsr,   r   c                 C   s\   dd |D }t |}t|t|ks2t|dkrLtd| d|  d| tt|}|S )a  
    Flattens the non-tensor optimizer state given by the values ``non_tensors``
    for the state ``state_name`` for a single flattened parameter corresponding
    to the unflattened parameter names ``unflat_param_names`` by enforcing that
    all values are the same and using that common value.

    See the note in :func:`_flatten_zero_dim_tensor_optim_state`.

    Args:
        state_name (str): Optimizer state name.
        non_tensors (List[Any]): Non-tensor optimizer state for the unflattened
            parameters corresponding to the single flattened parameter.
        unflat_param_names (List[str]): A :class:`list` of unflattened
            parameter names corresponding to the single flattened parameter.

    Returns:
        Any: A non-tensor giving the value of the state ``state_name`` for all
        unflattened parameters corresponding to the names
        ``unflat_param_names``.
    c                 S   s   g | ]}|d k	r|qS r   r   )rm   ntr   r   r   rn   q  s      z3_flatten_non_tensor_optim_state.<locals>.<listcomp>r>   r   r   z" and  unflattened parameter names )rt   rb   r[   rP   r   )rL   r   r,   Znon_none_non_tensorsZnon_tensor_setrV   r   r   r   rx   X  s    rx   )flat_optim_state_dictrD   r   c                 C   s   | }di i}|d   D ]\}}i |d |< t|D ]\}}t|oP| dk}|sh||d | |< q4|jrtj|d|d}	t|	dkst	|	 t
|	|j}
nt
|j|j}
|
|d | |< q4q|d |d< |S )a^  
    Processes positive-dimension tensor states in ``flat_optim_state_dict`` by
    replacing them with metadata. This is done so the processed optimizer state
    dict can be broadcast from rank 0 to all ranks without copying those tensor
    states, and thus, this is meant to only be called on rank 0.

    Args:
        flat_optim_state_dict (Dict[str, Any]): Flattened optimizer state dict
            with the positive-dimension tensor states unsharded.

    Returns:
        Dict[str, Any]: The flattened optimizer state dict with positive-
        dimension tensor states replaced by metadata.
    r<   r   )rQ   rD   r>   rY   )r^   r   r$   rB   rC   r-   r   Z_get_sharded_sizerb   r_   r'   r)   r(   )r   rD   flat_osdno_tensor_osdr;   param_staterL   rM   is_pos_dim_tensor_stateZsharded_sizeinfor   r   r   _process_pos_dim_tensor_state  s*      r   )processed_optim_state_dictrQ   r   c                 C   s<   |dkr| gndg}t j|d|d |d } | dk	s8t| S )a~  
    Broadcasts the processed optimizer state dict from rank 0 to all ranks.

    Args:
        processed_optim_state_dict (Optional[Dict[str, Any]]): The flattened
            optimizer state dict with positive-dimension tensor states replaced
            with metadata if on rank 0; ignored otherwise.

    Returns:
        Dict[str, Any]: The processed optimizer state dict.
    r   Nsrcr@   )rH   broadcast_object_listr_   )r   rQ   r@   obj_listr   r   r   %_broadcast_processed_optim_state_dict  s
    r   )r   r   rQ   rD   broadcast_devicer   c                 C   s   |dks|dk	st d| }|}|d  D ]\}}	t|	D ]\}
}t|t}|sTq<|dkrz|dk	sht |d | |
 }nd}|j|j }}|jrt||	|
||||||	 q<t	||	|
||||| q<q,|S )a-  
    Takes ``processed_optim_state_dict``, which has metadata in place of
    positive-dimension tensor states, and broadcasts those tensor states from
    rank 0 to all ranks. For tensor states corresponding to FSDP parameters,
    rank 0 shards the tensor and broadcasts shard-by-shard, and for tensor
    states corresponding to non-FSDP parameters, rank 0 broadcasts the full
    tensor.

    Args:
        processed_optim_state_dict (Dict[str, Any]): The flattened optimizer
            state dict with positive-dimension tensor states replaced with
            metadata; this should be returned by
            :meth:`_process_pos_dim_tensor_state` and non-empty on all ranks.
        flat_optim_state_dict (Optional[Dict[str, Any]]): The flattened
            unsharded optimizer state dict with the actual positive-dimension
            tensor states if on rank 0; ignored on nonzero ranks.

    Returns:
        Dict[str, Any]: The optimizer state dict with the positive-dimension
        tensor state correctly populated via ``broadcast()`` s from rank 0.
    r   Nz<Expects rank 0 to pass in the flattened optimizer state dictr<   )
r_   r^   r   r6   r'   r(   r)   r-   '_broadcast_sharded_pos_dim_tensor_state)_broadcast_unsharded_pos_dim_tensor_state)r   r   rQ   rD   r@   r   r   r   r;   r   rL   rM   r   unsharded_tensorr(   r)   r   r   r    _broadcast_pos_dim_tensor_states  sR    

r   )	r   r   rL   r(   r)   r   rQ   rD   r   c	                 C   s   d}	|dkr*| dk	st dttj| }	td|D ]d}
|dkrb|	dk	sLt |	|
|d |}ntj|d||d}t	j
|d|d ||
kr|||< q4~q4|dkrdS |	d|d |||< dS )a  
    Broadcasts positive-dimension tensor state for the state ``state_name``
    corresponding to an FSDP parameter shard-by-shard, only to be saved on the
    relevant rank. This modifies ``param_state`` destructively.

    Args:
        unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor from which
            to broadcast shards if on rank 0; ignored otherwise.
        shape (torch.Size): Shape of the sharded tensor; same on all ranks.
    Nr   .Expects rank 0 to pass in the unsharded tensorr>   FZrequires_gradr)   r   r   )r_   	functoolspartialr   rv   rO   rF   r$   r   rH   	broadcast)r   r   rL   r(   r)   r   rQ   rD   r@   Z	get_shardZtarget_rankZsharded_tensorr   r   r   r     s6    
r   )r   r   rL   r(   r)   r   rQ   r   c                 C   s   |dkrd| dk	st d|| jks8t d| d| j || jksXt d| d| j | |} ntj|d||d} tj| d|d	 | ||< dS )
aZ  
    Broadcasts positive-dimension tensor state for the state ``state_name``
    corresponding to an unsharded non-FSDP parameter from rank 0 to all ranks.
    This modifies ``param_state`` destructively.

    Args:
        unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor to
            broadcast if on rank 0; ignored otherwise.
    r   Nr   zShape mismatch: r   zdtype mismatch: Fr   r   )r_   r(   r)   rF   r$   r   rH   r   )r   r   rL   r(   r)   r   rQ   r@   r   r   r   r   =  s,    r   )sharded_osdrX   optimoptim_inputusing_optim_inputr   c                    s  |rt ||nt|}t|}t|t|ks4ti }i  | D ]8\}}	||krVqD|| }
|
|t|	< |	D ]}|
 |< qnqD| d }i }| D ]\}}||j }
|||
< qg }| d D ]>}t	
|}tt fdd|d D }||d< || q||dS )a  
    Rekeys the optimizer state dict from unflattened parameter names to
    flattened parameter IDs according to the calling rank's ``optim``, which
    may be different across ranks. In particular, the unflattened parameter
    names are represented as :class:`_OptimStateKey` s.
    r<   rY   c                 3   s   | ]} | V  qd S r   r   rl   Z"unflat_param_name_to_flat_param_idr   r   rr     s   z2_rekey_sharded_optim_state_dict.<locals>.<genexpr>paramsrZ   )'_get_param_to_param_id_from_optim_input_get_param_to_param_idrE   r]   rb   r_   r^   ra   r,   rc   rd   r   rt   rR   )r   rX   r   r   r   Zparam_to_flat_param_idrf   Z#unflat_param_names_to_flat_param_idrh   r,   flat_param_idrj   Zsharded_osd_stateZrekeyed_osd_stater;   r   Zrekeyed_osd_param_groupsunflat_param_groupflat_param_groupZflat_param_idsr   r   r   _rekey_sharded_optim_state_dictg  s>    



r   )rX   c                 C   s>   i }|   D ],}t|tjr|  |jD ]}|||< q*q|S )a  
    Constructs a mapping from FSDP flattened parameters to their owning FSDP
    modules and ensures that all FSDP modules are initialized.

    Args:
        model (torch.nn.model): Root module (which may or may not be a
            :class:`FullyShardedDataParallel` instance).

    Returns:
        Dict[FlatParameter, FullyShardedDataParallel]: Mapping from FSDP
            flattened parameters to their owning FSDP modules.
    )modulesr6   rE   ZFullyShardedDataParallelZ
_lazy_initr   )rX   re   modulerh   r   r   r   r\     s    
r\   )r   c                 C   s,   g }| j D ]}|d D ]}|| qq
|S )z
    Constructs a mapping from parameter IDs to parameters. This may be used
    both for models with ``FlatParameter`` s and without.
    r   )rY   rR   )r   param_id_to_paramparam_grouprh   r   r   r   _get_param_id_to_param  s
    
r   )rX   r   r   c           	      C   s   |dkrt |  S zt |}W n" tk
rB   td| Y nX t|dkrXtdd}d}|D ]"}|t|tjM }|t|tM }qd|s|std|r|S |st	g }|D ]0}d|k}|st	d|d D ]}|
| qq|S )	an  
    Constructs a mapping from parameter IDs to parameters. This may be used
    both for models with ``FlatParameter`` s and without.

    NOTE: This method is only preserved for backward compatibility. The method
    :meth:`_get_param_id_to_param` is the preferred code path that does not
    rely on ``optim_input``.

    NOTE: We critically assume that, whether the optimizer input is a list of
    parameters or a list of parameter groups, :class:`torch.optim.Optimizer`
    enumerates the parameter IDs in order. In other words, for a parameter list
    input, the parameter IDs should be in that list order, and for a parameter
    groups input, the parameter IDs should be in order within each parameter
    group and in order across parameter groups.

    Args:
        model (torch.nn.Module): Model whose parameters are passed into the
            optimizer.
        optim_input (Optional[Union[List[Dict[str, Any]],
        Iterable[torch.nn.Parameter]]]): Input passed into the optimizer
            representing either a :class:`list` of parameter groups or an
            iterable of parameters; if ``None``, then this method assumes the
            input was ``model.parameters()``. (Default: ``None``)

    Returns:
        List[torch.nn.Parameter]: Mapping from parameter IDs to parameters,
        where the parameter ID is implicitly the index in the :class:`list`.
    NzCOptimizer input should be an iterable of Tensors or dicts, but got r   z#Optimizer input should not be emptyTz9Optimizer input should be an iterable of Tensors or dictsr   zNA parameter group should map "params" to a list of the parameters in the group)r5   
parameters	TypeErrorrb   r[   r6   r$   r%   dictr_   rR   )	rX   r   r   Zall_tensorsZ	all_dictsrh   r   r   Zhas_params_keyr   r   r   '_get_param_id_to_param_from_optim_input  s:    '
r   )r   r   c                 C   s   t | }dd t|D S )AConstructs the inverse mapping of :func:`_get_param_id_to_param`.c                 S   s   i | ]\}}||qS r   r   rm   Zparam_idrh   r   r   r   
<dictcomp>  s      z*_get_param_to_param_id.<locals>.<dictcomp>)r   	enumerate)r   r   r   r   r   r     s    r   c                 C   s   t | |}dd t|D S )r   c                 S   s   i | ]\}}||qS r   r   r   r   r   r   r   '  s      z;_get_param_to_param_id_from_optim_input.<locals>.<dictcomp>)r   r   )rX   r   r   r   r   r   r     s    

r   )flat_to_unflat_param_idsr   c                    s   i  |   D ]2\}}|D ]$}| ks4td| d| |< qqt }t  }|tt|kstdt|d  d |   fddt|D S )a  
    Inverts the mapping ``flat_to_unflat_param_ids`` to be from unflattened
    parameter ID to flattened parameter ID, where the unflattened parameter ID
    is the index in the returned :class:`list`. There may be multiple
    unflattened parameter IDs mapping to the same flattened parameter ID.

    Args:
        flat_to_unflat_param_ids (Dict[int, List[int]]): A mapping from
            flattened parameter ID to a :class:`list` of corresponding
            unflattened parameter IDs.

    Returns:
        List[int]: A mapping from unflattened parameter ID to flattened
        parameter ID, where the unflattened parameter ID is the index in the
        :class:`list`.
    z<`flat_to_unflat_param_ids` has the unflattened parameter ID z+ mapped to multiple flattened parameter IDsz8The set of unflattened parameter IDs should be {0, ..., r>   z
} but got c                    s   g | ]} | qS r   r   )rm   unflat_param_idZunflat_to_flat_param_idsr   r   rn   O  s   z1_get_unflat_to_flat_param_ids.<locals>.<listcomp>)r^   r_   rb   rt   r   rO   r#   )r   r   Zunflat_param_idsr   Znum_unflat_param_idsZunflat_param_ids_setr   r   r   _get_unflat_to_flat_param_ids*  s*    



r   )xr   c                 C   s   t | o|  dkS )Nr   )r$   rB   rC   )r   r   r   r   rK   U  s    rK   )rX   r   r   
rank0_onlyr2   r@   r   r   c           '         s  |  }|d |d  }}	t|}
| p4|
dkp4|}|rDi g dni }|rT|d nd}t| |rpt| |nt| i }t }t	 D ]D\}}||krqt
t| t|td}|
dkr|||< |||< q|
dkr|gndg}tj|d|d |d dk	st|d }g }| D ]F}||kr8|| q|| }|dkrX|t k stdqtd	tj }tjt|gtj|d
}tj||d | dkr,dd tt|D }tj|||d d}t	|D ]D\}
}ttt
 |}t|dkr|d|
 ddd |D  7 }qt |t!| }| D ]}|| } | }|j"r|| }t#tt||| |||}|r$t|t|j$kstt%|j$|D ]\}}|||< qnj|r<t|j$dkst|j$d }t&&|| ||< t'|| D ]&\} }!t(|!r|!) || | < qq<|s2i S |d }"|	D ]T}#t&*|#}$ fdd|#d D }%fdd|%D }&dd |&D |$d< |"|$ q>|S )a  
    Consolidates the optimizer state and returns it as a :class:`dict`
    following the convention of :meth:`torch.optim.Optimizer.state_dict`,
    i.e. with keys ``"state"`` and ``"param_groups"``.
    The flattened parameters in ``FSDP`` modules contained in ``model``
    are mapped back to their unflattened parameters.

    Args:
        model (torch.nn.Module): Root module (which may or may not be a
            :class:`FullyShardedDataParallel` instance) whose parameters
            were passed into the optimizer ``optim``.
        optim (torch.optim.Optimizer): Optimizer for ``model`` 's
            parameters.
        rank0_only (bool): If ``True``, saves the populated :class:`dict`
            only on rank 0; if ``False``, saves it on all ranks. (Default:
            ``True``)
        shard_state (bool): If ``True``, shard and distribute all
            non-zero-dimension states.

    Returns:
        Dict[str, Any]: A :class:`dict` containing the optimizer state for
        ``model`` 's original unflattened parameters and including keys
        "state" and "param_groups" following the convention of
        :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``,
        then nonzero ranks return an empty :class:`dict`.
    r<   rY   r   rZ   N)r,   r-   r   z/Check the `flat_param_id_to_param` constructionrI   r   r?   c                 S   s   g | ]}d qS r   r   )rm   rT   r   r   r   rn     s     z%_optim_state_dict.<locals>.<listcomp>zFSDP currently requires each rank to have at least the optimizer states needed by rank 0's optimizer but some ranks are missing some of those statesz
Rank z' is missing states for the parameters: c                 S   s   g | ]
}|j qS r   )r,   )rm   r;   r   r   r   rn     s     r>   c                    s   g | ]} | qS r   r   )rm   r   )flat_param_id_to_paramr   r   rn     s   r   c                    s   g | ]} | qS r   r   )rm   rh   )rf   r   r   rn     s    c                 S   s   g | ]}|D ]}|qqS r   r   )rm   r,   rj   r   r   r   rn     s    )+Z
state_dictrH   Zget_rankrE   r]   r   r   collectionsOrderedDictr   r+   ra   r6   r   r   r_   valuesrR   rb   r$   r   rI   Zcurrent_devicer   Zint32Z
all_reducer   rO   Zget_world_sizeZall_gather_objectr   r   RuntimeErrorr\   r-   r=   r,   r   rc   r   rB   r7   rd   )'rX   r   r   r   r2   r@   r   ZosdZ	osd_stateZosd_param_groupsrQ   r1   Zfsdp_osdZfsdp_osd_stateZ optim_state_key_to_flat_param_idZ#r0_flat_param_id_to_optim_state_keyr   rh   Zoptim_state_keyZkey_obj_listZmissing_keysZr0_optim_state_keyr   Znum_missingr   	error_msgr   re   r8   Zunflat_staterj   r9   rL   rM   Zfsdp_osd_param_groupsr   r   Zparam_group_paramsZnested_unflat_param_namesr   )r   rf   r   _optim_state_dictY  s    (










r   )N)N)Hr   rc   r   typingr   r   r   r   r   r   r   r	   r
   r   r   r$   Ztorch.distributedZdistributedrH   Z2torch.distributed.fsdp.fully_sharded_data_parallelZfsdpZfully_sharded_data_parallelrE   Ztorch.nnnnZ'torch.distributed._shard.sharded_tensorr   Z#torch.distributed.fsdp._shard_utilsr   Z!torch.distributed.fsdp.flat_paramr   r   Z'torch.distributed.fsdp._fsdp_extensionsr   r#   r   r   r'   r+   r.   r=   r3   r4   Modulerk   r`   r%   r*   ru   rw   rx   intr   r   r   r   r)   r   r   r   Z	Optimizer	Parameterr   r\   r   r   r   r   r   rK   ZProcessGroupr   r   r   r   r   <module>   s8  4$
8
F?

;
 T7(

)


H
7
+


= 

M 
+

