U
    *-e/                     @   s   d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dl	m
Z
 ddlmZmZ ddlmZ ddlmZ dejee
d	d
dZdejjeedddZdaedd Zdd ZejjeejjdddZejjejjdddZdejedddZdS )    )contextmanagerN)distributed_c10d)ShardedTensor   )ShardingSpecChunkShardingSpec)ShardingPlan)Sharder)tensorsharding_specreturnc              
   C   s   |   std|dk	r|nt }t|}t|}dg| }tj|||f|d t|D ]h\}}	||	d krtd| d| d|	d  d| ||	d kr^td	| d| d
|	d  d| q^|j	| ||d}
|
S )ab  
    Given a :class:`torch.Tensor`, it shards that tensor according to the provided
    ``sharding_spec``. ``src_rank`` denotes the source rank which would be
    used as the ground truth of the data which would be scattered as shards
    across the rest of the ranks.

    Args:
        tensor (:class:`torch.Tensor`): Tensor needs to be sharded.
        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
            describing how to shard the Tensor.

    Keyword args:
        src_rank (int, optional): The source rank which is used as the ground truth of
            the data for the parameter that would be sharded and scattered
            across the rest of the ranks.
            Default: 0.
        process_group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.

    Returns:
        A :class:`ShardedTensor` sharded from the given tensor.

    .. warning::
        Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
        currently supported as the ``sharding_spec``.
    z'input tensor is not a contiguous TensorN)groupr   z	src_rank=z
 on rank: z does not match with src_rank=r   zsharding_spec=z# does not match with sharding_spec=src_rankprocess_group)
is_contiguous
ValueErrorr   _get_default_groupdistZget_world_sizeZget_rankZall_gather_object	enumerateshard)r
   r   r   r   ZpgZ
world_sizeZcurrent_rankZgathered_listidxentryst r   ]/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/torch/distributed/_shard/api.py_shard_tensor   s$    


