
    Vh·             
          d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZmZm	Z	 d dl m
Z
 d dlmZmZ d dlmZmZmZmZ d dlZd dlmZ d dlmc mc mZ d dlmZ d dlmZmZ d dl m!Z! d dl"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z( d d	l)m*Z* d d
l+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 d dl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZC d dlDmEZE d dlFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZT d dlUmVZV d dlWmXZX ddlYmZZZm[Z[ ddl\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZd ddlemfZf ddlgmhZhmiZimjZjmkZkmlZl ddlmmnZnmoZo ddgZpdZq G d de      Zr G d dej                  e#      Ztdeej                     devdej                  dej                  dej                  f
d Zyd!ej8                  j                  dezej8                  j                  e{f   fd"Z|d!ej8                  j                  deze{ej8                  j                  f   fd#Z}y)$    N)	GeneratorIterableIterator)contextmanager)autoEnum)AnyCallableOptionalUnion)_CHECKPOINT_WRAPPED_MODULEActivationWrapper)LOW_PRECISION_HOOKS)
_FSDPState_get_param_to_fqnsFSDP_PREFIXFSDP_WRAPPED_MODULEHandleTrainingStateTrainingState)_annotate_modules_for_dynamo)_check_orig_params_flattened_init_buffer_state_init_core_state_init_device_handle_init_extension_init_ignored_module_states_init_param_handle_from_module_init_prefetching_state_init_process_group_state_init_runtime_state_init_state_dict_stateHYBRID_SHARDING_STRATEGIESProcessGroupType)
_get_fsdp_root_states_is_fsdp_root
_lazy_init_post_forward_post_forward_reshard_pre_forward_pre_forward_unshard_root_pre_forward_unshard_wait_for_computation_stream)
_auto_wrap)BackwardPrefetch
CPUOffloadFullOptimStateDictConfigFullStateDictConfigLocalOptimStateDictConfigLocalStateDictConfigMixedPrecisionOptimStateDictConfigShardedOptimStateDictConfigShardedStateDictConfigShardingStrategyStateDictConfigStateDictSettingsStateDictType)
DeviceMesh)	_p_assert   )FlatParameterFlatParamHandle)_flatten_optim_state_dict'_get_param_id_to_param_from_optim_input_get_param_key_to_param'_get_param_to_param_id_from_optim_input_get_param_to_param_key_optim_state_dict_rekey_sharded_optim_state_dict_set_optim_use_dtensor)_register_all_state_dict_hooks)_deregister_orig_params_register_flat_param_register_orig_params_unshard_params_unshard_params_for_summon)CustomPolicyModuleWrapPolicyFullyShardedDataParallelOptimStateKeyType_flat_paramc                   ,    e Zd ZdZ e       Z e       Zy)rS   z6Represents the type of key in an optimizer state-dict.N)__name__
__module____qualname____doc__r   
PARAM_NAMEPARAM_ID     b/home/dcms/DCMS/lib/python3.12/site-packages/torch/distributed/fsdp/fully_sharded_data_parallel.pyrS   rS   n   s    @JvHr]   c            #           e Zd ZdZddddej
                  ddddddddddfdej                  dede	e
   de	e   d	e	eeeef      d
