U
    yh!                     @   s   d Z ddlZddlmZmZmZmZ ddlmZ ddl	m
Z
 ddlmZmZ ejedddZejeee eej f dd	d
Zejee dddZejedddZdS )z
NOTE: This file must be imported like
``import torch.distributed.fsdp._traversal_utils`` and not like
``from torch.distirbuted.fsdp._traversal_utils import ...`` to avoid circular
imports. For brevity, we may import the file as ``traversal_utils``.
    N)DequeListSetTuple_get_registry)
_FSDPState_get_module_fsdp_state)modulereturnc                 C   s   t | }|dkrdS d|kS )zA
    Returns if ``module`` can compose with ``fully_shard``.
    NTZ	replicater   )r
   registry r   Y/var/www/html/venv/lib/python3.8/site-packages/torch/distributed/fsdp/_traversal_utils.py_composable#   s    r   c           	      C   s   g }g }t  }t  }t| g}|r| }|| t|s@q tt| D ]}||krP|	| qPt
|}|dk	r ||kr || || || q ||fS )a  
    Returns a tuple containing:
    1. A list of the ``_FSDPState`` instances in the module tree rooted at
    ``module`` without any duplicates and following the ``module.modules()``
    traversal order (which is assumed to be depth-first).
    2. A corresponding list of the modules owning the states in the first list.

    For the wrapper code path, both returned lists are the same, each
    containing all ``FullyShardedDataParallel`` instances. For the composable
    code path, this returns a list of all composable state instances and a list
    of the corresponding fully sharded modules. See [Note: Fully Sharded
    Module].

    NOTE: The traversal does not proceed into any module annotated by an
    incompatible API (e.g. ``replicate``).
    N)setcollectionsdequepopleftaddr   reversedlistchildren
appendleftr	   append)	r
   fsdp_statesZfsdp_modulesZvisited_fsdp_statesZvisited_modulesr   	submoduleZchild_moduleZoptional_stater   r   r   _get_fsdp_states_with_modules1   s&    


r   c                 C   s   t | \}}|S )z*See :func:`_get_fsdp_states_with_modules`.)r   )r
   r   _r   r   r   _get_fsdp_statesa   s    r   c                 C   s   dd t | D }|S )z
    Returns all ``FlatParamHandle`` s in the module tree rooted at ``module``
    following the rules in :func:`_get_fsdp_state`.
    c                 S   s   g | ]}|j d k	r|j qS )N)Z_handle).0Z
fsdp_stater   r   r   
<listcomp>l   s   
z%_get_fsdp_handles.<locals>.<listcomp>)r   )r
   Zhandlesr   r   r   _get_fsdp_handlesg   s    r!   )__doc__r   typingr   r   r   r   Ztorch.nnnnZ&torch.distributed._composable.contractr   Z$torch.distributed.fsdp._common_utilsr   r	   Moduleboolr   r   r   r!   r   r   r   r   <module>   s   0