a
    dn                    @   sf  d dl Z d dlZd dlmZmZ d dlmZm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mZ d dlZd dlmZ d dlmZ d dlm  mZ d dlmZ d dlm Z  d dl!m"Z"m#Z# dd	l$m%Z%m&Z& dd
l'm(Z(m)Z)m*Z*m+Z+m,Z, g dZ-G dd deZ.G dd deZ/G dd deZ0G dd deZ1G dd dej2Z3G dd dZ4ee4df Z5dS )    N)autoEnum)
accumulatechain)AnyDict	GeneratorIteratorList
NamedTupleno_type_checkOptionalSequenceSetTupleUnion)Tensor)DTensor)_set_fsdp_flattenedHandleTrainingState   )_ext_post_unflatten_transform_ext_pre_flatten_transform)_alloc_storage_free_storage_no_dispatch_record_stream_same_storagep_assert)FlatParameterFlatParamHandleFlatParamShardMetadata	ParamInfoSharedParamInfoHandleShardingStrategyc                   @   s,   e Zd ZU dZeed< ejed< eed< dS )r!   z-Information for an original module parameter.
param_namemodulemodule_nameN__name__
__module____qualname____doc__str__annotations__nnModule r0   r0   j/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torch/distributed/fsdp/flat_param.pyr!   H   s   

r!   c                   @   sF   e Zd ZU dZeed< ejed< eed< eed< ejed< eed< dS )	r"   ai  
    Additional information for a shared parameter.

    For each shared parameter, we designate one module and its parameter
    variable to be the primary owner, determined as the first one encountered
    in the parameter walk. These are prefixed with "prim". The primary module
    and parameter do not have their own :class:`SharedParamInfo` instance.
    r$   r%   r&   prim_param_nameprim_moduleprim_module_nameNr'   r0   r0   r0   r1   r"   P   s   
	

r"   c                   @   s\   e Zd ZU dZeedf ed< eejdf ed< ee	df ed< eee	e	f df ed< dS )r    a  
    This holds metadata specific to this rank's shard of the flattened
    parameter.

    Attributes:
        param_names (Tuple[str, ...]): Prefixed parameter names of this rank's
            shard of the parameters; see :class:`FlatParameter`.
        param_shapes (Tuple[torch.Size, ...]): Parameter shapes of this rank's
            shard of the parameters; see :class:`FlatParameter`.
        param_numels (Tuple[int, ...]): Parameter numels of this rank's shard
            of the parameters; see :class:`FlatParameter`.
        param_offsets (Tuple[Tuple[int, int], ...]): [start, end] offsets (in
            units of numels) giving this rank's part of each flattened
            original module parameter.
    .Zparam_namesZparam_shapesZparam_numelsparam_offsetsN)
r(   r)   r*   r+   r   r,   r-   torchSizeintr0   r0   r0   r1   r    b   s
   
r    c                   @   s*   e Zd Ze Ze Ze Ze Ze ZdS )r#   N)	r(   r)   r*   r   Z
FULL_SHARDZSHARD_GRAD_OPNO_SHARDZHYBRID_SHARDZ_HYBRID_SHARD_ZERO2r0   r0   r0   r1   r#   |   s
   r#   c                
   @   s\   e Zd ZdZee ee eej ee	 ee
 ee eeej  eeej  dd	ddZdS )r   aE  
    This is the flattened parameter used by :class:`FullyShardedDataParallel`.
    It is comprised of one or more original parameters, which are flattened
    and concatenated to construct the flattened parameter.

    Under the current design, this parameter logically represents both the
    unsharded and sharded flattened parameter, and its data changes storages
    dynamically.
        - In the :class:`FullyShardedDataParallel` constructor, the parameter
        is initialized as unsharded and then sharded in-place.
        - At runtime, the parameter is lazily (re)-initialized. The sharded
        parameter data is saved in ``self._local_shard``, and a new ``Tensor``
        ``self._full_param_padded`` is created, which is the all-gather
        destination and owns the unsharded parameter storage thereafter. (See
        :meth:`FlatParamHandle.init_flat_param_attributes`.)
        - Throughout runtime, the parameter data changes storages as needed,
        e.g. to the sharded flattened parameter, reduced-precision sharded
        flattened parameter, or the unsharded flattened parameter.

    Attributes:
        _unpadded_unsharded_size (torch.Size): Unsharded flattened parameter's
            size without padding.
        _padded_unsharded_size (torch.Size): Unsharded flattened parameter's
            size with padding. This is only set for sharded strategies since
            they require padding for the all-gather.
        _sharded_size (torch.Size): Sharded flattened parameter's size with
            padding. This is also set for ``NO_SHARD``, in which case it is the
            same as the unsharded sizes. (We omit "padded" because there is no
            analogous unpadded one.)

        _param_infos (Tuple[ParamInfo, ...]): Each parameter's parameter info
            entry; see :class:`ParamInfo`.
        _numels (Tuple[int, ...]): Each parameter's numel.
        _shapes (Tuple[torch.Size, ...]): Each parameter's shape.
        _fqns (Tuple[str, ...]): The original parameters' FQNs prefixed from
            the owning handle's ``_fully_sharded_module``. The names are
            guaranteed to be unique within the subtree rooted at that module.
        _num_params (int): Number of original parameters flattened into this
            flattened parameter; this is the length of ``_param_infos``,
            ``_numels``, ``_shapes``, and ``_fqns``.
        _shared_param_infos (Tuple[SharedParamInfo, ...]): Shared parameter
            info entries; see :class:`SharedParamInfo`.
        _param_extensions (Tuple[Optional[Any], ...]): Parameter extensions
            (i.e. some per-parameter state) used to customize pre-flatten and
            post-unflatten behavior. This is experimental, and users should not
            depend on its existence in the future.
        _modules (Set[nn.Module]): Modules that contain some original parameter
            that is flattened into the ``FlatParameter``.

        _shard_param_offsets (List[Tuple[int, int])): [start, end] offsets (in
            units of numel) giving this rank's part of each flattened original
            module parameter; for any parameter ``p`` that is not sharded
            across ranks, this will be [0, ``p.numel()``-1].
        _shard_indices (Tuple[int, int]): [start, end] indices (in units of
            parameters) for this rank's shard of the original model parameters,
            where the parameters follow the order in which they were originally
            flattened; this indexes appropriately into any data structure that
            follows the flattening order (e.g. ``_param_infos``, ``_numels``,
            etc.).
        _shard_numel_padded (int): Numel padded for this rank's sharded
            flattened parameter.

        _local_shard (Tensor): Sharded flattened parameter with padding if
            using a sharded strategy. If using ``NO_SHARD``, then this is the
            unpadded unsharded flattened parameter, and there is no notion of a
            sharded flattened parameter or padded unsharded flattened
            parameter.
        _full_param_padded (Tensor): Unsharded flattened parameter with
            padding. This is not defined for ``NO_SHARD``. When using mixed
            precision for parameters, this has the low precision.
        _full_prec_full_param_padded (Tensor): Full precision unsharded
            flattened parameter with padding. This is used for unsharding
            outside of computation when using mixed precision for parameters.
            This is never defined for ``NO_SHARD``.
        _post_backward_hook_state (Tuple[AccumulateGrad, RemovableHandle]):
            Flattened parameter's :class:`AccumulateGrad` object and
            post-backward hook handle.
        _mp_shard (Tensor): Low precision sharded flattened parameter with
            padding. This is only defined when parameter mixed precision is
            enabled. For ``NO_SHARD``, this is used for computation.
        _cpu_grad (Tensor): Sharded gradient with padding stored on CPU.
            This is only defined when offloading parameters is enabled.
        _saved_grad_shard (Tensor): Sharded gradient with padding from previous
            iterations for gradient accumulation without :meth:`no_sync`.

        _params (Optional[List[nn.Parameter]]): The original parameter
            variables if ``use_orig_params=True`` and ``None`` otherwise.
        _shared_params (Optional[List[nn.Parameter]]): The original shared
            parameter variables if ``use_orig_params=True`` and ``None``
            otherwise.
        _tensors (Optional[List[Optional[Tensor]]]): This saves the ``Tensor``
            views created in the forward and tracked by autograd when
            ``use_orig_params=True`` and is ``None`` otherwise. This is to
            preserve those ``Tensor`` variables for the backward to ensure that
            the ``FlatParameter`` 's ``AccumulateGrad`` object does not change
            in which case the post-backward hook does not run. This is relevant
            for cases like reentrant activation checkpointing.
        _is_grad_none (Optional[List[bool]]): A mask over the original
            parameters' gradients indicating if it is logically ``None`` or not
            if ``use_orig_params=True`` and ``None`` otherwise. This is needed
            because only some of the parameters may have ``None`` gradient, in
            which case the ``FlatParameter`` gradient must be non-``None`` and
            must use zeros to approximate those original ``None`` gradients.
            This mask informs FSDP to set the original parameter gradients to
            ``None`` (instead of zeros) as needed.
    N)	param_infosnumelsshapesfqnsshared_param_infosparam_extensionsparamsshared_paramsreturnc	           
      C   s  t |t |ksJ t |t |ks(J t |t |ks<J t |t |ksPJ t || _t|| _t|| _t|| _t|| _t|| _t|| _dd | jD 	dd | jD | _
|du |du ksJ |durR|durt |t |ksJ || _|| _t| j| jD ]}	t|	 qdd tt |D | _dd tt | jD | _nd| _d| _d| _d| _|  | _t|  d| _dS )	a  
        Initializes attributes holding metadata about the original parameters
        comprising the flattened parameter.

        We expose this method separate from the constructor to keep the
        constructor only responsible for the flattened parameter's tensor data.
        This method should only be called once per model, while the constructor
        may be called multiple times, e.g. when reloading from a checkpoint, in
        which case only the tensor data needs to be passed to the constructor.
        Since :meth:`load_state_dict` is implemented via :meth:`copy_`, the
        metadata is correctly assumed to be unchanged.

        Args:
            See the Attributes in the class docstring.
        c                 S   s   h | ]
}|j qS r0   r%   .0pir0   r0   r1   	<setcomp>      z/FlatParameter._init_metadata.<locals>.<setcomp>c                 S   s   h | ]
}|j qS r0   rC   rE   Zspir0   r0   r1   rG     rH   Nc                 S   s   g | ]}d qS )Fr0   rE   _r0   r0   r1   
<listcomp>#  s   z0FlatParameter._init_metadata.<locals>.<listcomp>c                 S   s   g | ]}d qS Nr0   rJ   r0   r0   r1   rL   &  s   F)lenZ_num_paramstuple_param_infos_numels_shapes_fqns_shared_param_infos_param_extensionsunionZ_modules_params_shared_paramsr   r   range_is_grad_none_tensorssize_unpadded_unsharded_size_post_backward_called)
selfr:   r;   r<   r=   r>   r?   r@   rA   paramr0   r0   r1   _init_metadata   sH    