e	e   de	e   de	eej                  j                        de	eej                  gdf      de	eeej(                  f      dededededee	eej                  j,                        e	eej                  j                        f   de	e   f  fdZedej                  fd       Zedefd       Zede	e   fd       Zdedef fdZ dedef fdZ!defdZ"e#	 dfdej                  dede$d    fd        Z%d!eej                  gdf   dd f fd"Z&defd#Z'defd$Z(dgd%Z)e#	 	 dhdej                  d&e*d'e	e+   d(e	e,   de-f
d)       Z.e#dej                  de-fd*       Z/e#e0jb                  	 	 dhdej                  d&e*d'e	e+   d(e	e,   de2f
d+              Z3d,ed-edefd.Z4e#e0jb                  	 	 	 	 	 didej                  d/ed0ed1ed2ed3ede2fd4              Z5e0jb                  d5        Z6 fd6Z7de8e9eejt                  f      f fd7Z;de8e9eej                  j,                  f      f fd8Z<d9ee=e$e=   f   ddfd:Z>e1de2fd;       Z? ej                         	 djd<eeAef   d=eeAef   dejt                  fd>       ZBe#d?d@dAefdB       ZCe#defdC       ZDe#d?d@dDedEedAefdF       ZEe#	 	 	 	 	 dkd?dGdHej                  j                  dIej                  j                  dJeHeef   dKe	ee$eHeef      eej                  j,                     f      d1edLedMe	eIj                     dedNedeHeef   fdO       ZKe#	 	 	 	 	 	 dldJeHeef   dHej                  j                  dKe	ee$eHeef      eej                  j,                     f      dIe	ej                  j                     dLed1edPedMe	eIj                     deHeef   fdQ       ZLe#	 	 	 dmdHej                  j                  dIej                  j                  dKe	ee$eHeef      eej                  j,                     f      d1edMe	eIj                     deHeef   fdR       ZMe#	 dndHej                  j                  dIej                  j                  dMe	eIj                     deHeef   fdS       ZNe#	 	 dhdTeHeef   dHej                  j                  dKe	ee$eHeef      eej                  j,                     f      dIe	ej                  j                     deHeef   f
dU       ZOe#dVeHeef   dHej                  j                  dIej                  j                  deHeef   fdW       ZPe#	 	 	 dodTe	eHeef      dHej                  j                  dKe	ee$eHeef      eej                  j,                     f      dIe	ej                  j                     dMe	e   deHeef   fdX       ZQe#	 	 dhdJeHeef   dYeRdHej                  j                  dKe	ee$eHeef      eej                  j,                     f      dIe	ej                  j                     deHeef   fdZ       ZSe#	 	 dhdHej                  j                  dIej                  j                  dJe	eHeef      dMe	eIj                     deHeef   f
d[       ZTe#	 	 	 dpdHej                  j                  dIej                  j                  dJeHeef   dPed\edMe	eIj                     deHeef   fd]       ZUd9eVd^eWfd_ZXdfd`efdaZYdb ZZe0jb                  dce=dde[fde       Z\ xZ]S )qrR   aqA  A wrapper for sharding module parameters across data parallel workers.

    This is inspired by `Xu et al.`_ as well as the ZeRO Stage 3 from DeepSpeed_.
    FullyShardedDataParallel is commonly shortened to FSDP.

    .. _`Xu et al.`: https://arxiv.org/abs/2004.13336
    .. _DeepSpeed: https://www.deepspeed.ai/

    To understand FSDP internals, refer to the
    :ref:`fsdp_notes`.

    Example::

        >>> # xdoctest: +SKIP("undefined variables")
        >>> import torch
        >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
        >>> torch.cuda.set_device(device_id)
        >>> sharded_module = FSDP(my_module)
        >>> optim = torch.optim.Adam(sharded_module.parameters(), lr=0.0001)
        >>> x = sharded_module(x, y=3, z=torch.Tensor([1]))
        >>> loss = x.sum()
        >>> loss.backward()
        >>> optim.step()

    Using FSDP involves wrapping your module and then initializing your
    optimizer after. This is required since FSDP changes the parameter
    variables.

    When setting up FSDP, you need to consider the destination CUDA
    device. If the device has an ID (``dev_id``), you have three options:

    * Place the module on that device
    * Set the device using ``torch.cuda.set_device(dev_id)``
    * Pass ``dev_id`` into the ``device_id`` constructor argument.

    This ensures that the FSDP instance's compute device is the
    destination device. For option 1 and 3, the FSDP initialization
    always occurs on GPU. For option 2, the FSDP initialization
    happens on module's current device, which may be a CPU.

    If you're using the ``sync_module_states=True`` flag, you need to
    ensure that the module is on a GPU or use the ``device_id``
    argument to specify a CUDA device that FSDP will move the module
    to in the FSDP constructor. This is necessary because
    ``sync_module_states=True`` requires GPU communication.

    FSDP also takes care of moving input tensors to the forward method
    to the GPU compute device, so you don't need to manually move them
    from CPU.

    For ``use_orig_params=True``,
    ``ShardingStrategy.SHARD_GRAD_OP`` exposes the unsharded
    parameters, not the sharded parameters after forward, unlike
    ``ShardingStrategy.FULL_SHARD``. If you want
    to inspect the gradients, you can use the ``summon_full_params``
    method with ``with_grads=True``.

    With ``limit_all_gathers=True``, you may see a gap in the FSDP
    pre-forward where the CPU thread is not issuing any kernels. This is
    intentional and shows the rate limiter in effect. Synchronizing the CPU
    thread in that way prevents over-allocating memory for subsequent
    all-gathers, and it should not actually delay GPU kernel execution.

    FSDP replaces managed modules' parameters with ``torch.Tensor``
    views during forward and backward computation for autograd-related
    reasons. If your module's forward relies on saved references to
    the parameters instead of reacquiring the references each
    iteration, then it will not see FSDP's newly created views,
    and autograd will not work correctly.

    Finally, when using ``sharding_strategy=ShardingStrategy.HYBRID_SHARD``
    with the sharding process group being intra-node and the
    replication process group being inter-node, setting
    ``NCCL_CROSS_NIC=1`` can help improve the all-reduce times over
    the replication process group for some cluster setups.

    **Limitations**

    There are several limitations to be aware of when using FSDP:

    * FSDP currently does not support gradient accumulation outside
      ``no_sync()`` when using CPU offloading. This is because FSDP
      uses the newly-reduced gradient instead of accumulating with any
      existing gradient, which can lead to incorrect results.

    * FSDP does not support running the forward pass of a submodule
      that is contained in an FSDP instance. This is because the
      submodule's parameters will be sharded, but the submodule itself
      is not an FSDP instance, so its forward pass will not all-gather
      the full parameters appropriately.

    * FSDP does not work with double backwards due to the way it
      registers backward hooks.

    * FSDP has some constraints when freezing parameters.
      For ``use_orig_params=False``, each FSDP instance must manage
      parameters that are all frozen or all non-frozen. For
      ``use_orig_params=True``, FSDP supports mixing frozen and
      non-frozen parameters, but it's recommended to avoid doing so to
      prevent higher than expected gradient memory usage.

    * As of PyTorch 1.12, FSDP offers limited support for shared
      parameters. If enhanced shared parameter support is needed for
      your use case, please post in
      `this issue <https://github.com/pytorch/pytorch/issues/77724>`__.

    * You should avoid modifying the parameters between forward and
      backward without using the ``summon_full_params`` context, as
      the modifications may not persist.

    Args:
        module (nn.Module):
            This is the module to be wrapped with FSDP.
        process_group (Optional[Union[ProcessGroup, Tuple[ProcessGroup, ProcessGroup]]]):
            This is the process group over which the model is sharded and thus
            the one used for FSDP's all-gather and reduce-scatter collective
            communications. If ``None``, then FSDP uses the default process
            group. For hybrid sharding strategies such as
            ``ShardingStrategy.HYBRID_SHARD``, users can pass in a tuple of
            process groups, representing the groups over which to shard and
            replicate, respectively. If ``None``, then FSDP constructs process
            groups for the user to shard intra-node and replicate inter-node.
            (Default: ``None``)
        sharding_strategy (Optional[ShardingStrategy]):
            This configures the sharding strategy, which may trade off memory
            saving and communication overhead. See :class:`ShardingStrategy`
            for details. (Default: ``FULL_SHARD``)
        cpu_offload (Optional[CPUOffload]):
            This configures CPU offloading. If this is set to ``None``, then
            no CPU offloading happens. See :class:`CPUOffload` for details.
            (Default: ``None``)
        auto_wrap_policy (Optional[Union[Callable[[nn.Module, bool, int], bool], ModuleWrapPolicy, CustomPolicy]]):
            This specifies a policy to apply FSDP to submodules of ``module``,
            which is needed for communication and computation overlap and thus
            affects performance. If ``None``, then FSDP only applies to
            ``module``, and users should manually apply FSDP to parent modules
            themselves (proceeding bottom-up). For convenience, this accepts
            ``ModuleWrapPolicy`` directly, which allows users to specify the
            module classes to wrap (e.g. the transformer block). Otherwise,
            this should be a callable that takes in three arguments
            ``module: nn.Module``, ``recurse: bool``, and
            ``nonwrapped_numel: int`` and should return a ``bool`` specifying
            whether the passed-in ``module`` should have FSDP applied if
            ``recurse=False`` or if the traversal should continue into the
            module's subtree if ``recurse=True``. Users may add additional
            arguments to the callable. The ``size_based_auto_wrap_policy`` in
            ``torch.distributed.fsdp.wrap.py`` gives an example callable that
            applies FSDP to a module if the parameters in its subtree exceed
            100M numel. We recommend printing the model after applying FSDP
            and adjusting as needed.

            Example::

                >>> def custom_auto_wrap_policy(
                >>>     module: nn.Module,
                >>>     recurse: bool,
                >>>     nonwrapped_numel: int,
                >>>     # Additional custom arguments
                >>>     min_num_params: int = int(1e8),
                >>> ) -> bool:
                >>>     return nonwrapped_numel >= min_num_params
                >>> # Configure a custom `min_num_params`
                >>> my_auto_wrap_policy = functools.partial(custom_auto_wrap_policy, min_num_params=int(1e5))

        backward_prefetch (Optional[BackwardPrefetch]):
            This configures explicit backward prefetching of all-gathers. If
            ``None``, then FSDP does not backward prefetch, and there is no
            communication and computation overlap in the backward pass. See
            :class:`BackwardPrefetch` for details. (Default: ``BACKWARD_PRE``)
        mixed_precision (Optional[MixedPrecision]):
            This configures native mixed precision for FSDP. If this is set to
            ``None``, then no mixed precision is used. Otherwise, parameter,
            buffer, and gradient reduction dtypes can be set. See
            :class:`MixedPrecision` for details. (Default: ``None``)
        ignored_modules (Optional[Iterable[torch.nn.Module]]): Modules whose
            own parameters and child modules' parameters and buffers are
            ignored by this instance. None of the modules directly in
            ``ignored_modules`` should be :class:`FullyShardedDataParallel`
            instances, and any child modules that are already-constructed
            :class:`FullyShardedDataParallel` instances will not be ignored if
            they are nested under this instance. This argument may be used to
            avoid sharding specific parameters at module granularity when using an
            ``auto_wrap_policy`` or if parameters' sharding is not managed by
            FSDP. (Default: ``None``)
        param_init_fn (Optional[Callable[[nn.Module], None]]):
            A ``Callable[torch.nn.Module] -> None`` that
            specifies how modules that are currently on the meta device should
            be initialized onto an actual device. As of v1.12, FSDP detects
            modules with parameters or buffers on meta device via ``is_meta``
            and either applies ``param_init_fn`` if specified or calls
            ``nn.Module.reset_parameters()`` otherwise. For both cases, the
            implementation should *only* initialize the parameters/buffers of
            the module, not those of its submodules. This is to avoid
            re-initialization. In addition, FSDP also supports deferred
            initialization via torchdistX's (https://github.com/pytorch/torchdistX)
            ``deferred_init()`` API, where the deferred modules are initialized
            by calling ``param_init_fn`` if specified or torchdistX's default
            ``materialize_module()`` otherwise. If ``param_init_fn`` is
            specified, then it is applied to all meta-device modules, meaning
            that it should probably case on the module type. FSDP calls the
            initialization function before parameter flattening and sharding.

            Example::

                >>> # xdoctest: +SKIP("undefined variables")
                >>> module = MyModule(device="meta")
                >>> def my_init_fn(module: nn.Module):
                >>>     # E.g. initialize depending on the module type
                >>>     ...
                >>> fsdp_model = FSDP(module, param_init_fn=my_init_fn, auto_wrap_policy=size_based_auto_wrap_policy)
                >>> print(next(fsdp_model.parameters()).device) # current CUDA device
                >>> # With torchdistX
                >>> module = deferred_init.deferred_init(MyModule, device="cuda")
                >>> # Will initialize via deferred_init.materialize_module().
                >>> fsdp_model = FSDP(module, auto_wrap_policy=size_based_auto_wrap_policy)

        device_id (Optional[Union[int, torch.device]]): An ``int`` or
            ``torch.device`` giving the CUDA device on which FSDP
            initialization takes place, including the module initialization
            if needed and the parameter sharding. This should be specified to
            improve initialization speed if ``module`` is on CPU. If the
            default CUDA device was set (e.g. via ``torch.cuda.set_device``),
            then the user may pass ``torch.cuda.current_device`` to this.
            (Default: ``None``)
        sync_module_states (bool): If ``True``, then each FSDP module will
            broadcast module parameters and buffers from rank 0 to ensure that
            they are replicated across ranks (adding communication overhead to
            this constructor). This can help load ``state_dict`` checkpoints
            via ``load_state_dict`` in a memory efficient way. See
            :class:`FullStateDictConfig` for an example of this. (Default:
            ``False``)
        forward_prefetch (bool): If ``True``, then FSDP *explicitly* prefetches
            the next forward-pass all-gather before the current forward
            computation. This is only useful for CPU-bound workloads, in which
            case issuing the next all-gather earlier may improve overlap. This
            should only be used for static-graph models since the prefetching
            follows the first iteration's execution order. (Default: ``False``)
        limit_all_gathers (bool): If ``True``, then FSDP explicitly
            synchronizes the CPU thread to ensure GPU memory usage from only
            *two* consecutive FSDP instances (the current instance running
            computation and the next instance whose all-gather is prefetched).
            If ``False``, then FSDP allows the CPU thread to issue all-gathers
            without any extra synchronization. (Default: ``True``) We often
            refer to this feature as the "rate limiter". This flag should only
            be set to ``False`` for specific CPU-bound workloads with low
            memory pressure in which case the CPU thread can aggressively issue
            all kernels without concern for the GPU memory usage.
        use_orig_params (bool): Setting this to ``True`` has FSDP use
            ``module`` 's original parameters. FSDP exposes those original
            parameters to the user via :meth:`nn.Module.named_parameters`
            instead of FSDP's internal :class:`FlatParameter` s. This means
            that the optimizer step runs on the original parameters, enabling
            per-original-parameter hyperparameters. FSDP preserves the original
            parameter variables and manipulates their data between unsharded
            and sharded forms, where they are always views into the underlying
            unsharded or sharded :class:`FlatParameter`, respectively. With the
            current algorithm, the sharded form is always 1D, losing the
            original tensor structure. An original parameter may have all,
            some, or none of its data present for a given rank. In the none
            case, its data will be like a size-0 empty tensor. Users should not
            author programs relying on what data is present for a given
            original parameter in its sharded form. ``True`` is required to
            use ``torch.compile()``. Setting this to ``False`` exposes FSDP's
            internal :class:`FlatParameter` s to the user via
            :meth:`nn.Module.named_parameters`. (Default: ``False``)
        ignored_states (Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]):
            Ignored parameters or modules that will not be managed by this FSDP
            instance, meaning that the parameters are not sharded and their
            gradients are not reduced across ranks. This argument unifies with
            the existing ``ignored_modules`` argument, and we may deprecate
            ``ignored_modules`` soon. For backward compatibility, we keep both
            ``ignored_states`` and `ignored_modules``, but FSDP only allows one
            of them to be specified as not ``None``.
        device_mesh (Optional[DeviceMesh]): DeviceMesh can be used as an altenative to
            process_group. When device_mesh is passed, FSDP will use the underlying process
            groups for all-gather and reduce-scatter collective communications. Therefore,
            these two args need to be mutually exclusive. For hybrid sharding strategies such as
            ``ShardingStrategy.HYBRID_SHARD``, users can pass in a 2D DeviceMesh instead
            of a tuple of process groups. For 2D FSDP + TP, users are required to pass in
            device_mesh instead of process_group. For more DeviceMesh info, please visit:
            https://pytorch.org/tutorials/recipes/distributed_device_mesh.html
    NFTmoduleprocess_groupsharding_strategycpu_offloadauto_wrap_policybackward_prefetchmixed_precisionignored_modulesparam_init_fn	device_idsync_module_statesforward_prefetchlimit_all_gathersuse_orig_paramsignored_statesdevice_meshc                    t         j                  j                  d       t        |           t        |t        j                  t        j                  f      rt        j                  d| d       t        | |||       t        | || j                  |
       t        || j                  |       || _        t#        | ||||       |g||||||	|
||||| j                  |d}|t$        v r|| j&                  | j(                  f|d<   t+        ||| j                  | j                  |t,               d}d}t/        | |||||||       t1        |        t3        | ||       t5        | |       t7        | |       t9        | ||
|	|       || _        |s"t=        | | j                         t?        | |        tA        |        tC        |        d | _"        y )Nztorch.distributed.fsdpzRFSDP will not all-gather parameters for containers that do not implement forward:    
stacklevel)ra   rb   rc   re   rf   rh   ri   rj   rk   rl   rm   rn   ro   ra   r?   )#torch_C_log_api_usage_oncesuper__init__
isinstancenn
ModuleList
ModuleDictwarningswarnr   r   _ignored_paramsr   _ignored_modules_device_meshr   r"   ra   _inter_node_pgr.   rR   r   r    r   r   r   r   _fsdp_wrapped_moduler   rL   r!   rJ   _zero_scalar)selfr`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   root_kwargsbackward_prefetch_limitforward_prefetch_limit	__class__s                       r^   rx   z!FullyShardedDataParallel.__init__  s   . 	$$%=>fr}}bmm<=MM**03
 	$D&/>RD&$*>*>	J 	%VT-B-BOT (!	
 '!.%6*%6#2!.&&8$4%6#2"&"6"6*K !$>>;CV 150B0BDDWDW/XO, %%$$( #$!"#"		
 	D!&79IJ4(k*&	
 %+!(t/C/CD t, 	t$&t, r]   returnc                     t        | j                  t              rt        | j                  t              S | j                  S )zReturn the wrapped module.)ry   r   r   getattrr   r   s    r^   r`   zFullyShardedDataParallel.module  s5    
 d//1BC4446PQQ(((r]   c                 :    t        | d      xr | j                  duS )z:Returns whether this FSDP instance manages any parameters._handleN)hasattrr   r   s    r^   _has_paramsz$FullyShardedDataParallel._has_params  s     tY'DDLL,DDr]   c                 J    | j                   r| j                   j                  S d S N)r   
flat_paramr   s    r^   rT   z$FullyShardedDataParallel._flat_param  s    *.,,t||&&@D@r]   namec                 n    	 t         |   |      S # t        $ r t        | j                  |      cY S w xY w)z1Forward missing attributes to the wrapped module.)rw   __getattr__AttributeErrorr   r   )r   r   r   s     r^   r   z$FullyShardedDataParallel.__getattr__  s:    	<7&t,, 	<444d;;	<s    44keyc                 x    t        | t              r| j                  j                  |      S t        |   |      S )zBForward indexing calls in case the module is an ``nn.Sequential``.)r   r   r   __getitem__rw   )r   r   r   s     r^   r   z$FullyShardedDataParallel.__getitem__  s5    4,-,,88==w"3''r]   c                     t        | |       S )z-Check if this instance is a root FSDP module.)r%   r   s    r^   check_is_rootz&FullyShardedDataParallel.check_is_root$  s    T4((r]   	root_onlyc                 F    |rt        |       S t        j                  |       S )a  Return all nested FSDP instances.

        This possibly includes ``module`` itself and only includes FSDP root modules if ``root_only=True``.

        Args:
            module (torch.nn.Module): Root module, which may or may not be an
                ``FSDP`` module.
            root_only (bool): Whether to return only FSDP root modules.
                (Default: ``False``)

        Returns:
            List[FullyShardedDataParallel]: FSDP modules that are nested in
            the input ``module``.
        )r$   traversal_utils_get_fsdp_states)r`   r   s     r^   fsdp_modulesz%FullyShardedDataParallel.fsdp_modules(  s#    & (00//77r]   fnc                 <   | j                   du }| j                  t        j                         t	        | | dddd      5  t
        |   |      }ddd       |r6| j                   r*t        j                  |       D ]  }|j                           S # 1 sw Y   CxY w)a1  Apply ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self.

        Typical use includes initializing the parameters of a model (see also :ref:`nn-init-doc`).

        Compared to ``torch.nn.Module.apply``, this version additionally gathers
        the full parameters before applying ``fn``. It should not be called from
        within another ``summon_full_params`` context.

        Args:
            fn (:class:`Module` -> None): function to be applied to each submodule

        Returns:
            Module: self
        NTF)	writeback
