U
    <ºc,  ã                   @   sD   d dl Z d dlmZ G dd„ de jjƒZdd„ Zdd„ Zd	d
„ ZdS )é    N)ÚReplicatedTensorc                   @   s*   e Zd ZdZeddd„ƒZedd„ ƒZdS )ÚReplicatedTensorFunctionzv
    Autograd function to ensure gradients are replicated between the
    replicated tensor and the original one.
    Nc                 C   s   |   d¡ t||ƒS )NF)Zset_materialize_gradsr   )ÚctxÚinpÚprocess_group© r   úT/tmp/pip-unpacked-wheel-gikjz4vx/torch/nn/parallel/_replicated_tensor_ddp_interop.pyÚforward	   s    
z ReplicatedTensorFunction.forwardc                 C   s   |d fS ©Nr   )r   Zgrad_outputr   r   r   Úbackward   s    z!ReplicatedTensorFunction.backward)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ústaticmethodr	   r   r   r   r   r   r      s
   r   c                 C   s   t  | |¡}| j|_|S r
   )r   ÚapplyZgrad)Ztensorr   Zreplicated_tensorr   r   r   Ú_make_replicated_tensor   s    r   c           	      C   sŽ   |   ¡ }| j ¡ D ]0\}}|d k	r6t||t||ƒƒ qt|||ƒ q| j ¡ D ]\}}t|||ƒ qN| j ¡ D ]\}}t||t||ƒƒ qn|S r
   )Z_replicate_for_data_parallelÚ_parametersÚitemsÚsetattrr   Ú_buffersZ_modulesÚ_replicate_module_recurse)	Úmoduler   ZreplicaÚ
param_nameÚparamZbuffer_nameÚbufferÚmodule_nameÚchildr   r   r   r      s    r   c                 C   s&   ddl m} || ƒstdƒ‚t| |ƒS )Nr   )Ú_replicatable_modulezKCannot replicate network where python modules are childrens of ScriptModule)Ztorch.nn.parallel.replicater   ÚRuntimeErrorr   )Únetworkr   r   r   r   r   Ú_replicate_module(   s    r!   )	ZtorchZ*torch.distributed._shard.replicated_tensorr   ZautogradZFunctionr   r   r   r!   r   r   r   r   Ú<module>   s
   