zFlatParameter._init_metadata)r(   r)   r*   r+   r
   r!   r8   r6   r7   r,   r"   r   r   r.   	Parameterra   r0   r0   r0   r1   r      s   mr   c                       s  e Zd ZdZeej ejej	e
eeej eej eejed
 fddZeeej  ejeddddZeeej eed	d
dZeej eej ddddZe dd ZeeeddddZeeeeeeef df eeef f dddZeeeeeeef dddZeeeeeeef dddZeeeeejdddZ e!eeef  dd d!Z"e#dd"d#Z$e%e ddd$d%Z&edd&d'Z'd(d) Z(d*d+ Z)edd,d-Z*d.d/ Z+ejdd0d1Z,eed2d3d4Z-ejdd2d5d6Z.d7d8 Z/d9d: Z0e d;d< Z1d=d> Z2d?d@ Z3dAdB Z4e5j6dCdD Z7edEdFdGZ8dHdI Z9dJdK Z:dddLdMZ;edeeej e<e dNdOdPZ=eddQdRdSZ>dddTdUZ?e5j6e@ddVdWZAe dddXdYZBe dddZd[ZCe edd\d]ZDee eeejeedd^d_d`ZEdadb ZFdcdd ZGdedf ZHeIej ddgdhZJeedidjdkZKe<eeLeLf  ddldmZMe<eeLeLf  ddndoZNeOe!eL ddpdqZPeOee ddrdsZQdddtduZRdvdw ZSedxdydzZTedxd{d|ZUeedxd}d~ZVeedxddZWdd ZXedxddZYedxddZZeOedddZ[eOedddZ\eOedddZ]eOedddZ^  Z_S )r   a  
    This handle manages a flattened parameter (:class:`FlatParameter`). This
    includes sharding and view management.

    Args:
        params (Sequence[nn.Parameter]): The parameters to use for the
            flattened parameter.
        fully_sharded_module (nn.Module): See [Note: Fully Sharded Module].
        device (torch.device): The compute and communication device, which
            should be a non-CPU device. We refer to it as the compute device.
        sharding_strategy (ShardingStrategy): Sharding strategy to apply to
            this handle's ``FlatParameter``.
        offload_params (bool): Whether to offload the handle's
            ``FlatParameter`` to CPU.
        mp_param_dtype (Optional[torch.dtype]): Parameter mixed precision
            setting passed to the FSDP constructor.
        mp_reduce_dtype (Optional[torch.dtype]): Gradient reduction mixed
            precision setting passed to the FSDP constructor.
        keep_low_precision_grads (bool): Whether to keep gradients in low
            precision.
        use_orig_params (bool): If ``True``, then FSDP preserves the original
            parameter variables and returns them from ``named_parameters()``
            (e.g. to support different optimizer hyperparameters within one
            :class:`FlatParameter`). If ``False``, then FSDP reconstructs the
            parameter every iteration and returns the :class:`FlatParameter` s
            from ``named_parameters()``.
    )