rank0_onlyoffload_to_cpu
with_grads)
_is_root_assert_stater   IDLErO   rw   applyr   r   _reset_lazy_init)r   r   uninitializedretr`   r   s        r^   r   zFullyShardedDataParallel.apply?  s     -=--.
 ( 
 	$ '-#C	$ T]])::4@ *'')* 
#	$ 	$s    BBc                 2    | j                   j                  duS )a(  Return whether the user explicitly enabled buffer mixed precision.

        NOTE: Unlike parameters and gradient reduction, buffer mixed precision
        is applied at the FSDP instance level, not the ``FlatParameter`` level,
        which may be different for the composable code path.
        N)rf   buffer_dtyper   s    r^   $_mixed_precision_enabled_for_buffersz=FullyShardedDataParallel._mixed_precision_enabled_for_buffersg  s     ##00<<r]   c                 F    | j                   duxr | j                   t        v S )z2Whether a low precision hook is registered or not.N)
_comm_hookr   r   s    r^   _low_precision_hook_enabledz4FullyShardedDataParallel._low_precision_hook_enabledp  s     d*UtBU/UUr]   c                     d| _         y)zBReset instance so :func:`_lazy_init` will run on the next forward.N)r   r   s    r^   r   z)FullyShardedDataParallel._reset_lazy_initt  s	    (,r]   state_dict_typestate_dict_configoptim_state_dict_configc                    t        j                  dt               t        j                  t
        t        j                  t        t        j                  t        i}t        j                  t        t        j                  t        t        j                  t        i}||   }||   }| |       }| |       }|t        |      k7  rt        d| dt        |             |t        |      k7  rt        d| dt        |             d}d}	d}
t        j                   |       D ]  }||j"                  }n||j"                  k(  sJ d       |	|j$                  }	n&t'        |j$                  t        |	            sJ d       |
|j(                  }
n&t'        |j(                  t        |
            sJ d       ||_        ||_        ||_         t+        ||	|
      S )	a  Set the ``state_dict_type`` of all the descendant FSDP modules of the target module.

        Also takes (optional) configuration for the model's and optimizer's state dict.
        The target module does not have to be a FSDP module. If the target
        module is a FSDP module, its ``state_dict_type`` will also be changed.

        .. note:: This API should be called for only the top-level (root)
            module.

        .. note:: This API enables users to transparently use the conventional
            ``state_dict`` API to take model checkpoints in cases where the
            root FSDP module is wrapped by another ``nn.Module``. For example,
            the following will ensure ``state_dict`` is called on all non-FSDP
            instances, while dispatching into `sharded_state_dict` implementation
            for FSDP:

        Example::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> model = DDP(FSDP(...))
            >>> FSDP.set_state_dict_type(
            >>>     model,
            >>>     StateDictType.SHARDED_STATE_DICT,
            >>>     state_dict_config = ShardedStateDictConfig(offload_to_cpu=True),
            >>>     optim_state_dict_config = OptimStateDictConfig(offload_to_cpu=True),
            >>> )
            >>> param_state_dict = model.state_dict()
            >>> optim_state_dict = FSDP.optim_state_dict(model, optim)

        Args:
            module (torch.nn.Module): Root module.
            state_dict_type (StateDictType): the desired ``state_dict_type`` to set.
            state_dict_config (Optional[StateDictConfig]): the configuration for the
                target ``state_dict_type``.
            optim_state_dict_config (Optional[OptimStateDictConfig]): the configuration
                for the optimizer state dict.

        Returns:
            A StateDictSettings that include the previous state_dict type and
            configuration for the module.
        a  FSDP.state_dict_type() and FSDP.set_state_dict_type() are being deprecated. Please use APIs, get_state_dict() and set_state_dict(), which can support different parallelisms, FSDP1, FSDP2, DDP. API doc: https://pytorch.org/docs/stable/distributed.checkpoint.html#torch.distributed.checkpoint.state_dict.get_state_dict .Tutorial: https://pytorch.org/tutorials/recipes/distributed_checkpoint_recipe.html .Nz#Expected state_dict_config of type 	 but got z)Expected optim_state_dict_config of type z6All FSDP modules should have the same state_dict_type.z>All FSDP modules must have the same type of state_dict_config.zDAll FSDP modules must have the same type of optim_state_dict_config.)r}   r~   FutureWarningr<   FULL_STATE_DICTr2   LOCAL_STATE_DICTr4   SHARDED_STATE_DICTr8   r1   r3   r7   typeRuntimeErrorr   r   _state_dict_type_state_dict_configry   _optim_state_dict_configr;   )r`   r   r   r   _state_dict_type_to_config _optim_state_dict_type_to_configstate_dict_config_typeoptim_state_dict_config_typeprev_state_dict_typeprev_state_dict_configprev_optim_state_dict_config	submodules               r^   set_state_dict_typez,FullyShardedDataParallel.set_state_dict_typex  s<   ` 	c 	
 ))+>**,@,,.D&
" ))+C**,E,,.I,
( "<O!L'G'X$$ 6 8"*&B&D#!T*;%<<56L5M N 1235  (40G+HH;<X;Y Z 789;   $!%'+$(99&A 	II#+'0'A'A$+y/I/II LI &-)2)E)E&!00$7M2N TST  ,3/8/Q/Q,!6656  [	  *9I&+<I(1HI.3	I6 ! "8:V
 	
r]   c                 H   d}t         j                  |       D ]  }|9t        |j                  |j                  |j
                        }t        ||       >t        |j                  |j                  |j
                        }||k(  sJ d| d| d       t        ||        |S )a  Get the state_dict_type and the corresponding configurations for the FSDP modules rooted at ``module``.

        The target module does not have to be an FSDP module.

        Returns:
            A ``StateDictSettings`` containing the state_dict_type and
            state_dict / optim_state_dict configs that are currently set.

        Raises:
            ``AssertionError`` if the ``StateDictSettings`` for different
            FSDP submodules differ.
        N)r   r   r   z<All FSDP modules must have the same state dict settings.Got z and .)rR   r   r;   r   r   r   rI   )r`   state_dict_settingsr   submodule_settingss       r^   get_state_dict_typez,FullyShardedDataParallel.get_state_dict_type  s     <@1>>vF 	FI"*&7$-$>$>&/&B&B,5,N,N'#
 'y2EF%6..0066&"
 +.@@ -.e4G3HK@ 'y2DE%	F& #"r]   c              #      K   t         j                  | |||      }d t         j                  | |j                  |j                  |j                         yw)a  Set the ``state_dict_type`` of all the descendant FSDP modules of the target module.

        This context manager has the same functions as :meth:`set_state_dict_type`. Read the document of
        :meth:`set_state_dict_type` for the detail.

        Example::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> model = DDP(FSDP(...))
            >>> with FSDP.state_dict_type(
            >>>     model,
            >>>     StateDictType.SHARDED_STATE_DICT,
            >>> ):
            >>>     checkpoint = model.state_dict()

        Args:
            module (torch.nn.Module): Root module.
            state_dict_type (StateDictType): the desired ``state_dict_type`` to set.
            state_dict_config (Optional[StateDictConfig]): the model ``state_dict``
                configuration for the target ``state_dict_type``.
            optim_state_dict_config (Optional[OptimStateDictConfig]): the optimizer
               ``state_dict`` configuration for the target ``state_dict_type``.
        N)rR   r   r   r   r   )r`   r   r   r   prev_state_dict_settingss        r^   r   z(FullyShardedDataParallel.state_dict_type  sV     > $<#O#O#	$
  	 44$44$66$<<		
s   AAargskwargsc           	         | j                   }t        j                  j                  j	                  d      5  t        | | ||      \  }}d}t        | |t        | j                  ||      \  }}|rQt        |j                  j                  | j                  k(  d| j                   d|j                  j                           | j                  |i |}t        | |t        | ||      cddd       S # 1 sw Y   yxY w)zjRun the forward pass for the wrapped module, inserting FSDP-specific pre- and post-forward sharding logic.z FullyShardedDataParallel.forwardNz5Expected `FlatParameter` to be on the compute device r   )r   rt   autogradprofilerrecord_functionr+   r)   r*   r   r>   r   devicecompute_devicer'   r(   )r   r   r   handleunusedoutputs         r^   forwardz FullyShardedDataParallel.forwardB  s    ^^$$44.
 	 -T4vFLD&F'$))LD& %%,,0C0CCK**+9V5F5F5M5M4NP
 /T..??F f3T66)	 	 	s   B-C--C6recurser   r   r   r   c              #   ^   K   t        | |||||      5  d ddd       y# 1 sw Y   yxY ww)a1  Expose full params for FSDP instances with this context manager.

        Can be useful *after* forward/backward for a model to get
        the params for additional processing or checking. It can take a non-FSDP
        module and will summon full params for all contained FSDP modules as
        well as their children, depending on the ``recurse`` argument.

        .. note:: This can be used on inner FSDPs.
        .. note:: This can *not* be used within a forward or backward pass. Nor
            can forward and backward be started from within this context.
        .. note:: Parameters will revert to their local shards after the context
            manager exits, storage behavior is the same as forward.
        .. note:: The full parameters can be modified, but only the portion
            corresponding to the local param shard will persist after the
            context manager exits (unless ``writeback=False``, in which case
            changes will be discarded). In the case where FSDP does not shard
            the parameters, currently only when ``world_size == 1``, or ``NO_SHARD``
            config, the modification is persisted regardless of ``writeback``.
        .. note:: This method works on modules which are not FSDP themselves but
            may contain multiple independent FSDP units. In that case, the given
            arguments will apply to all contained FSDP units.

        .. warning:: Note that ``rank0_only=True`` in conjunction with
            ``writeback=True`` is not currently supported and will raise an
            error. This is because model parameter shapes would be different
            across ranks within the context, and writing to them can lead to
            inconsistency across ranks when the context is exited.

        .. warning:: Note that ``offload_to_cpu`` and ``rank0_only=False`` will
            result in full parameters being redundantly copied to CPU memory for
            GPUs that reside on the same machine, which may incur the risk of
            CPU OOM. It is recommended to use ``offload_to_cpu`` with
            ``rank0_only=True``.

        Args:
            recurse (bool, Optional): recursively summon all params for nested
                FSDP instances (default: True).
            writeback (bool, Optional): if ``False``, modifications to params are
                discarded after the context manager exits;
                disabling this can be slightly more efficient (default: True)
            rank0_only (bool, Optional): if ``True``, full parameters are
                materialized on only global rank 0. This means that within the
                context, only rank 0 will have full parameters and the other
                ranks will have sharded parameters. Note that setting
                ``rank0_only=True`` with ``writeback=True`` is not supported,
                as model parameter shapes will be different across ranks
                within the context, and writing to them can lead to
                inconsistency across ranks when the context is exited.
            offload_to_cpu (bool, Optional): If ``True``, full parameters are
                offloaded to CPU. Note that this offloading currently only
                occurs if the parameter is sharded (which is only not the case
                for world_size = 1 or ``NO_SHARD`` config). It is recommended
                to use ``offload_to_cpu`` with ``rank0_only=True`` to avoid
                redundant copies of model parameters being offloaded to the same CPU memory.
            with_grads (bool, Optional): If ``True``, gradients are also
                unsharded with the parameters. Currently, this is only
                supported when passing ``use_orig_params=True`` to the FSDP
                constructor and ``offload_to_cpu=False`` to this method.
                (Default: ``False``)
        N)rN   )r`   r   r   r   r   r   s         r^   summon_full_paramsz+FullyShardedDataParallel.summon_full_params]  s7     L GY
