U
    ©Ê¹j„  ã                   @   s²   d dl mZmZmZmZ d dlZd dlmZ ddlm	Z
 eeeejf ZdgZeejdœdd	„Zeeef eejejf d
œdd„Zee eej dœdd„ZG dd„ deƒZdS )é    )ÚDictÚListÚOptionalÚUnionN)Ú _TensorPipeRpcBackendOptionsBaseé   )Ú	constantsÚTensorPipeRpcBackendOptions)ÚdeviceÚreturnc                 C   s*   t  | ¡} | jdkr&td| j› d�ƒ‚| S )NÚcudazA`set_devices` expect a list of CUDA devices, but got device type Ú.)Útorchr
   ÚtypeÚ
ValueError)r
   © r   ú\/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torch/distributed/rpc/options.pyÚ
_to_device   s    

ÿr   )Ú
device_mapr   c                 C   sj   i }i }|   ¡ D ]T\}}t |¡t |¡ }}||krTtd|› d|| › d|› �ƒ‚|||< |||< q|S )Nz9`device_map` only supports 1-to-1 mapping, trying to map ú and ú to )Úitemsr   r
   r   )r   Úfull_device_mapZreverse_mapÚkÚvr   r   r   Ú_to_device_map   s    ÿ
r   )Údevicesr   c                 C   s   t tt| ƒƒS )N)ÚlistÚmapr   ©r   r   r   r   Ú_to_device_list'   s    r    c                
       sœ   e Zd ZdZejejejdddddœee	e
eee
eeef f  eee  ee ee dœ‡ fdd„Ze
eeef dœ‡ fdd„Zee d	œd
d„Z‡  ZS )r	   a'  
    The backend options for
    :class:`~torch.distributed.rpc.TensorPipeAgent`, derived from
    :class:`~torch.distributed.rpc.RpcBackendOptions`.

    Args:
        num_worker_threads (int, optional): The number of threads in the
            thread-pool used by
            :class:`~torch.distributed.rpc.TensorPipeAgent` to execute
            requests (default: 16).
        rpc_timeout (float, optional): The default timeout, in seconds,
            for RPC requests (default: 60 seconds). If the RPC has not
            completed in this timeframe, an exception indicating so will
            be raised. Callers can override this timeout for individual
            RPCs in :meth:`~torch.distributed.rpc.rpc_sync` and
            :meth:`~torch.distributed.rpc.rpc_async` if necessary.
        init_method (str, optional): The URL to initialize the distributed
            store used for rendezvous. It takes any value accepted for the
            same argument of :meth:`~torch.distributed.init_process_group`
            (default: ``env://``).
        device_maps (Dict[str, Dict], optional): Device placement mappings from
            this worker to the callee. Key is the callee worker name and value
            the dictionary (``Dict`` of ``int``, ``str``, or ``torch.device``)
            that maps this worker's devices to the callee worker's devices.
            (default: ``None``)
        devices (List[int, str, or ``torch.device``], optional): all local
            CUDA devices used by RPC agent. By Default, it will be initialized
            to all local devices from its own ``device_maps`` and corresponding
            devices from its peers' ``device_maps``. When processing CUDA RPC
            requests, the agent will properly synchronize CUDA streams for
            all devices in this ``List``.
    N)Únum_worker_threadsÚrpc_timeoutÚinit_methodÚdevice_mapsr   Ú_transportsÚ	_channelsc          
   	      sN   |d kri ndd„ |  ¡ D ƒ}|d kr*g nt|ƒ}	tƒ  |||||||	¡ d S )Nc                 S   s   i | ]\}}|t |ƒ“qS r   )r   )Ú.0r   r   r   r   r   Ú
<dictcomp>[   s      z8TensorPipeRpcBackendOptions.__init__.<locals>.<dictcomp>)r   r    ÚsuperÚ__init__)
Úselfr!   r"   r#   r$   r   r%   r&   Zfull_device_mapsZfull_device_list©Ú	__class__r   r   r*   M   s    ÿýùz$TensorPipeRpcBackendOptions.__init__)Útor   c              	      sz   t |ƒ}tƒ j}||krh| ¡ D ]F\}}||| kr ||| | kr td|› d|› d|| | › �ƒ‚q tƒ  ||¡ dS )a4  
        Set device mapping between each RPC caller and callee pair. This
        function can be called multiple times to incrementally add
        device placement configurations.

        Args:
            to (str): Callee name.
            device_map (Dict of int, str, or torch.device): Device placement
                mappings from this worker to the callee. This map must be
                invertible.

        Example:
            >>> # xdoctest: +SKIP("distributed")
            >>> # both workers
            >>> def add(x, y):
            >>>     print(x)  # tensor([1., 1.], device='cuda:1')
            >>>     return x + y, (x + y).to(2)
            >>>
            >>> # on worker 0
            >>> options = TensorPipeRpcBackendOptions(
            >>>     num_worker_threads=8,
            >>>     device_maps={"worker1": {0: 1}}
            >>>     # maps worker0's cuda:0 to worker1's cuda:1
            >>> )
            >>> options.set_device_map("worker1", {1: 2})
            >>> # maps worker0's cuda:1 to worker1's cuda:2
            >>>
            >>> rpc.init_rpc(
            >>>     "worker0",
            >>>     rank=0,
            >>>     world_size=2,
            >>>     backend=rpc.BackendType.TENSORPIPE,
            >>>     rpc_backend_options=options
            >>> )
            >>>
            >>> x = torch.ones(2)
            >>> rets = rpc.rpc_sync("worker1", add, args=(x.to(0), 1))
            >>> # The first argument will be moved to cuda:1 on worker1. When
            >>> # sending the return value back, it will follow the invert of
            >>> # the device map, and hence will be moved back to cuda:0 and
            >>> # cuda:1 on worker0
            >>> print(rets[0])  # tensor([2., 2.], device='cuda:0')
            >>> print(rets[1])  # tensor([2., 2.], device='cuda:1')
        z=`set_device_map` only supports 1-to-1 mapping, trying to map r   r   N)r   r)   r$   r   r   Z_set_device_map)r+   r.   r   r   Zcurr_device_mapsr   r   r,   r   r   Úset_device_maph   s    -ÿz*TensorPipeRpcBackendOptions.set_device_mapr   c                 C   s   t |ƒ| _dS )ab  
        Set local devices used by the TensorPipe RPC agent. When processing
        CUDA RPC requests, the TensorPipe RPC agent will properly synchronize
        CUDA streams for all devices in this ``List``.

        Args:
            devices (List of int, str, or torch.device): local devices used by
                the TensorPipe RPC agent.
        N)r    r   )r+   r   r   r   r   Úset_devices¢   s    
z'TensorPipeRpcBackendOptions.set_devices)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úrpc_contantsZDEFAULT_NUM_WORKER_THREADSZDEFAULT_RPC_TIMEOUT_SECZDEFAULT_INIT_METHODÚintÚfloatÚstrr   r   Ú
DeviceTyper   r*   r/   r0   Ú__classcell__r   r   r,   r   r	   +   s&   $÷
÷:)Útypingr   r   r   r   r   Ztorch._C._distributed_rpcr   Ú r   r5   r6   r8   r
   r9   Ú__all__r   r   r    r	   r   r   r   r   Ú<module>   s   
þ