U
    yh#                     @   s   d dl mZmZ d dlmZ d dlZd dlm  m  mZ d dl	m
Z
 d dlmZ d dlmZmZ d dlmZ d dlmZ dgZe
jeeeeeef f e
jd	d
dZdS )    )DictUnionfnmatchN)
DeviceMesh)is_rng_supported_meshTensorParallelRNGTracker)_validate_tp_mesh_dim)ParallelStyleparallelize_module)moduledevice_meshparallelize_planreturnc           
         s  t jd t| t|rLttjtsLt|j	t_tjj
|dd dtj_t|trb|| |S t|tr| D ]\}}|d}t|dkrtd|rv|d t fdd	|  }|D ]4\}}|rd|}	t|||	|i qt||| qqqv| S td
t| ddS )a  
    Apply Tensor Parallelism in PyTorch by parallelizing modules or sub-modules based on a user-specified plan.

    We parallelize module or sub_modules based on a parallelize_plan. The parallelize_plan contains
    :class:`ParallelStyle`, which indicates how user wants the module or sub_module
    to be parallelized.

    User can also specify different parallel style per module fully qualified name (FQN).

    Note that ``parallelize_module`` only accepts a 1-D :class:`DeviceMesh`, if you have a 2-D or N-D :class:`DeviceMesh`,
    slice the DeviceMesh to a 1-D sub DeviceMesh first then pass to this API(i.e. ``device_mesh["tp"]``)

    Args:
        module (:class:`nn.Module`):
            Module to be parallelized.
        device_mesh (:class:`DeviceMesh`):
            Object which describes the mesh topology
            of devices for the DTensor.
        parallelize_plan (Union[:class:`ParallelStyle`, Dict[str, :class:`ParallelStyle`]]):
            The plan used to parallelize the module. It can be either a
            :class:`ParallelStyle` object which contains how
            we prepare input/output for Tensor Parallelism or it can be a
            dict of module FQN and its corresponding :class:`ParallelStyle` object.
    Return:
        A :class:`nn.Module` object parallelized.

    Example::
        >>> # xdoctest: +SKIP("distributed")
        >>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel
        >>> from torch.distributed.device_mesh import init_device_mesh
        >>>
        >>> # Define the module.
        >>> m = Model(...)
        >>> tp_mesh = init_device_mesh("cuda", (8,))
        >>> m = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel(), "w2": RowwiseParallel()})
        >>>

    .. note:: For complex module architecture like Attention, MLP layers, we recommend composing
        different ParallelStyles together (i.e. ``ColwiseParallel`` and ``RowwiseParallel``) and pass
        as a parallelize_plan, to achieves the desired sharding computation.
    z4torch.distributed.tensor.parallel.parallelize_modulei  )Z	base_seedF.r   z9Expect module path to be non-empty, but got empty string!c                    s   t | d  S )Nr   r   )tZatom W/var/www/html/venv/lib/python3.8/site-packages/torch/distributed/tensor/parallel/api.py<lambda>e       z$parallelize_module.<locals>.<lambda>zLExpect Union[ParallelStyle, Dict[str, ParallelStyle]] for parallelize_plan, z found!N)torchZ_CZ_log_api_usage_oncer	   r   
isinstancerandomZ_rng_trackerr   Zdevice_typeZ_manual_seedZdistribute_region_enabledr
   _applydictitemssplitlen
ValueErrorpopfilterZnamed_childrenjoinr   	TypeErrortype)
r   r   r   module_pathZparallelize_styleZpath_splitsZmatched_children_	submoduleZ	leaf_pathr   r   r   r      sB    .
 



 
)typingr   r   r   r   Z torch.distributed._tensor.randomdistributedZ_tensorr   Ztorch.nnnnZtorch.distributed._tensorr   r   r   Z(torch.distributed.tensor.parallel._utilsr	   Z'torch.distributed.tensor.parallel.styler
   __all__Modulestrr   r   r   r   r   <module>   s   