NJ
 	 	 	 	s   -!	-*-c              #   0  K   t        | j                  d       t        j                  |       D ]  }t	        ||        	 d t        j                  |       D ]  }t        ||        y# t        j                  |       D ]  }t        ||        w xY ww)a  Deregister the original parameters and expose the :class:`FlatParameter`.

        If a :class:`FlatParameter` is sharded, then
        this refreshes the sharded views before exiting. This method should
        only be called when using the original parameters.
        zR`_deregister_orig_params_ctx()` should only be called when `_use_orig_params=True`N)r>   _use_orig_paramsr   r   rK   rM   )r   fsdp_modules     r^   _deregister_orig_params_ctxz4FullyShardedDataParallel._deregister_orig_params_ctx  s      	!!&	

 +;;DA 	>K#K=	>	@.??E @%k;?@??E @%k;?@s   =B A+ 'B+(BBc                     | j                   r| j                         nt        j                         }|5  t	        |   |i |cddd       S # 1 sw Y   yxY w)zgDeregister the original parameters and expose the :class:`FlatParameter` s before calling ``_apply()``.N)r   r   
contextlibnullcontextrw   _apply)r   r   r   contextr   s       r^   r   zFullyShardedDataParallel._apply  sX     $$ ,,.'') 	
  	37>4262	3 	3 	3s   AAc              /      K   | j                   t        j                  k(  }t        |   |i |D ]#  \  }}|r|j                  t        d      }||f % yw)a  Return an iterator over module buffers, yielding both the name of the buffer and the buffer itself.

        Intercepts buffer names and removes all occurrences of the FSDP-specific flattened buffer prefix
        when inside the :meth:`summon_full_params` context manager.
         N)training_stater   SUMMON_FULL_PARAMSrw   named_buffersreplacer   )r   r   r   should_clean_namebuffer_namebufferr   s         r^   r   z&FullyShardedDataParallel.named_buffers  se      !//=3S3SS#(7#8$#I&#I 	(K  *11+rB''	(   AAc              /      K   | j                   t        j                  k(  }t        |   |i |D ]#  \  }}|r|j                  t        d      }||f % yw)a)  Return an iterator over module parameters, yielding both the name of the parameter and the parameter itself.

        Intercepts parameter names and removes all occurrences of the FSDP-specific flattened parameter prefix
        when inside the :meth:`summon_full_params` context manager.
        r   N)r   r   r   rw   named_parametersr   r   )r   r   r   r   
param_nameparamr   s         r^   r   z)FullyShardedDataParallel.named_parameters  se      !//=3S3SS!&!94!J6!J 	&J  (//R@
u%%	&r   statec                     t        |t              r|g}| j                  |vr\d| d| j                   }| j                  dk(  r0t	        d|         t	        d|        t        j                          t        |      y)z!Assert we are in the given state.zexpected to be in states z but current state is r   zAsserting FSDP instance is: zERROR: N)ry   r   r   rankprint	tracebackprint_stack
ValueError)r   r   msgs      r^   r   z&FullyShardedDataParallel._assert_state  s    
 e]+GEe++E7 3))*,  yyA~4TF;<uo&%%'S/! ,r]   c              #     K   t        | |        | j                  st        d      | j                  t        j
                         g }| j                         D ]7  }t        |t              s|j                  ||j                  f       d|_
        9 	 d |D ]  \  }}|j                  rJ d       ||_
        ! y# |D ]  \  }}|j                  rJ d       ||_
        ! w xY ww)a  Disable gradient synchronizations across FSDP instances.

        Within this context, gradients will be accumulated in module
        variables, which will later be synchronized in the first
        forward-backward pass after exiting the context. This should only be
        used on the root FSDP instance and will recursively apply to all
        children FSDP instances.

        .. note:: This likely results in higher memory usage because FSDP will
            accumulate the full model gradients (instead of gradient shards)
            until the eventual sync.

        .. note:: When used with CPU offloading, the gradients will not be
            offloaded to CPU when inside the context manager. Instead, they
            will only be offloaded right after the eventual sync.
        zb`no_sync()` on inner FSDP instances is not supported. Please call `no_sync()` on root FSDP module.FNzX`_sync_gradients` was incorrectly set to `True` while in the `no_sync()` context manager)r&   r   r   r   r   r   modulesry   rR   append_sync_gradients)r   	old_flagsmold_flags       r^   no_syncz FullyShardedDataParallel.no_sync  s     $ 	4}}t  	=--.	 	*A!56  !Q%6%6!78$)!	*	-( -8,, F, %-!-y -8,, F, %-!-s$   A(C$+&C$B; %C$;&C!!C$max_norm	norm_typec                 	   t        | |        | j                  st        d      | j                  &t	        j
                  d| j                        | _        | j                  t        j                         t        d | j                  D              }|r9t        j                  j                  j                  | j                         ||      S t!        |      }t!        |      }t#               }t#               }g }g }g }| j                  D ]  }	|	j$                  r|}
