a
    Þñhÿ"  ã                   @   s  d dl mZmZ d dlm  m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 ddlmZ d dlm  mZ d dlmZ d dlmZ e	jG d	d
„ d
eƒƒZG dd„ dejƒZG dd„ deƒZdd„ Zdd„ Zdd„ Z e	j!ee e"ddœdd„ƒZ#dd„ Z$G dd„ dƒZ%dS )é    )ÚListÚOptionalN)ÚTensor)ÚRRefé   )Ú_FunctionalAdagrad)Údefaultdict)ÚLockc                   @   s   e Zd Zeddœdd„ZdS )Ú_ScriptLocalOptimizerInterfaceN)Úautograd_ctx_idÚreturnc                 C   s   d S ©N© )Úselfr   r   r   úa/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/distributed/optim/optimizer.pyÚstep   s    z#_ScriptLocalOptimizerInterface.step)Ú__name__Ú
__module__Ú__qualname__Úintr   r   r   r   r   r
      s   r
   c                       s6   e Zd Zeƒ Z‡ fdd„Zejedœdd„ƒZ	‡  Z
S )Ú_ScriptLocalOptimizerc                    s8   t ƒ  ¡  dd„ |D ƒ| _|| jg|¢R i |¤Ž| _d S )Nc                 S   s   g | ]}|  ¡ ‘qS r   ©Úlocal_value©Ú.0Zrrefr   r   r   Ú
<listcomp>(   ó    z2_ScriptLocalOptimizer.__init__.<locals>.<listcomp>)ÚsuperÚ__init__Ú_local_paramsÚoptim©r   Ú	optim_clsÚlocal_params_rrefÚargsÚkwargs©Ú	__class__r   r   r   &   s    
ÿþýz_ScriptLocalOptimizer.__init__)r   c                    s.   t  |¡‰ ‡ fdd„| jD ƒ}| j |¡ d S )Nc                    s    g | ]}|ˆ v rˆ | nd ‘qS r   r   )r   Úp©Úall_local_gradsr   r   r   2   s   ÿz._ScriptLocalOptimizer.step.<locals>.<listcomp>)Údist_autogradÚget_gradientsr   r    r   )r   r   Zgradsr   r)   r   r   .   s
    

þz_ScriptLocalOptimizer.step)r   r   r   r	   Úcompile_lockr   ÚjitÚexportr   r   Ú__classcell__r   r   r&   r   r       s   r   c                   @   s"   e Zd Zeƒ Zdd„ Zdd„ ZdS )Ú_LocalOptimizerc                 O   s.   dd„ |D ƒ| _ || j g|¢R i |¤Ž| _d S )Nc                 S   s   g | ]}|  ¡ ‘qS r   r   r   r   r   r   r   G   r   z,_LocalOptimizer.__init__.<locals>.<listcomp>)r   r    r!   r   r   r   r   F   s    ÿþýz_LocalOptimizer.__init__c                 C   sV   t  |¡}tj�2 | ¡ D ]\}}||_q| j ¡  W d   ƒ n1 sH0    Y  d S r   )r+   r,   r1   Úglobal_lockÚitemsÚgradr    r   )r   r   r*   Úparamr4   r   r   r   r   M   s
    
z_LocalOptimizer.stepN)r   r   r   r	   r2   r   r   r   r   r   r   r1   <   s   r1   c                 O   s   t  t| |g|¢R i |¤Ž¡S r   )Úrpcr   r1   )r"   r#   r$   r%   r   r   r   Ú_new_local_optimizerV   s    ÿr7   c                 C   s   |   ¡ }| |¡ d S r   ©r   r   ©Úlocal_optim_rrefr   Zlocal_optimr   r   r   Ú_local_optimizer_step[   s    r;   c                 O   sX   t | |g|¢R i |¤Ž}t j�& t |¡}t |t¡W  d   ƒ S 1 sJ0    Y  d S r   )r   r-   r.   Úscriptr6   r   r
   )r"   r#   r$   r%   r    Zscript_optimr   r   r   Ú_new_script_local_optimizera   s    