r@   fully_sharded_moduledevicesharding_strategyoffload_paramsmp_param_dtypemp_reduce_dtypekeep_low_precision_gradsprocess_groupuse_orig_paramsc                    s   t    || _|	| _|	 | _|	 | _|| _|| _|
| _	|| _
tj| _t | _|| _| |||
 | jj| _| jdd | || d S )NF	as_params)super__init__rd   rj   rankr\   
world_size_sharding_strategy_offload_params_use_orig_params_keep_low_precision_gradsr   IDLE_training_statedistZget_debug_level_debug_levelZ_fully_sharded_module_init_flat_param
flat_paramdtype_orig_param_dtype_use_unsharded_views_init_param_reduce_dtypes)r_   r@   rc   rd   re   rf   rg   rh   ri   rj   rk   	__class__r0   r1   ro   U  s     




zFlatParamHandle.__init__N)r@   r%   rk   rB   c                 C   sJ  t |}|d t|dkr&tdg }g }g }g }g }	i }
g }g }g }d}d}| D ]`\}}|jddD ]H\}}||vrqp||
v r|
| \}}}|| |	t|||||| qpt|t	u rtd|dur|j
|krtd| d|j
 |du r| std	|dur4|j|kr4td
t|\}}|| |j
}|j}|||f|
|< || |t||| ||  ||j |r|d | n|}|| qpqZ|dusJ d| d| t||| _tttjtjf  ttj ddd}| j|||||	||r0||nd|r@||nd dS )a  
        Initializes the flattened parameter ``self.flat_param`` by flattening
        the parameters in ``params`` into a single :class:`FlatParameter` and
        saves relevant metadata. Shared parameters are only included in the
        flattened parameter once.

        This checks that all comprising parameters have the same dtype and
        ``requires_grad`` and does not support nested construction of
        :class:`FlatParameter` s.

        Args:
            See the Args in the class docstring.
        Nr   z@Cannot initialize a `FlatParameter` from an empty parameter listF)Zrecursez(`FlatParameter` does not support nestingz/`FlatParameter` requires uniform dtype but got z and z"Integer parameters are unsupportedz0`FlatParameter` requires uniform `requires_grad`.z=Passed-in `params` were not found in the module tree
params: z	
module: )tensorsrB   c                 S   s   dd | D S )Nc                 S   s&   g | ]}t |tjr|nt|qS r0   )
isinstancer.   rb   )rE   tr0   r0   r1   rL     s   zOFlatParamHandle._init_flat_param.<locals>.convert_to_params.<locals>.<listcomp>r0   )r   r0   r0   r1   convert_to_params  s    z;FlatParamHandle._init_flat_param.<locals>.convert_to_params)setdiscardrN   
ValueErrorZnamed_modulesZnamed_parametersappendr"   typer   r|   Zis_floating_pointrequires_gradr   r!   numelshaper   flatten_paramsr{   r
   r   r6   r   r.   rb   ra   )r_   r@   r%   rk   Z
params_setr:   r;   r<   r=   r>   Zshared_param_memoZparams_to_flattenrA   r?   r|   r   Zsubmodule_name	submoduler$   r`   r3   r4   r2   	extensionZfqnr   r0   r0   r1   rz   s  s    




z FlatParamHandle._init_flat_param)r@   r   rB   c                 C   sT   t  , dd | D }t j|dd}W d   n1 s:0    Y  t||d}|S )a  
        Flattens the parameters in ``params`` into a single
        :class:`FlatParameter`. This should be the only way used to construct
        :class:`FlatParameter` s.

        We expose this factory method for checkpointing (e.g. sharded state
        dict). The flattened parameter's metadata should only be initialized
        once (see :meth:`_init_metadata`), but its tensor data may be reloaded.
        c                 S   s0   g | ](}t |tjr"| d n|d qS ))r   r.   rb   detachreshape)rE   pr0   r0   r1   rL     s   z2FlatParamHandle.flatten_params.<locals>.<listcomp>r   ZdimN)r   )r6   no_gradcatr   )r@   r   Zflat_paramsZflat_param_datar{   r0   r0   r1   r     s    
,zFlatParamHandle.flatten_params)rg   rh   rB   c                 C   sh   |du| _ |du| _| j r0| js0|| _| j| _n|p8| j| _|pD| j| _| jdusVJ | jdusdJ dS )aM  
        Precondition: ``self.flat_param`` is set via :meth:`_init_flat_param`.
        This ensures that this handle's parameters have a single dtype.

        Postcondition: This sets ``self._fwd_bwd_param_dtype`` and
        ``self._reduce_dtype``. If ``mp_param_dtype`` or ``mp_reduce_dtype``
        is ``None``, then we assume the original parameter dtype. One special
        case is if ``mp_param_dtype`` is not ``None`` and ``mp_reduce_dtype``
        is ``None``, in which case we assume the gradient reduction dtype
        matches the forward/backward parameter dtype.
        N)_low_prec_param_dtype_specified _low_prec_reduce_dtype_specified_fwd_bwd_param_dtype_reduce_dtyper}   )r_   rg   rh   r0   r0   r1   r     s    


z)FlatParamHandle._init_param_reduce_dtypesc                 C   s   | j }| js$| dd| d  nt| dkd | }t|| j	| j
\}}|| | | j	 }| | j	d  d }| ||| | dkr|d | jr|   dS )a  
        Shards the handle's ``FlatParameter``. In terms of memory, this
        allocates new memory for the sharded flattened parameter and frees the
        unsharded flattened parameter's storage.

        Postcondition: ``self.flat_param`` is the sharded flattened parameter.
        Shard metadata attributes are set for all sharding strategies.
        ``process_group``, ``rank``, and ``world_size`` attributes are set if
        using a sharded strategy.
        r   r   z;The `FlatParameter` is not the sole occupant of its storageN)r{   uses_sharded_strategy_init_shard_metadatar   r   Zstorage_offset_typed_storager   
_get_shardrp   rq   set__sizeZ_resize_rt   _use_sharded_views)r_   r{   Zorig_storagesharded_flat_paramnumel_paddedstartendr0   r0   r1   shard!  s&    



zFlatParamHandle.shard)r   r   r   rB   c                 C   sx   | j  | j _| j  }t|dko(||kd| d|  t||kd| d|  | ||\| j _| j _|| j _dS )a  
        Initializes shard-related metadata for this rank's shard of the
        flattened parameter: ``_sharded_size``, ``_shard_param_offsets``,
        ``_shard_indices``, and ``_shard_numel_padded``.

        Args:
            numel_padded (int): Numel padded for this rank's sharded flattened
                parameter.
            start (int): Start index in the sharded flattened parameter
                assigned to this rank.
            end (int): End index (inclusive) in the sharded flattened parameter
                assigned to this rank. If this exceeds the sharded flattened
                parameter's numel, then it is truncated.

        Precondition: ``self.flat_param`` 's data is the sharded flattened
        parameter.
        r   zstart: z end: znumel_padded: z sharded_flat_param_numel: N)	r{   r\   _sharded_sizer   r   _get_shard_metadata_shard_param_offsets_shard_indicesZ_shard_numel_padded)r_   r   r   r   Zsharded_flat_param_numelr0   r0   r1   r   B  s    