|}n|}
|}|	j&                  rk|	j(                  j*                  D ]Q  }||
vs|
j-                  |       |j/                  |       |j0                  7|j/                  |j0                         S |	j(                  |
vs|
j-                  |	j(                         |j/                  |	j(                         |	j(                  j0                  |j/                  |	j(                  j0                          | j                         D ]Y  }||vxr ||v}|s|j-                  |       |j/                  |       |j0                  ?|j/                  |j0                         [ t3        ||| j                  | j                        }|r"t3        ||| j                  | j                        nd}|t4        j6                  k(  r_|t	        j8                  ||      n|}t;        j<                  |t        j>                  j@                  jB                  | jD                         n8||z  }t;        j<                  || jD                         ||||z  z  }|d|z  z  }| jF                  jH                  r|jK                         }||d	z   z  }t	        jL                  |d
      }|D ]7  }|jO                  |jQ                  |jR                  |jT                               9 tW        |      dk(  r1tY        jZ                  d| j\                   d|jT                          |S t_        j`                  t        jb                  |D cg c]  }|jT                   c}      }|jQ                  |      S c c}w )a  Clip the gradient norm of all parameters.

        The norm is computed over all parameters' gradients as viewed as a single vector, and the
        gradients are modified in-place.

        Args:
            max_norm (float or int): max norm of the gradients
            norm_type (float or int): type of the used p-norm. Can be ``'inf'``
                for infinity norm.

        Returns:
            Total norm of the parameters (viewed as a single vector).

        If every FSDP instance uses ``NO_SHARD``, meaning that no
        gradients are sharded across ranks, then you may directly use
        :func:`torch.nn.utils.clip_grad_norm_`.

        If at least some FSDP instance uses a sharded strategy (i.e.
        one other than ``NO_SHARD``), then you should use this method
        instead of :func:`torch.nn.utils.clip_grad_norm_` since this method
        handles the fact that gradients are sharded across ranks.

        The total norm returned will have the "largest" dtype across
        all parameters/gradients as defined by PyTorch's type promotion
        semantics. For example, if *all* parameters/gradients use a low
        precision dtype, then the returned norm's dtype will be that low
        precision dtype, but if there exists at least one parameter/
        gradient using FP32, then the returned norm's dtype will be FP32.

        .. warning:: This needs to be called on all ranks since it uses
            collective communications.
        zC`clip_grad_norm_()` should only be called on the root FSDP instanceNg        r   c              3   6   K   | ]  }|j                      y wr   )uses_sharded_strategy).0r   s     r^   	<genexpr>z;FullyShardedDataParallel.clip_grad_norm_.<locals>.<genexpr>Z  s      
17,,,
s   )opgroup)r  g      ?gư>)maxr   z&Called FSDP.clip_grad_norm_() on rank zD with no gradients -- returning the total norm in the default dtype )2r&   r   r   r   rt   tensorr   r   r   r   all_all_handlesrz   utilsclip_grad_norm_
parametersfloatsetr  r   r   _paramsaddr  grad_get_grad_normmathinfmaximumdist
all_reducedistributedReduceOpMAXra   rc   offload_paramscpuclampmul_tor   dtypelenr}   r~   r   	functoolsreducepromote_types)r   r  r  all_no_shardsharded_params_setnonsharded_params_setsharded_paramsnonsharded_paramsgradsr   
target_settarget_listr   not_fsdp_managedlocal_sharded_normlocal_nonsharded_norm
total_norm	clip_coefclip_coef_clampedr   total_norm_dtypes                        r^   r  z(FullyShardedDataParallel.clip_grad_norm_,  s/   H 	4}}U  $ %S9L9L MD=--.  
;?;L;L
 
 88>>11!8Y 
 ?)$	 U # $&'' 	=F++/
,2
/&&#..66 5EJ."u-#**51 ::1!LL45 $$J6NN6#4#45&&v'8'89((--9V%6%6%;%;<'	=( __& 	-E//VEAV4V   %))%0!((/::)LL,	- ,It'8'8$:M:M
 ! !9d.?.?ATAT  	   )4 02GH' 
 OOu0099==TEWEW ,Y6JOOJd.@.@A %03Y>>
#i8J**#)J
T 12	 "KK	s; 	EDII'**4;;

CD	E u:? MM8 DN##$&
 $++$)*DTZZ*
 }}-.. +s   R
r?   rr   rs   c                H    |  t        j                  dt        |dz          y y )NzThe `optim_input` argument is deprecated and will be removed after PyTorch 1.13. You may remove it from your code without changing its functionality.r?   rr   r}   r~   r   )optim_inputrs   s     r^   _warn_optim_inputz*FullyShardedDataParallel._warn_optim_input  s)    "MMW%>	 #r]   c                     | |y| yy)NTFr\   )rE  optims     r^   _is_using_optim_inputz.FullyShardedDataParallel._is_using_optim_input  s    5="r]   currnewc          	      V    t        j                  d|  d| d|  dt        |dz          y )Nz``FullyShardedDataParallel.zD``is being deprecated and is replaced by ``FullyShardedDataParallel.z``. ``FullyShardedDataParallel.z$`` may be removed after PyTorch 2.2.r?   rr   rD  )rJ  rK  rs   s      r^   _warn_legacy_optim_state_dictz6FullyShardedDataParallel._warn_legacy_optim_state_dict  s>    )$ 0669U ;**./SU !A~	
r]   )_stacklevelmodelrH  optim_state_dictrE  full_state_dictr  rN  c                F  
 |r1t         j                  ||dz          t         j                  ||      }	nd}	||rJ t         j                  |       d   j                  
t        
fdt         j                  |       D              sJ d       t        | ||||| ||	
|
      S )aR  Transform the state-dict of an optimizer corresponding to a sharded model.

        This is the internal API that is used by all the optim_state_dict implementations.
        Given model, optim, the original optim_state_dict, this API removes the
        FSDP internal information and internal sharding from the optim_state_dict.
        r?   rr   Fr   c              3   <   K   | ]  }|j                   k(    y wr   r   r  r  rm   s     r^   r  zBFullyShardedDataParallel._optim_state_dict_impl.<locals>.<genexpr>  $      
 q111
   9Not all FSDP modules have the same _use_orig_params value)
rO  rH  rP  rE  r   shard_stater  using_optim_inputrm   rc   )rR   rF  rI  r   r   r  rG   )rO  rH  rP  rE  r   rQ  r  rc   rN  rZ  rm   s             @r^   _optim_state_dict_implz/FullyShardedDataParallel._optim_state_dict_impl  s    0 $66a 7  !9 N N!
 !&&z992??F


 	  
-::5A
 
 	G G	G 

 !-#!++/+#
 	
r]   is_named_optimizerc                   
 |r,t         j                  |       t         j                  ||      }nd}||rJ t         j                  |      d   j                  
t        
fdt         j                  |      D              sJ d       |rt        j                  |      dkD  ri } t        | |
|r|nd||      }	t        |	|||||      S )a}  
        Convert an optimizer state-dict so that it can be loaded into the optimizer associated with the FSDP model.

        This is the internal API that is used by all the load optim_state_dict implementations.
        Given model, optim, and the saved optim_state_dict, this API adds the FSDP
        internal information and internal sharding to the optim_state_dict.
        FNr   c              3   <   K   | ]  }|j                   k(    y wr   rT  rU  s     r^   r  zJFullyShardedDataParallel._optim_state_dict_to_load_impl.<locals>.<genexpr>>  rV  rW  rX  )rO  rm   rH  r   r  )rO  rH  rE  rZ  r\  )
rR   rF  rI  r   r   r  r%  get_rankrB   rH   )rP  rO  rE  rH  rQ  r   r\  r  rZ  sharded_osdrm   s             @r^   _optim_state_dict_to_load_implz7FullyShardedDataParallel._optim_state_dict_to_load_impl  s    . $66{C 8 N N!
 !&&z992??F


 	  
-::5A
 
 	G G	G 

 $--.2!/+.5D!
 /#/1
 	
r]   c           
          t         j                  ddd       t         j                  | ||j                         |||dd      S )a$
  Return the full optimizer state-dict.

        Consolidates the full optimizer state on rank 0 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.

        This needs to be called on all ranks since it uses
        collective communications. However, if ``rank0_only=True``, then
        the state dict is only populated on rank 0, and all other ranks
        return an empty :class:`dict`.

        Unlike ``torch.optim.Optimizer.state_dict()``, this method
        uses full parameter names as keys instead of parameter IDs.

        Like in :meth:`torch.optim.Optimizer.state_dict`, the tensors
        contained in the optimizer state dict are not cloned, so there may
        be aliasing surprises. For best practices, consider saving the
        returned optimizer state dict immediately, e.g. using
        ``torch.save()``.

        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.
            optim_input (Optional[Union[List[Dict[str, Any]], Iterable[torch.nn.Parameter]]]):
                Input passed into the optimizer ``optim`` representing either a
                :class:`list` of parameter groups or an iterable of parameters;
                if ``None``, then this method assumes the input was
                ``model.parameters()``. This argument is deprecated, and there
                is no need to pass it in anymore. (Default: ``None``)
            rank0_only (bool): If ``True``, saves the populated :class:`dict`
                only on rank 0; if ``False``, saves it on all ranks. (Default:
                ``True``)
            group (dist.ProcessGroup): Model's process group or ``None`` if using
                the default process group. (Default: ``None``)

        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=True``,
            then nonzero ranks return an empty :class:`dict`.
        full_optim_state_dictrP  rq   rr   T)rO  rH  rP  rE  r   r  rQ  rN  rR   rM  r[  
state_dict)rO  rH  rE  r   r  s        r^   rc  z.FullyShardedDataParallel.full_optim_state_dictV  s\    x 	!>># 	? 	

 (>>"--/#!  ? 	
 		
r]   c           
          t         j                  ddd       t         j                  | ||j                         ddd|d      S )a`  Return the optimizer state-dict in its sharded form.

        The API is similar to :meth:`full_optim_state_dict` but this API chunks
        all non-zero-dimension states to :class:`ShardedTensor` to save memory.
        This API should only be used when the model ``state_dict`` is derived
        with the context manager ``with state_dict_type(SHARDED_STATE_DICT):``.

        For the detailed usage, refer to :meth:`full_optim_state_dict`.

        .. warning:: The returned state dict contains ``ShardedTensor`` and
            cannot be directly used by the regular ``optim.load_state_dict``.
        sharded_optim_state_dictrP  rq   rr   NF)rO  rH  rP  rE  r   rQ  r  rN  rd  )rO  rH  r  s      r^   rg  z1FullyShardedDataParallel.sharded_optim_state_dict  s[    $ 	!>>& 	? 	

 (>>"--/! ? 	
 		
r]   rc  c                 h    t         j                  ddd       t         j                  | |||dd      S )a  Shard a full optimizer state-dict.

        Remaps the state in ``full_optim_state_dict`` to flattened parameters instead of unflattened
        parameters and restricts to only this rank's part of the optimizer state.
        The first argument should be the return value of :meth:`full_optim_state_dict`.

        Example::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
            >>> model, optim = ...
            >>> full_osd = FSDP.full_optim_state_dict(model, optim)
            >>> torch.save(full_osd, PATH)
            >>> # Define new model with possibly different world size
            >>> new_model, new_optim = ...
            >>> full_osd = torch.load(PATH)
            >>> sharded_osd = FSDP.shard_full_optim_state_dict(full_osd, new_model)
            >>> new_optim.load_state_dict(sharded_osd)

        .. note:: Both :meth:`shard_full_optim_state_dict` and
            :meth:`scatter_full_optim_state_dict` may be used to get the
            sharded optimizer state dict to load. Assuming that the full
            optimizer state dict resides in CPU memory, the former requires
            each rank to have the full dict in CPU memory, where each rank
            individually shards the dict without any communication, while the
            latter requires only rank 0 to have the full dict in CPU memory,
            where rank 0 moves each shard to GPU memory (for NCCL) and
            communicates it to ranks appropriately. Hence, the former has
            higher aggregate CPU memory cost, while the latter has higher
            communication cost.

        Args:
            full_optim_state_dict (Dict[str, Any]): Optimizer state dict
                corresponding to the unflattened parameters and holding the
                full non-sharded optimizer state.
            model (torch.nn.Module): Root module (which may or may not be a
                :class:`FullyShardedDataParallel` instance) whose parameters
                correspond to the optimizer state in ``full_optim_state_dict``.
            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()``. This argument is deprecated, and there
                is no need to pass it in anymore. (Default: ``None``)
            optim (Optional[torch.optim.Optimizer]): Optimizer that will load
                the state dict returned by this method. This is the preferred
                argument to use over ``optim_input``. (Default: ``None``)

        Returns:
            Dict[str, Any]: The full optimizer state dict now remapped to
            flattened parameters instead of unflattened parameters and
            restricted to only include this rank's part of the optimizer state.
        shard_full_optim_state_dictoptim_state_dict_to_loadrq   rr   TFrP  rO  rE  rH  rQ  r\  rR   rM  ra  )rc  rO  rE  rH  s       r^   ri  z4FullyShardedDataParallel.shard_full_optim_state_dict  sN    B 	!>>)& 	? 	

 (FF2# $ G 
 	
r]   rg  c                 h    t         j                  ddd       t         j                  | |d|dd      S )a@  Flatten a sharded optimizer state-dict.

        The API is similar to :meth:`shard_full_optim_state_dict`. The only
        difference is that the input ``sharded_optim_state_dict`` should be
        returned from :meth:`sharded_optim_state_dict`. Therefore, there will
        be all-gather calls on each rank to gather ``ShardedTensor`` s.

        Args:
            sharded_optim_state_dict (Dict[str, Any]): Optimizer state dict
                corresponding to the unflattened parameters and holding the
                sharded optimizer state.
            model (torch.nn.Module):
                Refer to :meth:`shard_full_optim_state_dict`.
            optim (torch.optim.Optimizer): Optimizer for ``model`` 's
                parameters.

        Returns:
            Refer to :meth:`shard_full_optim_state_dict`.
         flatten_sharded_optim_state_dictrj  rq   rr   NFrk  rl  )rg  rO  rH  s      r^   rn  z9FullyShardedDataParallel.flatten_sharded_optim_state_dict  sM    2 	!>>.& 	? 	

 (FF5!$ G 
 	
r]   c           
      l    t         j                  ddd       t         j                  | |||ddd|      S )a  Scatter the full optimizer state dict from rank 0 to all other ranks.

        Returns the sharded optimizer state dict on each rank.
        The return value is the same as :meth:`shard_full_optim_state_dict`, and on rank
        0, the first argument should be the return value of
        :meth:`full_optim_state_dict`.

        Example::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
            >>> model, optim = ...
            >>> full_osd = FSDP.full_optim_state_dict(model, optim)  # only non-empty on rank 0
            >>> # Define new model with possibly different world size
            >>> new_model, new_optim, new_group = ...
            >>> sharded_osd = FSDP.scatter_full_optim_state_dict(full_osd, new_model, group=new_group)
            >>> new_optim.load_state_dict(sharded_osd)

        .. note:: Both :meth:`shard_full_optim_state_dict` and
            :meth:`scatter_full_optim_state_dict` may be used to get the
            sharded optimizer state dict to load. Assuming that the full
            optimizer state dict resides in CPU memory, the former requires
            each rank to have the full dict in CPU memory, where each rank
            individually shards the dict without any communication, while the
            latter requires only rank 0 to have the full dict in CPU memory,
            where rank 0 moves each shard to GPU memory (for NCCL) and
            communicates it to ranks appropriately. Hence, the former has
            higher aggregate CPU memory cost, while the latter has higher
            communication cost.

        Args:
            full_optim_state_dict (Optional[Dict[str, Any]]): Optimizer state
                dict corresponding to the unflattened parameters and holding
                the full non-sharded optimizer state if on rank 0; the argument
                is ignored on nonzero ranks.
            model (torch.nn.Module): Root module (which may or may not be a
                :class:`FullyShardedDataParallel` instance) whose parameters
                correspond to the optimizer state in ``full_optim_state_dict``.
            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()``. This argument is deprecated, and there
                is no need to pass it in anymore. (Default: ``None``)
            optim (Optional[torch.optim.Optimizer]): Optimizer that will load
                the state dict returned by this method. This is the preferred
                argument to use over ``optim_input``. (Default: ``None``)
            group (dist.ProcessGroup): Model's process group or ``None`` if
                using the default process group. (Default: ``None``)

        Returns:
            Dict[str, Any]: The full optimizer state dict now remapped to
            flattened parameters instead of unflattened parameters and
            restricted to only include this rank's part of the optimizer state.
        scatter_full_optim_state_dictrj  rq   rr   TFrP  rO  rE  rH  rQ  r   r\  r  rl  )rc  rO  rE  rH  r  s        r^   rp  z6FullyShardedDataParallel.scatter_full_optim_state_dict:  sT    H 	!>>+& 	? 	

 (FF2# $ G 	
 		
r]   optim_state_key_typec                    t         j                  |       t         j                  ||      }|t        j                  t        j
                  fv sJ | }|d   D cg c]  }t        |      t        u  }}|d   D cg c]  }t        |      t        u  }	}t        |      rt        |      rt        |	      r,t        |	      s!d|d   j                          }