ÿr=   )r:   r   r   c                 C   s   |   ¡ }| |¡ d S r   r8   r9   r   r   r   Ú_script_local_optimizer_stepi   s    r>   c                 C   sh   d }g }| D ]J}z|  | ¡ ¡ W q tyT } z|  |¡ |}W Y d }~qd }~0 0 q|d urd|‚|S r   )ÚappendÚwaitÚ	Exception)Úrpc_futsÚ	exceptionÚresultsZfutÚer   r   r   Ú_wait_for_allq   s    
rF   c                   @   s*   e Zd ZdZejeiZdd„ Zdd„ Z	dS )ÚDistributedOptimizeraG  
    DistributedOptimizer takes remote references to parameters scattered
    across workers and applies the given optimizer locally for each parameter.

    This class uses :meth:`~torch.distributed.autograd.get_gradients` in order
    to retrieve the gradients for specific parameters.

    Concurrent calls to
    :meth:`~torch.distributed.optim.DistributedOptimizer.step`,
    either from the same or different clients, will
    be serialized on each worker -- as each worker's optimizer can only work
    on one set of gradients at a time. However, there is no guarantee that
    the full forward-backward-optimizer sequence will execute for one client
    at a time. This means that the gradients being applied may not correspond
    to the latest forward pass executed on a given worker. Also, there is no
    guaranteed ordering across workers.

    Args:
        optimizer_class (optim.Optimizer): the class of optimizer to
            instantiate on each worker.
        params_rref (list[RRef]): list of RRefs to local or remote parameters
            to optimize.
        args: arguments to pass to the optimizer constructor on each worker.
        kwargs: arguments to pass to the optimizer constructor on each worker.

    Example::
        >>> import torch.distributed.autograd as dist_autograd
        >>> import torch.distributed.rpc as rpc
        >>> from torch import optim
        >>> from torch.distributed.optim import DistributedOptimizer
        >>>
        >>> with dist_autograd.context() as context_id:
        >>>   # Forward pass.
        >>>   rref1 = rpc.remote("worker1", torch.add, args=(torch.ones(2), 3))
        >>>   rref2 = rpc.remote("worker1", torch.add, args=(torch.ones(2), 1))
        >>>   loss = rref1.to_here() + rref2.to_here()
        >>>
        >>>   # Backward pass.
        >>>   dist_autograd.backward(context_id, [loss.sum()])
        >>>
        >>>   # Optimizer.
        >>>   dist_optim = DistributedOptimizer(
        >>>      optim.SGD,
        >>>      [rref1, rref2],
        >>>      lr=0.05,
        >>>   )
        >>>   dist_optim.step(context_id)
    c                 O   s”   t tƒ}|D ]}|| ¡   |¡ qtj ||¡}||k| _| jrHt}nt	}g }	| 
¡ D ],\}
}tj|
|||f| |d�}|	 |¡ qXt|	ƒ| _d S )N)r$   r%   )r   ÚlistÚownerr?   rG   Úfunctional_optim_mapÚgetÚis_functional_optimr=   r7   r3   r6   Ú	rpc_asyncrF   Úremote_optimizers)r   Zoptimizer_classZparams_rrefr$   r%   Zper_worker_params_rrefr5   Z
optim_ctorZoptimizer_new_funcZremote_optim_futsZworkerZparam_rrefsZremote_optim_rref_futr   r   r   r   º   s$    

üzDistributedOptimizer.__init__c                 C   sT   t  |¡ | jrt}nt}g }| jD ]"}| tj| 	¡ |||fd�¡ q$t
|ƒ dS )a%  
        Performs a single optimization step.

        This will call :meth:`torch.optim.Optimizer.step` on each worker
        containing parameters to be optimized, and will block until all workers
        return. The provided ``context_id`` will be used to retrieve the
        corresponding :class:`~torch.distributed.autograd.context` that
        contains the gradients that should be applied to the parameters.

        Args:
            context_id: the autograd context id for which we should run the
                optimizer step.
        )r$   N)r+   Z_is_valid_contextrL   r>   r;   rN   r?   r6   rM   rI   rF   )r   Z
context_idZoptimizer_step_funcrB   Z	optimizerr   r   r   r   Ó   s    

ý
zDistributedOptimizer.stepN)
r   r   r   Ú__doc__r    ZAdagradr   rJ   r   r   r   r   r   r   rG   €   s
   6ÿrG   )&Útypingr   r   Ztorch.distributed.rpcZdistributedr6   Ztorch.optimr    Z	torch.jitr.   Ztorch.nnÚnnZtorchr   r   Zfunctional_adagradr   Ztorch.distributed.autogradZautogradr+   Úcollectionsr   Ú	threadingr	   Z	interfaceÚobjectr
   ÚModuler   r1   r7   r;   r=   r<   r   r>   rF   rG   r   r   r   r   Ú<module>   s0   ý