"
z$FlatParamHandle._init_shard_metadata.)r   r   rB   c                 C   s   |   }g }g }t|D ]Z\}\}}||ks||k r6q||krDd}	n|| }	t||| }
|| ||	|
f qt|dkrd}t|dksJ n0|d |d f}t||d |d  d ksJ t||fS )a  
        Computes the shard metadata based on ``start`` and ``end``, which give
        the closed interval of the unsharded flattened parameter specifying the
        shard.

        Args:
            start (int): Start index (in units of numel) of this rank's shard
                of the flattened parameter.
            end (int): End index (in units of numel and inclusive) of this
                rank's shard of the flattened parameter.

        Return:
            Tuple[Tuple[Tuple[int, int], ...], Tuple[int, int]]: See
            ``_shard_param_offsets`` and ``_shard_indices`` in
            :class:`FlatParameter` 's docstring.
        r   )r   r   r   r   )_get_flat_param_offsets	enumerateminr   rN   rO   )r_   r   r   Zflat_param_offsetsZshard_param_indices_rangeZshard_param_offsetsiparam_start	param_endZintra_param_startZintra_param_endZshard_param_indicesr0   r0   r1   r   g  s2    
z#FlatParamHandle._get_shard_metadata)tensorrp   rq   rB   c                 C   sd   t | |}t||d k r0|d d}n|| }|d  |  }|dks\J d||fS )aa  
        Returns the shard of ``tensor`` without any padding for the given
        ``rank`` and ``world_size`` and the numel to pad for that shard.

        If ``tensor`` is already flattened or may be viewed in the flattened
        shape (which is true in the expected usage), then this method does not
        allocate any new tensor memory.
        r   r   z5Chunk's size should be at most the first chunk's size)r6   flattenchunkrN   Z	new_emptyr   )r   rp   rq   chunksr   numel_to_padr0   r0   r1   _get_unpadded_shard  s    z#FlatParamHandle._get_unpadded_shardc                 C   s:   t | ||\}}| }|dkr2t|d|g}||fS )a(  
        Returns the shard of ``tensor`` with padding for the given ``rank`` and
        ``world_size`` and the numel padded for that shard.

        This method allocates new memory (via :meth:`clone`) since the
        unsharded ``tensor`` may be deallocated after this method returns.
        r   )r   r   cloneFpad)r   rp   rq   r   r   r   r0   r0   r1   r     s    zFlatParamHandle._get_shardc                 C   s^   t | jdksJ | j t| ||\}}| }t |dksJJ | t|d | gS )z
        Returns the shape of ``tensor`` after sharding including padding. This
        requires ``tensor`` to have 1D shape and ensures that the returned
        shape is 1D.
        r   r   )rN   r   r   r   r\   r6   r7   )r   rp   rq   Zunpadded_sharded_tensorr   Zunpadded_sharded_sizer0   r0   r1   _get_sharded_size  s    z!FlatParamHandle._get_sharded_size)rB   c                 C   sB   t t| jj}dg|dd  }dd |D }t t||}|S )zReturns [start, end] offsets of each original parameter's flattened
        data in the unsharded flattened parameter (without padding).r   Nr   c                 S   s   g | ]}|d  qS )r   r0   )rE   r   r0   r0   r1   rL     rH   z;FlatParamHandle._get_flat_param_offsets.<locals>.<listcomp>)listr   r{   rQ   zip)r_   Zcumulative_sumZstartsZendsr5   r0   r0   r1   r     s
    z'FlatParamHandle._get_flat_param_offsetsc                 C   s   t | jdrt | jds J d| jjd }| jjd }||krNt||d ntdd}t| jj| | jj| | jj| | jjdd S )z`Returns shard-related metadata specific to this rank's shard of the
        flattened parameter.r   r   z'Shard metadata has not been initializedr   r   N)	hasattrr{   r   slicer    rS   rR   rQ   r   )r_   Zshard_param_start_indexZshard_param_end_indexslr0   r0   r1   shard_metadata  s"    


zFlatParamHandle.shard_metadatac                 C   sH  | j }|j| jkr<| js |j| _| js4| js4|j| _|j| _td}| j	rft
|j|kd|j  n| | j  |j|_| j	r|j |_tj|j|d |_| jrtj|j| j| jd|_t|j | jrD| jr| jn|j}| | j }tj|| j|d|_|j |_t|j | jrDtj|| j|jd|_t|j dS )a  
        This initializes some attributes on the handle's ``FlatParameter``.
        This should be called during lazy initialization since it requires the
        parameter to be on the compute device if not offloading to CPU and we
        want to give users the chance to move the parameter appropriately after
        the FSDP constructor.

        For each tensor attribute on the ``FlatParameter``, see the unshard and
        reshard methods in this class for the allocation and free pattern.
        cpuzWExpects the `FlatParameter` to be on CPU when parameter CPU offloading is enabled, not rd   )rd   r|   N)r{   r|   r}   r   r   r   r   r6   rd   rs   r   _check_on_compute_devicedata_local_shardZ
pin_memory
zeros_like	_cpu_grad_uses_param_mixed_precision	_mp_shardr   r   r   rq   zeros_full_param_paddedr\   _padded_unsharded_size_full_prec_full_param_padded)r_   r{   Z
cpu_deviceZunsharded_param_dtypeZpadded_unsharded_numelr0   r0   r1   init_flat_param_attributes  sh    


z*FlatParamHandle.init_flat_param_attributesc                 C   sz   d}| j r|  }| jr(| js(|  s(nB| jrB| jsB|   d}n(| jrj| jj	| j	krj| j
| j	dd d}| | j |S )a$  
        Returns: ``False`` if this is a no-op and ``True`` otherwise.

        Postcondition: ``self.flat_param`` 's data is on the device for
        communication and is what should be all-gathered. This means that it
        matches the dtype of the expected unsharded parameter.
        FTZnon_blocking)rt   _writeback_orig_paramsr   rs   needs_unshardr   _force_full_precision_use_low_precision_shardr{   rd   flat_param_tor   )r_   retr0   r0   r1   pre_unshardT  s$    zFlatParamHandle.pre_unshardc                 C   sF   |    | j}t|j|j  |j|jj| jdd |j|_	dS )z
        Allocates the low precision shard directly on the compute device and
        switches to using the low precision sharded flattened parameter.
        Tr   N)