t        |
      |t        j                  k(  rt        |      s|t        j
                  k(  rt        |	      r|S i }|t        j                  k(  r|rt        ||      n
t        |      }t        |      }|j!                         D cg c]  }||   	 }}|d   j#                         D ci c]  \  }}||   | c}}|d<   t%        j&                  |d         |d<   |d   D ]$  }t)        |d   D cg c]  }||   	 c}      |d<   & |S |t        j
                  k(  rt+        |      }|rt-        ||      n
t/        |      }|j#                         D ci c]  \  }}||v r|||    }}}|d   j#                         D ci c]  \  }}||   | c}}|d<   t%        j&                  |d         |d<   |d   D ]$  }t)        |d   D cg c]  }||   	 c}      |d<   & |S |S c c}w c c}w c c}w c c}}w c c}w c c}}w c c}}w c c}w )a?  Re-keys the optimizer state dict ``optim_state_dict`` to use the key type ``optim_state_key_type``.

        This can be used to achieve compatibility between optimizer state dicts from models with FSDP
        instances and ones without.

        To re-key an FSDP full optimizer state dict (i.e. from
        :meth:`full_optim_state_dict`) to use parameter IDs and be loadable to
        a non-wrapped model::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> wrapped_model, wrapped_optim = ...
            >>> full_osd = FSDP.full_optim_state_dict(wrapped_model, wrapped_optim)
            >>> nonwrapped_model, nonwrapped_optim = ...
            >>> rekeyed_osd = FSDP.rekey_optim_state_dict(full_osd, OptimStateKeyType.PARAM_ID, nonwrapped_model)
            >>> nonwrapped_optim.load_state_dict(rekeyed_osd)

        To re-key a normal optimizer state dict from a non-wrapped model to be
        loadable to a wrapped model::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> nonwrapped_model, nonwrapped_optim = ...
            >>> osd = nonwrapped_optim.state_dict()
            >>> rekeyed_osd = FSDP.rekey_optim_state_dict(osd, OptimStateKeyType.PARAM_NAME, nonwrapped_model)
            >>> wrapped_model, wrapped_optim = ...
            >>> sharded_osd = FSDP.shard_full_optim_state_dict(rekeyed_osd, wrapped_model)
            >>> wrapped_optim.load_state_dict(sharded_osd)

        Returns:
            Dict[str, Any]: The optimizer state dict re-keyed using the
            parameter keys specified by ``optim_state_key_type``.
        r   zInvalid parameter keys: param_groupsparams)rR   rF  rI  rS   rZ   r[   r   strintanyr  keysr  rC   rD   _get_param_to_fqnvaluesitemscopydeepcopysorted_get_fqn_to_paramrE   rF   )rP  rr  rO  rE  rH  rZ  osd	param_keyuses_param_name_maskuses_param_id_mask	error_msgnew_osdparam_id_to_paramparam_to_param_namer   param_id_to_param_nameparam_idparam_stateparam_groupparam_name_to_paramparam_to_param_idr   param_name_to_param_ids                          r^   rekey_optim_state_dictz/FullyShardedDataParallel.rekey_optim_state_dict  sk   X 	!22;?4JJ
 $((&&(
 
 	
 
 HKGU9Y3 6UUFI'lSd9o4SS$%c2F.G"#C0B,C23w<3D3D3F2GHIY'' !$5$@$@@() $5$>$>>&'J#4#?#?? % 8{K,U3 
 #4E":8I8P8P8R1/4#E*1" 1
 .1\-?-?-A )Hk 'x0+= GG '+mmC4G&HGN#&~6 (. )4H(=$ /x8)H% N!%6%?%??"3E": % 8{K,U3  *=)B)B)D&%J-- -e44&" & 037|/A/A/C +J 'z2K? GG '+mmC4G&HGN#&~6 (. +6h*?& /z:)H% NI  VS01 &
 s0   K:K*KKK
8K!%K'+K-
c                    t         j                  |       }||j                         }t         j                  | ||dt	        |j
                  dd      |j                  t        j                  k(  |t	        |j
                  dd      d	      S )a  
        Transform the state-dict of an optimizer corresponding to a sharded model.

        The given state-dict can be transformed to one of three types:
        1) full optimizer state_dict, 2) sharded optimizer state_dict, 3) local optimizer state_dict.

        For full optimizer state_dict, all states are unflattened and not sharded.
        Rank0 only and CPU only can be specified via :meth:`state_dict_type` to
        avoid OOM.

        For sharded optimizer state_dict, all states are unflattened but sharded.
        CPU only can be specified via :meth:`state_dict_type` to further save
        memory.

        For local state_dict, no transformation will be performed. But a state
        will be converted from nn.Tensor to ShardedTensor to represent its sharding
        nature (this is not supported yet).

        Example::

            >>> # xdoctest: +SKIP("undefined variables")
            >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
            >>> from torch.distributed.fsdp import StateDictType
            >>> from torch.distributed.fsdp import FullStateDictConfig
            >>> from torch.distributed.fsdp import FullOptimStateDictConfig
            >>> # Save a checkpoint
            >>> model, optim = ...
            >>> FSDP.set_state_dict_type(
            >>>     model,
            >>>     StateDictType.FULL_STATE_DICT,
            >>>     FullStateDictConfig(rank0_only=False),
            >>>     FullOptimStateDictConfig(rank0_only=False),
            >>> )
            >>> state_dict = model.state_dict()
            >>> optim_state_dict = FSDP.optim_state_dict(model, optim)
            >>> save_a_checkpoint(state_dict, optim_state_dict)
            >>> # Load a checkpoint
            >>> model, optim = ...
            >>> state_dict, optim_state_dict = load_a_checkpoint()
            >>> FSDP.set_state_dict_type(
            >>>     model,
            >>>     StateDictType.FULL_STATE_DICT,
            >>>     FullStateDictConfig(rank0_only=False),
            >>>     FullOptimStateDictConfig(rank0_only=False),
            >>> )
            >>> model.load_state_dict(state_dict)
            >>> optim_state_dict = FSDP.optim_state_dict_to_load(
            >>>     model, optim, optim_state_dict
            >>> )
            >>> optim.load_state_dict(optim_state_dict)

        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.
            optim_state_dict (Dict[str, Any]): the target optimizer state_dict to
                transform. If the value is None, optim.state_dict() will be used. (
                Default: ``None``)
            group (dist.ProcessGroup): Model's process group across which parameters
                are sharded or ``None`` if using the default process group. (
                Default: ``None``)

        Returns:
            Dict[str, Any]: A :class:`dict` containing the optimizer state for
            ``model``. The sharding of the optimizer state is based on
            ``state_dict_type``.
        Nr   Fr   Trq   )	rO  rH  rP  rE  r   rQ  r  rc   rN  )	rR   r   re  r[  r   r   r   r<   r   )rO  rH  rP  r  r   s        r^   rP  z)FullyShardedDataParallel.optim_state_dict  s    X 7JJ5Q#$//1'>>-#;;\5 0??,,-#;;=Mt  ? 
 	
