o
    hL&                     @   s*  d dl Z d dlmZ d dlmZ d dlmZ d dlZd dlm	  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	gZe eZejG d
d dZG dd dejZG dd dZdd Zdd Z dd Z!ej"dee de#ddfddZ$dd Z%G dd	 d	Z&dS )    N)defaultdict)Lock)Optional)Tensor)RRef   )functional_optim_mapDistributedOptimizerc                   @   s   e Zd ZdeddfddZdS )_ScriptLocalOptimizerInterfaceautograd_ctx_idreturnNc                 C   s   d S N )selfr   r   r   u/var/www/html/construction_image-detection-poc/venv/lib/python3.10/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defddZ	  Z
S )_ScriptLocalOptimizerc                    s8   t    dd |D | _|| jg|R i || _d S )Nc                 S      g | ]}|  qS r   local_value.0rrefr   r   r   
<listcomp>0       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   7   s    z._ScriptLocalOptimizer.step.<locals>.<listcomp>)dist_autogradget_gradientsr!   r"   r   )r   r   gradsr   r+   r   r   3   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   r   r   r   r   r   r   r   r   L   r   z,_LocalOptimizer.__init__.<locals>.<listcomp>)r!   r"   r#   r   r   r   r    K   s   z_LocalOptimizer.__init__c                 C   sX   t |}tj | D ]\}}||_q| j  W d    d S 1 s%w   Y  d S r   )r-   r.   r4   global_lockitemsgradr"   r   )r   r   r,   paramr7   r   r   r   r   O   s   
"z_LocalOptimizer.stepN)r   r   r   r   r5   r    r   r   r   r   r   r4   A   s    r4   c                 O   s   t t| |g|R i |S r   )rpcr   r4   )r$   r%   r&   r'   r   r   r   _new_local_optimizerX   s   r:   c                 C      |   }|| d S r   r   r   local_optim_rrefr   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 s%w   Y  d S r   )r   r0   r1   scriptr9   r   r
   )r$   r%   r&   r'   r"   script_optimr   r   r   _new_script_local_optimizerb   s
   

$rC   r>   r   r   c                 C   r;   r   r<   r=   r   r   r   _script_local_optimizer_stepj   s   rD   c                 C   sf   d }g }| D ]$}z	| |  W q ty* } z| | |}W Y d }~qd }~ww |d ur1||S r   )appendwait	Exception)rpc_futs	exceptionresultsfuter   r   r   _wait_for_allr   s   
rM   c                   @   s    e Zd ZdZdd Zdd ZdS )r	   ah
  
    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.

    `DistributedOptimizer` creates the local optimizer with TorchScript enabled
    by default, so that optimizer updates are not blocked by the Python Global
    Interpreter Lock (GIL) in the case of multithreaded training (e.g. Distributed
    Model Parallel). This feature is currently enabled for most optimizers. You
    can also follow `the recipe`__ in PyTorch tutorials to enable TorchScript support
    for your own custom optimizers.

    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::
        >>> # xdoctest: +SKIP("distributed")
        >>> 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)

    __ https://github.com/pytorch/tutorials/pull/1465
    c                 O   s   t jd tt}|D ]}||  | q|tv r&tj	j
r&t|}n|}||k| _| jr3t}ntd| t}g }	| D ]\}
}tj|
|||f| |d}|	| qAt|	| _d S )Nz,torch.distributed.optim.DistributedOptimizera$  Creating the optimizer %s without TorchScript support, this might result in slow computation time in multithreading environment(i.e. Distributed Model Parallel training on CPU) due to the Python's Global Interpreter Lock (GIL). Please file an issue if you need this optimizer in TorchScript. )r&   r'   )torch_C_log_api_usage_oncer   listownerrE   r   r1   _state_enabledgetis_functional_optimrC   loggerwarningr:   r6   r9   	rpc_asyncrM   remote_optimizers)r   optimizer_classparams_rrefr&   r'   per_worker_params_rrefr8   
optim_ctoroptimizer_new_funcremote_optim_futsworkerparam_rrefsremote_optim_rref_futr   r   r   r       s2   

zDistributedOptimizer.__init__c                    s:   t   | jr
tnt fdd| jD }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.
        c                    s$   g | ]}t j| | fd qS ))r&   )r9   rY   rR   )r   	optimizer
context_idoptimizer_step_funcr   r   r      s    z-DistributedOptimizer.step.<locals>.<listcomp>N)r-   _is_valid_contextrV   rD   r@   rZ   rM   )r   rf   rH   r   re   r   r      s   
zDistributedOptimizer.stepN)r   r   r   __doc__r    r   r   r   r   r   r	      s    ;%)'loggingcollectionsr   	threadingr   typingr   rN   torch.distributed.autograddistributedautogradr-   torch.distributed.rpcr9   	torch.jitr1   torch.nnnnr   r   utilsr   __all__	getLoggerr   rW   	interfacer
   Moduler   r4   r:   r@   rC   rA   r   rD   rM   r	   r   r   r   r   <module>   s>   