_check_low_precision_shardr{   r   r   r   r\   copy_tord   r   r_   r{   r0   r0   r1   r   o  s    z(FlatParamHandle._use_low_precision_shardc                 C   sJ   |   s*| jr|  n| j}| | dS |  }| |}| | dS )a  
        Runs the unshard logic. This includes all-gathering the flattened
        parameter and switching to using the unsharded flattened parameter. If
        the handle does not need unsharding, then this only switches to using
        the unsharded flattened parameter. For ``NO_SHARD``, this is a no-op.

        If FSDP is in :meth:`summon_full_params` and the handle uses parameter
        mixed precision, then the parameter is forced to full precision.
        N)r   r    _get_padded_unsharded_flat_paramr{   _use_unsharded_flat_param"_alloc_padded_unsharded_flat_param_all_gather_flat_param)r_   unsharded_flat_parampadded_unsharded_flat_paramr0   r0   r1   unshard  s    



zFlatParamHandle.unshardc                 C   s,   | j s
dS |  }|  | k}| S )zBReturns if the handle's flattened parameter needs to be unsharded.F)r   r   r   r   r   )r_   r   Zalready_unshardedr0   r0   r1   r     s    
zFlatParamHandle.needs_unshardc                 C   s0   |    | j}|  }| | t||j |S )a*  
        Allocates the *padded* unsharded flattened parameter. The unpadded
        unsharded flattened parameter is always a view into the padded one.
        This padded parameter is saved to a different attribute on the
        ``FlatParameter`` depending on if we force full precision.
        )_check_sharded_strategyr{   r   _check_storage_freedr   r   r_   r{   r   r0   r0   r1   r     s    
z2FlatParamHandle._alloc_padded_unsharded_flat_paramc                 C   s@   |    | j}| jr6|j}t|j| jkd| j  n|j}|S )z
        Returns a reference to the padded unsharded flattened parameter
        depending on the calling context. This should only be called if using a
        sharded strategy.
        zExpects full precision but got )r   r{   r   r   r   r|   r   r   r   r0   r0   r1   r     s    

z0FlatParamHandle._get_padded_unsharded_flat_param)r   rB   c                 C   sf   t t| dot| dd | jj}| | j }t | |kd| d|   t||| j |S )z
        All-gathers the handle's flattened parameter to the destination
        ``padded_unsharded_flat_param``, and switches to using the all-gathered
        tensor.
        rj   rq   zEExpects a process group and world size to have been set via `shard()`Expects  numel but got )	r   r   r{   r   r   rq   rx   all_gather_into_tensorrj   )r_   r   r   Zexpected_numelr0   r0   r1   r     s     	
z&FlatParamHandle._all_gather_flat_paramc                 C   sj   | j j}|d|  || j _| jtjk}| jtjk}| j	rV| j
| oN| d n|rf| j
dd dS )z
        Switches to using the *unpadded* unsharded flattened parameter, which
        is a view into the *padded* unsharded flattened parameter.
        Nrl   F)r{   r]   r   viewr   rw   r   FORWARDBACKWARD_PRErt   r~   )r_   r   unsharded_sizeZ
in_forwardZin_pre_backwardr0   r0   r1   r     s    

z)FlatParamHandle._use_unsharded_flat_paramc                 C   s$   | j r| jr|   | | j dS )zo
        Runs the post-unshard logic. This includes freeing the low precision
        shard if needed.
        N)r   r   !_free_low_precision_sharded_paramr   r{   r_   r0   r0   r1   post_unshard  s    zFlatParamHandle.post_unshardc                 C   s,   |    t| jjtj  t| jj dS )z4Frees the low precision sharded flattened parameter.N)r   r   r{   r   r6   cudacurrent_streamr   r   r0   r0   r1   r     s
    z1FlatParamHandle._free_low_precision_sharded_paramc                 C   s"  | j s|   dS | j}| | tjdtj| jd}|jdu |d< t	j
|| jd |d | jkrtd|_|   dS tj|j| jd}|jdu r| jt	jjkrtd| j d d|_tj|j| jd}n| |j |j|_|j}t	||| j | jj}|d|  ||_|   dS )	a  
        Unshards the handle's ``FlatParameter`` 's gradient. If all ranks have
        ``None`` gradient, then all original parameters will as well. This
        method performs an all-reduce and an all-gather. The additional
        all-reduce is tolerable since this method is not meant to be used on
        the computation critical path.

        Postcondition: ``_saved_grad_shard`` is defined and contains the value
        to set ``flat_param.grad`` after gradients are resharded.
        Nr   )r|   rd   r   )groupr   [Rank z] Only some but not all ranks have a `None` `FlatParameter` gradient, so FSDP is using zeros to approximate those ranks' sharded gradients being `None`)r   _use_unsharded_grad_viewsr{   _check_unshardedr6   r   int32rd   gradrx   Z
all_reducerj   rq   _saved_grad_shardemptyr   ry   
DebugLevelDETAILwarningswarnrp   r   _check_shardedr   r]   r   r   )r_   r{   Znum_grad_noneZpadded_unsharded_gradsharded_gradr   r0   r0   r1   unshard_grad  sD    

zFlatParamHandle.unshard_gradc                 C   s4   | j r|   | jsd S | jj| j_t| jd d S )Nr   )rt   _use_sharded_grad_viewsr   r{   r   r   delattrr   r0   r0   r1   reshard_gradL  s    zFlatParamHandle.reshard_gradc                 C   s(  t | jtjtjfv d | j}|jdur$|j |jksJ|jj	|j	kr$| 
| j |jj	| j	k}t | pp| jd| j	 d|jj	  |j |j k}|r|s|jj|_|j}nt t|dd |j}|jj}| jr|j|kr|||_n,|j}t |j |kd| d|j   d|_dS )	z
        Prepares the gradient for the backward computation by saving and
        clearing any existing sharded gradient in ``.grad`` to enable computing
        a new unsharded gradient.
        z:Expects to be in `BACKWARD_PRE` or `IDLE` (if prefetching)Nz&Expects the sharded gradient to be on 	 but got r   z7`_cpu_grad` should be defined if the gradient is on CPUzFExpects `.grad` to be the unsharded gradient in `no_sync()` with size z but got size )r   rw   r   r   rv   r{   r   r\   r]   rd   r   rs   r   r   r   r   r   r|   ru   r   r   )r_   r{   Zgrad_offloadedZprev_iter_synced_gradientsr   Zlocal_shard_dtypeZpadded_unsharded_sizer0   r0   r1   prepare_gradient_for_backwardT  sb    



z-FlatParamHandle.prepare_gradient_for_backwardc                    s    fdd} j }t|drB |  | |j|_|| nXt|dr |  |  |j |jr|j|_|| nt	 j
 p|j d t|drt|d dS )z
        Prepares the gradient for optimizer computation by moving the sharded
        gradient to the ``.grad`` attribute.
        c                    sF    j rB| jd usJ | jj jkrB| j j| j_ jrB   d S rM   )ru   r   r|   r   r   r   rt   r  )r{   r   r0   r1   "cast_grad_to_param_dtype_if_needed  s    zVFlatParamHandle.prepare_gradient_for_optim.<locals>.cast_grad_to_param_dtype_if_neededr   r   zcAll sharded parameters that received a gradient in the post-backward should use `_saved_grad_shard`N)r{   r   r   _check_on_cpur   r   r   r   r^   r   r   r  )r_   r  r{   r0   r   r1   prepare_gradient_for_optim  s*    








z*FlatParamHandle.prepare_gradient_for_optimc                 c   sL  |    t| j | jjkd| jj d| j   | | j | j  }|    }t||kd | 	t
d |   zddV  W t| j | jjkd| jj d| j   |  }|d| j  | j | | n\t| j | jjkd| jj d| j   |  }|d| j  | j | | 0 dS )ao  
        Moves the unpadded unsharded flattened parameter to CPU while in the
        context and moves it back to the previous device upon exit. For now,
        this assumes the ``FlatParameter`` is the unpadded unsharded flattened
        parameter since (1) there is no reason to include the padding in the
        copy and (2) there is no use case for the sharded flattened parameter.

        Precondition: ``self.flat_param`` 's data is the unpadded unsharded
        flattened parameter on the compute device, and the handle uses a
        sharded strategy.
        Postcondition: Same as the precondition.
        zExpects size r  zEExpects the unpadded parameter to be a view into the padded parameterr   N)r   r   r{   r\   r]   r   r   Z	_data_ptrr   r   r6   rd   _free_unsharded_flat_paramr   r   r   r   )r_   Zunpadded_storage_ptrZpadded_storage_ptrr   r0   r0   r1   to_cpu  sF    zFlatParamHandle.to_cpu)free_unsharded_flat_paramc                 C   s   |    |r|   dS )z
        Runs the reshard logic. This includes freeing the unsharded flattened
        parameter if ``free_unsharded_flat_param`` and switching to using the
        sharded flattened parameter.
        N)_use_sharded_flat_paramr
  )r_   r  r0   r0   r1   reshard  s    