r]   load_directlyc                     t         j                  |       }t         j                  || d||j                  t        j
                  k(  t        |j                  dd      ||      }|r|j                  |       |S )a|  
        Convert an optimizer state-dict so that it can be loaded into the optimizer associated with the FSDP model.

        Given a ``optim_state_dict`` that is transformed through
        :meth:`optim_state_dict`, it gets converted to the flattened optimizer
        state_dict that can be loaded to ``optim`` which is the optimizer for
        ``model``. ``model`` must be sharded by FullyShardedDataParallel.

            >>> # xdoctest: +SKIP("undefined variables")
            >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
            >>> from torch.distributed.fsdp import StateDictType
            >>> from torch.distributed.fsdp import FullStateDictConfig
            >>> from torch.distributed.fsdp import FullOptimStateDictConfig
            >>> # Save a checkpoint
            >>> model, optim = ...
            >>> FSDP.set_state_dict_type(
            >>>     model,
            >>>     StateDictType.FULL_STATE_DICT,
            >>>     FullStateDictConfig(rank0_only=False),
            >>>     FullOptimStateDictConfig(rank0_only=False),
            >>> )
            >>> state_dict = model.state_dict()
            >>> original_osd = optim.state_dict()
            >>> optim_state_dict = FSDP.optim_state_dict(
            >>>     model,
            >>>     optim,
            >>>     optim_state_dict=original_osd
            >>> )
            >>> save_a_checkpoint(state_dict, optim_state_dict)
            >>> # Load a checkpoint
            >>> model, optim = ...
            >>> state_dict, optim_state_dict = load_a_checkpoint()
            >>> FSDP.set_state_dict_type(
            >>>     model,
            >>>     StateDictType.FULL_STATE_DICT,
            >>>     FullStateDictConfig(rank0_only=False),
            >>>     FullOptimStateDictConfig(rank0_only=False),
            >>> )
            >>> model.load_state_dict(state_dict)
            >>> optim_state_dict = FSDP.optim_state_dict_to_load(
            >>>     model, optim, optim_state_dict
            >>> )
            >>> optim.load_state_dict(optim_state_dict)

        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.
            optim_state_dict (Dict[str, Any]): The optimizer states to be loaded.
            is_named_optimizer (bool): Is this optimizer a NamedOptimizer or
                KeyedOptimizer. Only set to True if ``optim`` is TorchRec's
                KeyedOptimizer or torch.distributed's NamedOptimizer.
            load_directly (bool): If this is set to True, this API will also
                call optim.load_state_dict(result) before returning the result.
                Otherwise, users are responsible to call ``optim.load_state_dict()``
                (Default: ``False``)
            group (dist.ProcessGroup): Model's process group across which parameters
                are sharded or ``None`` if using the default process group. (
                Default: ``None``)
        Nr   Frq  )	rR   r   ra  r   r<   r   r   r   load_state_dict)rO  rH  rP  r\  r  r  r   results           r^   rj  z1FullyShardedDataParallel.optim_state_dict_to_loadk  s    N 7JJ5Q)HH-#33}7T7TT#;;\5  2 I 
 !!&)r]   hookc                 >   | j                         st        d      t        j                  |       D ]j  }|j                  t
        v rt        d|j                         |j                  t        d      t        |      st        d|       ||_        ||_	        l y)aM
  Register a communication hook.

        This is an enhancement that provides a flexible hook to users where they can specify how FSDP aggregates
        gradients across multiple workers.
        This hook can be used to implement several algorithms like
        `GossipGrad <https://arxiv.org/abs/1803.05880>`_ and gradient compression
        which involve different communication strategies for
        parameter syncs while training with :class:`FullyShardedDataParallel`.

        .. warning ::
            FSDP communication hook should be registered before running an initial forward pass
            and only once.

        Args:
            state (object): Passed to the hook to maintain any state information during the training process.
                            Examples include error feedback in gradient compression,
                            peers to communicate with next in `GossipGrad <https://arxiv.org/abs/1803.05880>`_, etc.
                            It is locally stored by each worker
                            and shared by all the gradient tensors on the worker.
            hook (Callable): Callable, which has one of the following signatures:
                            1) ``hook: Callable[torch.Tensor] -> None``:
                            This function takes in a Python tensor, which represents
                            the full, flattened, unsharded gradient with respect to all variables
                            corresponding to the model this FSDP unit is wrapping
                            (that are not wrapped by other FSDP sub-units).
                            It then performs all necessary processing and returns ``None``;
                            2) ``hook: Callable[torch.Tensor, torch.Tensor] -> None``:
                            This function takes in two Python tensors, the first one represents
                            the full, flattened, unsharded gradient with respect to all variables
                            corresponding to the model this FSDP unit is wrapping
                            (that are not wrapped by other FSDP sub-units). The latter
                            represents a pre-sized tensor to store a chunk of a sharded gradient after
                            reduction.
                            In both cases, callable performs all necessary processing and returns ``None``.
                            Callables with signature 1 are expected to handle gradient communication for a `NO_SHARD` case.
                            Callables with signature 2 are expected to handle gradient communication for sharded cases.

        z9register_comm_hook can only be called on a root instance.z;Communication hook is not supported for hybrid strategies: Nz*A communication hook is already registeredz0The communication hook must be callable but got )