r   )module
param_namer   c                 C   s   t | |s"t|   d| dt| |}t|tjs^tdt| j	 d| dt|j	 |
 svtd| dt||||}| |t| dS )	a.  
    Given a :class:`torch.nn.Module`, a ``param_name`` for a parameter in that
    module, it shards that parameter according to the provided
    ``sharding_spec``. ``src_rank`` denotes the source rank which would be
    used as the ground truth of the data which would be scattered as shards
    across the rest of the ranks.

    This method replaces ``module.param_name`` with a
    :class:`torch.distributed._sharded_tensor.ShardedTensor`

    Args:
        module (:class:`torch.nn.Module`): Module whose parameter needs to be sharded.
        param_name (str): Name of the parameter of ``module`` that needs to be sharded.
        sharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`): The specification
            describing how to shard the Tensor.

    Keyword args:
        src_rank (int, optional): The source rank which is used as the ground truth of
            the data for the parameter that would be sharded and scattered
            across the rest of the ranks.
            Default: 0.
        process_group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.

    .. warning::
        Only :class:`torch.distributed._shard.sharding_spec.ChunkShardingSpec` is
        currently supported as the ``sharding_spec``.
    z has no attribute ``z	Expected .z to be a Tensor, but found zparam: z is not a contiguous TensorN)hasattrAttributeErrorZ	_get_namegetattr
isinstancetorchTensorr   type__name__r   r   Zregister_parameternn	Parameter)r   r   r   r   r   r
   r   r   r   r   shard_parameterH   s    #

&r+   c                 c   s*   t dk	rtd| a z
| V  W 5 da X dS )zV
    Context manager to set the process group with which to load a ShardedTensor.
    NzNProcessGroup already set by previous "load_with_process_group" context manager)_CURRENT_PROCESS_GROUPRuntimeError)r   r   r   r   load_with_process_group}   s    
r.   c                   C   s   t dkrt S t S dS )z
    Retrieves the current process group set by ``load_with_process_group``.
    If not set, it just returns the default group.
    N)r,   r   r   r   r   r   r   _get_current_process_group   s    r/   )r   resharding_specr   c                    s    fdd}|  | | S )a  
    Hook a module with output resharding in the forward pass according
    to the given ``resharding_spec``.

    Args:
        module (:class:`torch.nn.Module`): Module whose output needs to be resharded.
        resharding_spec (:class:`torch.distributed._shard.sharding_spec.ShardingSpec`):
            The specification describing how the output of the module will be resharded.

    Returns:
        A :class:`torch.nn.Module` object with reshard API hooked.
    c                    s   t |tr| S |S )N)r$   r   Zreshard)_module_inputoutputr0   r   r   	hook_func   s    

z"_reshard_output.<locals>.hook_funcZregister_forward_hook)r   r0   r5   r   r4   r   _reshard_output   s    
r7   )r   r   c                 C   s   dd }|  | | S )a  
    Hook a module with local shards collection in the forward pass.

    This API is typically used to convert a sharded representation back to data parallel
    representation. In particular, it returns the local tensor for this Shard. If the
    size along the sharding dimension for the local tensor is 1, this dimension is removed
    from the final result. For example a [4, 16] ShardedTensor across 4 ranks is typically
    a local Tensor of size [16] across each rank and not [1, 16] across each rank.

    Args:
        module (:class:`torch.nn.Module`): Module whose output is ShardedTensor and the
            local tensor value needs to be returned.

    Returns:
        A :class:`torch.nn.Module` object with collection API hooked.
    c                 S   sH   t |trD| }|j}t |tr@||jdkr@||jj}|S d S )Nr   )r$   r   local_tensorZ_sharding_specr   sizedimZsqueeze)r1   r2   r3   r8   r   r   r   r   r5      s    

z'_collect_local_shard.<locals>.hook_funcr6   )r   r5   r   r   r   _collect_local_shard   s    
r;   )r   planc                 C   s  g }|j  D ]\}}t|tr|| q|j  D ]\}}t|tr|d\}}}	|D ]$}
||
r\td| d|
 dq\| 	|}t
||	|||d q6t|tr|d\}}}|dkrtd| 	|}| 	|}||}||_q6td| d	q6|jd
k	rV|j D ]<\}}t|trB| 	|}t|| ntd| d	q|jd
k	r|jD ]}| 	|}t| qhd
S )aa  
    Shards a given module according to the provided sharding `plan`. This method
    first shards all the parameters according to the given sharding `plan`. Then if
    `output_plan` and `return_local_tensor` are specified in the sharding `plan`, it
    will tag the output of modules according `output_plan`, convert the module's
    output back to data parallel according to `return_local_tensor`.

    Needs to be called on all ranks in an SPMD fashion.

    Args:
        module (:class:`torch.nn.Module`): The module to apply sharding to
        plan (:class:`torch.distributed._shard.sharding_plan.ShardingPlan`):
            The ShardingPlan which specified param name to ShardingSpec to apply to
            each parameter.

    Keyword args:
         src_rank (int, optional): The source rank which is used as the ground truth of
            the data for the module that would be sharded and scattered across the rest
            of the ranks.
            Default: 0.
        process_group (ProcessGroup, optional): The process group to work on. If None,
            the default process group will be used.
    r    z7ShardingPlan is in-valid, trying to shard a parameter: z1, but there's already a Sharder entry for module z`, parameter sharding should not conflict with the submodule tree that a Sharder is working with!r    z1Module path must not be empty for custom sharder!z:Only `ShardingSpec` and `Sharder` are supported to shard ''Nz5Only `ShardingSpec` is supported as output_plan for ')r<   itemsr$   r	   appendr   
rpartition
startswithr-   Zget_submoduler+   KeyErrorr   mod_name	TypeErrorZoutput_planr7   Zreturn_local_tensorr;   )r   r<   r   r   Zsharder_pathsnamespecmodule_path_r   Zsharder_pathmodZparent_mod_pathrD   Z
parent_modZsharded_modZoutput_specr   r   r   shard_module   sJ    










rK   )r   N)r   N)r   N)
contextlibr   r%   Ztorch.distributeddistributedr   Ztorch.nnr)   r   Z'torch.distributed._shard.sharded_tensorr   r   r   r   Zsharding_planr   Zsharderr	   r&   r   Modulestrr+   r,   r.   r/   r7   r;   rK   r   r   r   r   <module>   sJ       :  3
 #  