zFlatParamHandle.reshardc                 C   s   | j r| js| js|   dS )aE  
        Runs the post-reshard logic. This includes freeing any memory that
        can now be freed given that the ``FlatParameter`` points to the full
        precision sharded flattened parameter.

        Precondition: ``self.flat_param`` 's data points to the full precision
        sharded flattened parameter.
        N)r   r   r   r   r   r0   r0   r1   post_reshard  s    zFlatParamHandle.post_reshardc                 C   s@   |    |  }| | | | t|tj  t| dS )z
        Frees the padded unsharded flattened parameter. The tensor to free
        depends on the calling context since the unshard may have forced full
        precision, in which case a different tensor is used.
        N)	r   r   _check_storage_allocatedr   r   r6   r   r   r   )r_   r   r0   r0   r1   r
    s    

z*FlatParamHandle._free_unsharded_flat_paramc                 C   s   | j }| jr.|jj}t|tdkd|  |j|_| jr|   | j	t
jkr|jduol| jol|jj|jk}|r||   n|   dS )z2Switches to using the sharded flattened parameter.r   z-Expects the local shard to be on CPU but got N)r{   rs   r   rd   r   r6   r   rt   r   rw   r   r   r   r   r   r]   r   r  )r_   r{   rd   Zaccumulated_grad_in_no_syncr0   r0   r1   r     s&    

z'FlatParamHandle._use_sharded_flat_param)r{   r   rB   c                 C   sh   |du r| }t | | j kd| j  d|  d dd ttj|| jdd| j| jD }|S )	a  
        Returns unflattened ``Tensor`` views into ``tensor`` if it is not
        ``None`` or ``flat_param`` otherwise, where the unflattening is based
        on ``flat_param`` 's metadata.

        In other words, to get views into the unsharded flattened parameter,
        pass ``tensor`` as ``None``, but to get views into tensor optimizer
        state, pass ``tensor`` as the optimizer state tensor.
        Nr   r   z numelc                 s   s$   | ]\}}}t |||V  qd S rM   )r   r   )rE   Z	subtensorr   Zparam_extensionr0   r0   r1   	<genexpr>U  s   z4FlatParamHandle._get_unflat_views.<locals>.<genexpr>r   r   )	r   r   r]   r   r6   splitrQ   rR   rU   )r{   r   viewsr0   r0   r1   _get_unflat_views@  s     z!FlatParamHandle._get_unflat_views)rm   rB   c                 C   st  |  | j | | j}tt|| jjD ]8\}\}\}}}t||rRt|| | jr|rt	|t
u r|t||t| q*| jj| }t||| ||_q*|r||t| q*|}	| jr<| jtjkr| jjdusJ || jj|< nR| jtjkr<| jjdus
J | jj| }
t|
dud ||
_|
dus8J |
}	t|||	 | jr*| jtjkr*|	|j|< q*t| jjD ]\}\}}}}}}t||rt|| tt||d| d|  t||}t| pt|tjd| dt	|  | jr|r| jj| }t||| ||_nR|r@t|tjs2J ||| n,t||| | jrr| jtjkrr||j|< qrdS )a  
        Unflattens the unsharded flattened parameter by setting the original
        module parameter variables to be views into it.

        Args:
            as_params (bool): If ``True``, then registers the original
                parameters as ``nn.Parameter`` s; if ``False``, then registers
                the original parameters only as ``Tensor`` s. ``False`` should
                be used during forward/backward computation and when hiding the
                original parameters from :meth:`nn.Module.named_parameters`.
        Nz.Expects `Tensor` to have been saved in forwardzModule z is missing parameter z