r   AssertionErrorr   r   rb   r"   r   callabler  _comm_hook_state)r   r   r  
fsdp_states       r^   register_comm_hookz+FullyShardedDataParallel.register_comm_hook  s    N !!# K  *::4@ 	0J++/II$QR\RnRnQop  $$0$%QRRD> FtfM  %)J!*/J'	0r]   async_opc                     G d d      }| j                   r| j                  t        j                  t        j
                        5  t        | | j                   | j                  | j                         | j                  j                         | _
        d d d        d| j                   _         || j                   | j                        }|r|S |j                          y # 1 sw Y   LxY w)Nc                   <    e Zd Zdee   dej                  fdZd Zy)8FullyShardedDataParallel._unshard.<locals>.UnshardHandleflat_param_handleunshard_eventc                      || _         || _        y r   )_flat_param_handle_unshard_event)r   r  r  s      r^   rx   zAFullyShardedDataParallel._unshard.<locals>.UnshardHandle.__init__   s    
 +<'&3#r]   c                     | j                   G| j                   j                  j                         }|j                  | j                         d | _         y y r   )r  _device_handlecurrent_stream
wait_eventr  )r   r  s     r^   waitz=FullyShardedDataParallel._unshard.<locals>.UnshardHandle.wait  sN    **6//>>MMO # #--d.A.AB.2D+ 7r]   N)	rV   rW   rX   r   rA   rt   Eventrx   r  r\   r]   r^   UnshardHandler    s'    4#+O#<4  %{{43r]   r  T)r   _use_training_stater   FORWARD_BACKWARDr   FORWARDr,   _unshard_stream_pre_unshard_streamrecord_eventr  _prefetchedr  )r   r  r  unshard_handles       r^   r,   z!FullyShardedDataParallel._unshard  s    	3 	3" <<))..0C0K0K J $,,(<(<d>V>V '+&:&:&G&G&I#J (,DLL$&t||T5I5IJ!!J Js   ACC%c                 v    t        | j                  j                         | j                  | j                         y r   )r-   r  r  r  r  r   s    r^   '_wait_unshard_streams_on_current_streamz@FullyShardedDataParallel._wait_unshard_streams_on_current_stream  s.    $..0  $$	
r]   r   handle_training_statec              #   @  K   | j                   }|| _         | j                  r'| j                  j                  }|| j                  _        	 d  || _         | j                  r| j                  _        y y # || _         | j                  r| j                  _        w w xY wwr   )r   r   _training_state)r   r   r  prev_training_stateprev_handle_training_states        r^   r  z,FullyShardedDataParallel._use_training_state&  s      #11,<<)-)E)E&+@DLL(	J"5D||/I,  #6D||/I, s   AB
A4 &B4'BB)F)r   N)NN)TTFFF)g       @)NTTNT)NNTFFN)NTNr   )NNN)FFN)^rV   rW   rX   rY   r/   BACKWARD_PRErz   Moduler#   r   r9   r0   r   r
   rQ   rP   r5   r   rt   rw  r   bool	Parameterr=   rx   propertyr`   r   r@   rT   rv  r	   r   r   r   staticmethodlistr   r   r   r   r   r<   r:   r6   r;   r   r   r   r   r   r   r   r   r   r   r   tupleTensorr   r   r   r   r
  no_gradr  r  rF  rI  rM  rH  	Optimizerdictr%  ProcessGroupr[  ra  rc  rg  ri  rn  rp  rS   r  rP  rj  objectr  r  r,   r  r   r  __classcell__)r   s   @r^   rR   rR   u   s   Y| +/8<,0 8H8U8U48?C?C8<#(!&"& % ,0+r!		r! (r! $$45	r!
 j)r! #(,l:;
r! $$45r! ".1r! "(588??";<r!  "))d): ;<r! E#u||"345r! !r! r!   !r!" #r!$ Xehh0012HXehhoo=V4WW
%r!* j)+r!h )		 ) ) ET E E AXm4 A A< < <(s (s ()t )   8		88 
(	)8 8,&"))d!23 &8R &P=d =VT V-  8<BF	v
		v
&v
 $O4v
 "**>!?	v

 
v
 v
p !#BII !#2C !# !#F  8<BF	)
		)
&)
 $O4)
 "**>!?	)

 
)
  )
VS C C 6   $ G		GG G 	G
 G G 
G  GR @ @(3 ( 
%U\\)*	+	($& 
%UXX///0	1	&$"5]8K)K#L "QU "( $- $- $-L U]]_JMS/eSj)S/6;E3J6GS/	S/ S/j <= c   T   PQ 
C 
c 
# 
 
   $-1 6
 6
xx6
{{$$6
 sCx.6
 T#s(^$++,.
	6
 6
 6
 ))*6
 6
 6
  
c3h!6
 6
p  15 $ #(-19
sCx.9
xx9
 T#s(^$++,.
9
 --.9
 9
 9
 !9
 ))*9
 
c3h9
 9
v  -1I
xxI
{{$$I
 T#s(^$++,.
I
 I
 ))*I
 
c3hI
 I
V  .2
xx
{{$$
 ))*
 
c3h	
 
B  15L
#CH~L
xxL
 T#s(^$++,.
L
 --.L
 
c3hL
 L
\ $
"&sCx.$
xx$
 {{$$$
 
c3h	$
 $
L  15#Q
'S#X7Q
xxQ
 T#s(^$++,.
Q
 --.Q
 }Q
 
c3hQ
 Q
f  15zsCx.z/z xxz T#s(^$++,.
	z --.z 
c3hz zx  6:-1	]
xx]
{{$$]
 #4S>2]
 ))*	]

 
c3h]
 ]
~ 
 $)#-1WxxW{{$$W sCx.W !	W
 W ))*W 
c3hW Wr70 70h 70r B
 J+JDWJ Jr]   ru  r  zeror   r   c                 \   | D cg c]  }|j                   | }}t        |      dk(  r|S |D cg c]  }|j                    }}|D ch c]  }|j                   }}t        |      dk7  rt        d|       t        j
                  j                  t	        j                  |D cg c]@  }t        j
                  j                  |j                         |t        j                        B c}      |t        j                        }	|	j                  |      S c c}w c c}w c c}w c c}w )a   
    Return the gradient norm of parameters ``param`` s, where the gradients are viewed as a single vector.

    The returned norm is in FP32 even if parameters/gradients are in a low precision. This is because the downstream
    use of this return value is a reduction across ranks.
    r   r?   z4Requires uniform dtype across all gradients but got )r/  r  )r   r0  r/  r  rt   linalgvector_normstackdetachfloat32r.  )
ru  r  r  r   r   params_with_gradr9  r   grad_dtypes	grad_norms
             r^   r!  r!  7  s    ,2L%UZZ5KLL
!%56EUZZ6E6*/0$4::0K0
;1B;-P
 	

 (( " ((	(W	
 	mm ) 	I <<v<&&- M 70s   DDD
D$'AD)rO  c                    t        |       }|j                         D ]?  }t        |      dkD  sJ d       t        |      dkD  s't        dt        |       d|        |j	                         D ci c]  \  }}||d    }}}|S c c}}w )a  
    Construct a mapping from parameters to their parameter names.

    The ``model`` should not contain any :class:`FullyShardedDataParallel` instances, which
    means that none of the parameters should be ``FlatParameter`` s. As a
    result, compared to :meth:`_get_param_to_fqns`, the mapped
    values may be flattened from singleton :class:`list` s to the contained
    names themselves.

    Args:
        model (torch.nn.Module): Root module, which should not contain any
            :class:`FullyShardedDataParallel` instances.
    r   z7`_get_param_to_fqns()` should not construct empty listsr?   z=Each parameter should only map to one parameter name but got z: )r   r{  r0  r   r|  )rO  param_to_param_namesparam_namesr   r  s        r^   rz  rz  \  s      .e4+224 ;!# 	
E	
# {aO{#$B{m5  9M8R8R8T"4%{1~  s   1Bc                 z    t        |       }t        t        |j                         |j	                                     S )z;Construct the inverse mapping of :meth:`_get_param_to_fqn`.)rz  r  zipr{  ry  )rO  r  s     r^   r  r  |  s5     ,E2'..02E2J2J2LMNNr]   )~r   r}  r1  r"  r   r}   collections.abcr   r   r   r   enumr   r   typingr	   r
   r   r   rt   torch.distributedr'  r%  'torch.distributed.fsdp._traversal_utilsfsdp_traversal_utilsr   torch.nnrz   ;torch.distributed.algorithms._checkpoint.checkpoint_wrapperr   r   (torch.distributed.algorithms._comm_hooksr   $torch.distributed.fsdp._common_utilsr   r   r   r   r   r   $torch.distributed.fsdp._dynamo_utilsr   "torch.distributed.fsdp._init_utilsr   r   r   r   r   r   r   r   r   r    r!   r"   r#   %torch.distributed.fsdp._runtime_utilsr$   r%   r&   r'   r(   r)   r*   r+   r,   r-   "torch.distributed.fsdp._wrap_utilsr.   torch.distributed.fsdp.apir/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   torch.distributed.tensorr=   torch.distributed.utilsr>   rT   r@   rA   _optim_utilsrB   rC   rD   rE   rF   rG   rH   rI   _state_dict_utilsrJ   _unshard_param_utilsrK   rL   rM   rN   rO   wraprP   rQ   __all__
FLAT_PARAMrS   r  rR   r  r  r  r   r!  r  rv  rz  r  r\   r]   r^   <module>r     s         9 9 %  1 1    A A  I  N      :     0 - 7	 	 	 >  1  
 Jryy* JD>"'R\\""'"' ,,"' LL	"'
 \\"'J88??	%((

c
!"@O88??O	#uxx!!
!"Or]   