as_params=z type(prim_param)=)r   r{   r  r   r   rP   r   r  rt   r   r   setattrr.   rb   rW   r   Zregister_parameterrw   r   r   r[   r   r   _parametersrT   getattrr   rX   )r_   rm   r  r   r   r$   r%   rK   r`   Z	param_varr   r2   r3   r4   
prim_paramZshared_paramr0   r0   r1   r~   _  s    







z$FlatParamHandle._use_unsharded_viewsc                 C   s  | j jdu rN| j jdusJ | j jdus,J t| j j| j jD ]
}d|_q>dS | | j j | | j | j j}tt|| j j	D ]x\}\}\}}}t
t||| j j|  d t||}|j|jks|j|jkr|jdu rt||_||j_q||_qt| j jD ]\}\}}}}	}
}t
t|||r6|d | n| d t||}t|
|	}|j|jjksv|j|jjkr|jdu rt||_|j|j_n|j|_qdS )z
        Unflattens the unsharded flattened parameter's gradient by setting the
        original module parameter variables' gradients to be views into it.
        Nz is missingr   )r{   r   rW   rX   r   r   r  r   r   rP   r   r   rS   r  r   r|   r6   
empty_liker   rT   )r_   r`   r  r   r   r$   r%   rK   r&   r2   r3   r  r0   r0   r1   r     s\    






z)FlatParamHandle._use_unsharded_grad_viewsc              	   c   s6   | j dd zdV  W | j dd n| j dd 0 dS )a1  
        Assumes the flattened parameter is unsharded. When in the context,
        unflattens the original parameters as ``nn.Parameter`` views into the
        flattened parameter, and after the context, restores the original
        parameters as ``Tensor`` views into the flattened parameter.
        Trl   NF)r~   r   r0   r0   r1   unflatten_as_params  s    z#FlatParamHandle.unflatten_as_paramsc                 C   s  | j s| jdd dS | | j | jj\}}d}| jjdusBJ tt| jj| jjD ]\}\}\}}}t	||| ||ko||ko| jj
}	|	r| jj
||  \}
}||
 d }| j|||  |_||7 }qXtjd| jj| jjdd|_qX| jjdusJ tt| jj| jjD ]6\}\}\}}}}}}t	||| t||}||_q| jtjkr| jjduslJ tt| jjD ]}d| jj|< q|dS )aF  
        Sets the original module parameter variables' data to be flattened
        views into the sharded flattened parameter.

        The views are kept as flattened to simplify the case where a parameter
        is sharded across ranks. Parameters whose data is not present in the
        sharded flattened parameter have their data set to a size-0 empty
        tensor. We do not delete them to ensure to preserve expected behaviors
        like model printability. Parameters whose data is present must preserve
        their variables to be passable to an optimizer.
        Trl   Nr   r   F)r|   rd   r   )r   r~   r   r{   r   rW   r   r   rP   r  r   r   r6   r   r|   rd   rX   rT   r  rw   r   BACKWARD_POSTr[   rY   rN   )r_   r   r   offsetr   r`   r$   r%   rK   in_sharded_flat_paramr   r   numel_in_shardr2   r3   r  r0   r0   r1   r   
  sR    




z"FlatParamHandle._use_sharded_viewsc                 C   s  | j }| | | j}|du rX|jdus,J |jdus:J t|j|jD ]
}d|_qHdS | | |j\}}d}|jdus~J t|jD ]\}}||ko||ko|j	}|rd|j	||  \}	}
|
|	 d }|j
dusJ |jrT|j
| sT| js|j|jkr8|jdu rt||_||||  |j|j_n||||  |j|_nd|_||7 }qd|_q|jdus|J tt|j|jD ]L\}\}\}}}}}}t||}|r|jrt||}|j|_nd|_qdS )a6  
        Sets the original module parameter variables' gradients to be flattened
        views into the sharded flattened parameter's gradient. This is a no-op
        if there is no gradient.

        Parameters whose data is not present in the sharded flattened parameter
        and parameters with ``requires_grad=False`` have their gradients set to
        ``None``. Since the gradient variables do not need to be preserved,
        this method does not manipulate existing ``Tensor`` data directly and
        creates new ``Tensor`` variables instead.
        Nr   r   )r{   r   r   rW   rX   r   r   r   r   r   rZ   r   ru   r|   r6   r  r   r   r   r   rT   r   r  )r_   r{   r   r`   r   r   r  r   r  r   r   r  rK   r2   r3   r  r0   r0   r1   r  F  s^    








z'FlatParamHandle._use_sharded_grad_viewsc              	   C   s  | j r| | jsdS | j}|j\}}d}|jdus8J d}tt|j|jD ]\}\}\}}	}
t|	|snqN||ko||ko| jj	}|sqN|j	||  \}}|| d }t
|	||u}|pt|| }|rt
|	|}||j|< |r
t|g}| |||||d d}|jdu rF|jdurFt|g}| d|j|||d n|jdur| j sb| jsh|jn|j}|du pt|j| }|r|du rt|}t|g}| |j||||d ||_||7 }qNt|jD ]4\}\}}	}
}}}
t
|	|t
||urtdq|S )a  
        Iterates over the original parameters and writes back any parameters
        that changed storages (due to a non-inplace operator) to the handle's
        ``FlatParameter``. This method preserves the ``FlatParameter` 's
        device even if an original parameter's device changes.

        Raises:
            RuntimeError: If an original parameter or gradient changes storages
            but no longer has the expected flattened shape.
        Returns: ``True`` if some writeback happened, and ``False`` otherwise.
        Fr   Nr   Tz/Changing shared parameters is not supported yet)r   
is_shardedr{   r   rW   r   r   rP   r   r   r  r   r6   r7   _writeback_tensorr   rs   r   r   rT   NotImplementedError)r_   r{   r   r   r  Z	wrotebackr   r`   r$   r%   rK   r  r   r   r  Zparam_changedZneeds_param_writebackexpected_shapeZflat_param_gradZneeds_grad_writebackr2   r3   r0   r0   r1   r     s    










z&FlatParamHandle._writeback_orig_params)
src_tensor
dst_tensortensor_indexr"  r  is_paramrB   c           
      C   s6  t t|dkd|  | jtjjkrt| dr6| jnt }|durL|j	nd}|dur^|j
nd}	td| d|rvdnd d	| j d
| d| d|j
 d|	  |dur|j	|krtd|rdnd d| d|j	 |dur||||   | n6||||     | jjdus&J d| jj|< dS )a#  
        Writes back ``src_tensor`` to ``dst_tensor`` at offset ``offset``,
        where ``src_tensor`` should have shape ``expected_shape``. ``is_param``
        indicates if the tensor is the parameter (if ``True``) or gradient (if
        ``False``). If ``src_tensor`` is ``None``, then the effect is zeroing
        instead of copying. ``tensor_index`` gives the index of ``src_tensor``
        in the metadata structures.

        Raises:
            RuntimeError: If the ``src_tensor`` does not have the expected
            shape.
        r   z$Expects a 1D expected shape but got rp   Nr   z] rb   ZGradientz needs writeback in z
expected shape=z shape=z expected device=z device=zCannot writeback when the Z	parameterZgradientz shape changes
Expects r  T)r   rN   ry   rx   r   r   r   rp   Zget_rankr   rd   r   r   rw   RuntimeErrorr   r   Zzero_r{   rZ   )
r_   r#  r$  r%  r"  r  r&  rp   Z	src_shapeZ
src_devicer0   r0   r1   r     sD    
z!FlatParamHandle._writeback_tensorc                 C   s<   | j s
dS | j}|jdusJ tdd |jD r8d|_dS )aZ  
        When ``use_orig_params=True``, sets the underlying ``flat_param.grad``
        to ``None`` if *all* of the original parameters' ``.grad`` are
        ``None``. This is targeting ``optim.zero_grad(set_to_none=True)``, in
        which case we want to free the gradients as soon after the
        ``zero_grad()`` call as possible.
        Nc                 s   s   | ]}|j d u V  qd S rM   )r   )rE   r`   r0   r0   r1   r  -  rH   z9FlatParamHandle._clear_grads_if_needed.<locals>.<genexpr>)rt   r{   rW   allr   r   r0   r0   r1   _clear_grads_if_needed!  s    z&FlatParamHandle._clear_grads_if_neededc                 C   sZ   | j jD ]\}}}t||rt|| q| j jD ]$\}}}}}}t||r0t|| q0d S rM   )r{   rP   r   r  rT   )r_   r$   r%   rK   r0   r0   r1   _deregister_orig_params0  s    

z'FlatParamHandle._deregister_orig_paramsc                 O   sB   | j j|i || j _| jr>| | j r2|   n| jdd dS )z<Wraps an in-place call to ``.to()`` for ``self.flat_param``.Trl   N)r{   r   r   rt   r  r   r~   )r_   argskwargsr0   r0   r1   r   ;  s
    
zFlatParamHandle.flat_param_toc                 C   s&   dd | j jD dd | j jD S )zqReturns a :class:`set` of the modules whose parameters are included
        in this handle's flattened parameter.c                 S   s   h | ]
}|j qS r0   rC   rD   r0   r0   r1   rG   H  rH   z/FlatParamHandle._get_modules.<locals>.<setcomp>c                 S   s   h | ]
}|j qS r0   rC   rI   r0   r0   r1   rG   I  rH   )r{   rP   rV   rT   r   r0   r0   r1   _get_modulesE  s    zFlatParamHandle._get_modules)r   rB   c                 C   s*   t | jdr| jsdS | jj}| |kS )z
        Returns if ``tensor`` is *currently* sharded. For ``NO_SHARD``, we
        choose to have this always return ``False`` for clarity.
        r   F)r   r{   r   r   r\   )r_   r   sharded_sizer0   r0   r1   r  L  s    
zFlatParamHandle.is_shardedc                 c   s:   dd | j jD }t| j j|D ]\}}}||fV  q d S )Nc                 S   s$   g | ]\}}}}}}t |||qS r0   r!   rE   r$   r%   r&   rK   r0   r0   r1   rL   [  s   z:FlatParamHandle.parameter_module_names.<locals>.<listcomp>)r{   rT   r   rP   )r_   r>   r$   rK   r&   r0   r0   r1   parameter_module_namesZ  s    	z&FlatParamHandle.parameter_module_namesc                 c   s,   dd | j jD D ]\}}}||fV  qd S )Nc                 S   s$   g | ]\}}}}}}t |||qS r0   r/  r0  r0   r0   r1   rL   l  s   zAFlatParamHandle.shared_parameter_module_names.<locals>.<listcomp>)r{   rT   )r_   r$   rK   r&   r0   r0   r1   shared_parameter_module_namesk  s    	z-FlatParamHandle.shared_parameter_module_namesc                 C   sT   g }| j j\}}tt| j jD ].}||kr ||kr | j jr || j j|  q |S )z@Returns the FQNs of the parameters present in this rank's shard.)r{   r   rY   rN   rS   r   r   )r_   Zfqns_in_shardr   r   r   r0   r0   r1   _fqns_in_shardy  s    zFlatParamHandle._fqns_in_shardc                 C   sX   | j }t|dr|j}n<t|dr*|j}n*t|jdu pH| j pH| jtj	kd |j}|S )z&Returns the handle's sharded gradient.r   r   NzqSharded strategies should use `_cpu_grad` or `_saved_grad_shard` unless in FORWARD (for the post-forward reshard))
r{   r   r   r   r   r   r   rw   r   r   )r_   r{   r   r0   r0   r1   r     s    



zFlatParamHandle.sharded_gradc                 C   sf   | j s
dS t| jtjkd | j}|jdus0J t|jD ]&\}}|jr:|j	dusVJ d|j	|< q:dS )a.  
        Resets the ``_is_grad_none`` mask as needed. This method should only be
        called in the post-backward after gradient computation, in which case
        if a parameter requires gradient, then it will surely receive a
        gradient and we may reset its mask entry to ``False``.
        NzIExpects to only be called in the post-backward after gradient computationF)
rt   r   rw   r   r  r{   rW   r   r   rZ   )r_   r{   r   r`   r0   r0   r1   _reset_is_grad_none  s    
z#FlatParamHandle._reset_is_grad_nonec                 C   s   t | jd d S )NzExpects sharded strategy)r   r   r   r0   r0   r1   r     s    z'FlatParamHandle._check_sharded_strategy)r   c                 C   s   t |j| jkd| j  d S )Nz+Expects tensor to be on the compute device )r   rd   r_   r   r0   r0   r1   r     s    

z(FlatParamHandle._check_on_compute_devicec                 C   s"   t |jtdkd|j  d S )Nr   z$Expects tensor to be on CPU but got )r   rd   r6   r5  r0   r0   r1   r    s    
zFlatParamHandle._check_on_cpuc                 C   s$   |    }t|dkd|  d S )Nr   z6Expects storage to be freed but got storage with size r   r   r   r   Zstorage_sizer0   r0   r1   r     s
    z$FlatParamHandle._check_storage_freedc                 C   s   |    }t|dkd d S )Nr   zExpects storage to be allocatedr6  r7  r0   r0   r1   r    s    z(FlatParamHandle._check_storage_allocatedc                 C   sP   t | jd t t| jdd d ud | jjj}t || jkd| j d|  d S )Nz&Not using low precision for parametersr   zExpects `_mp_shard` to existz)Expects the low precision shard to be on r  )r   r   r  r{   r   rd   )r_   rd   r0   r0   r1   r     s    
z*FlatParamHandle._check_low_precision_shardc                 C   sH   d}t |d u|d  | jj}t | |k|d| d|    d S )NzExpects tensor to be unsharded but got `None`
with size r  )r   r{   r]   r\   )r_   r   
msg_prefixr   r0   r0   r1   r     s    
z FlatParamHandle._check_unshardedc                 C   sH   d}t |d u|d  | jj}t | |k|d| d|    d S )NzExpects tensor to be sharded r8  r9  r  )r   r{   r   r\   )r_   r   r:  r.  r0   r0   r1   r     s    
zFlatParamHandle._check_shardedc                 C   s   | j tjkS rM   )rr   r#   r9   r   r0   r0   r1   r     s    z%FlatParamHandle.uses_sharded_strategyc                 C   s   | j | jkS rM   )r   r}   r   r0   r0   r1   r     s    z+FlatParamHandle._uses_param_mixed_precisionc                 C   s   | j | jkS rM   )r   r}   r   r0   r0   r1   _uses_reduce_mixed_precision  s    z,FlatParamHandle._uses_reduce_mixed_precisionc                 C   s   | j tjko| jS rM   )rw   r   ZSUMMON_FULL_PARAMSr   r   r0   r0   r1   r     s    z%FlatParamHandle._force_full_precision)N)`r(   r)   r*   r+   r   r.   rb   r/   r6   rd   r#   boolr   r|   rx   ZProcessGroupro   rz   staticmethodr   r   r   r   r   r   r8   r   r   r   r   r   r7   r   r
   r   r    r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r	  
contextlibcontextmanagerr  r  r  r
  r  r	   r  r~   r   r   r  r   r  r   r   r)  r*  r   r   r-  r  r,   r1  r2  propertyr3  r   r4  r   r   r  r   r  r   r   r   r   r   r;  r   __classcell__r0   r0   r   r1   r   5  s  ! s$
"'"7

V	
6A,
/  ]@;Bg2
		r   .)6r>  r   enumr   r   	itertoolsr   r   typingr   r   r   r	   r
   r   r   r   r   r   r   r   r6   Ztorch.distributedZdistributedrx   Ztorch.nnr.   Ztorch.nn.functionalZ
functionalr   r   Ztorch.distributed._tensorr   Z$torch.distributed.fsdp._common_utilsr   r   Z_fsdp_extensionsr   r   _utilsr   r   r   r   r   __all__r!   r"   r    r#   rb   r   r   Z_HandlesKeyr0   r0   r0   r1   <module>   sF   8  2             d