U
    Jc                     @   s6  d dl mZmZ d dlZd dlmZ dddddgZejej	ej
jej	 dd	d
Zejejej
jej	 dddZejejej
jej	 dddZejejej
jej	 dddZeeejgej
jej	 f eeejgej
jej	 f dddZeeejgej
jej	 f eeejgej
jej	 f dddZdS )    )AnyCallableNallreduce_hookfp16_compress_hookbf16_compress_hookfp16_compress_wrapperbf16_compress_wrapper)process_grouptensorreturnc                 C   s@   | dk	r| nt jj}||  t j||dd dd S )zEAverages the input gradient tensor by allreduce and returns a future.NTgroupZasync_opc                 S   s   |   d S Nr   )value)fut r   ]/tmp/pip-unpacked-wheel-gikjz4vx/torch/distributed/algorithms/ddp_comm_hooks/default_hooks.py<lambda>       z _allreduce_fut.<locals>.<lambda>)distr   WORLDdiv_size
all_reduce
get_futurethen)r	   r
   group_to_user   r   r   _allreduce_fut   s    r   )r	   bucketr   c                 C   s   t | | S )a{  
    This DDP communication hook just calls ``allreduce`` using ``GradBucket``
    tensors. Once gradient tensors are aggregated across all workers, its ``then``
    callback takes the mean and returns the result. If user registers this hook,
    DDP results is expected to be same as the case where no hook was registered.
    Hence, this won't change behavior of DDP and user can use this as a reference
    or modify this hook to log useful information or any other purposes while
    unaffecting DDP behavior.

    Example::
        >>> # xdoctest: +SKIP
        >>> ddp_model.register_comm_hook(process_group, allreduce_hook)
    )r   buffer)r	   r   r   r   r   r      s    c                    s\   | dk	r| nt jj}| }  tj|}t j	||dd
 } fdd}||S )a/  
    This DDP communication hook implements a simple gradient compression
    approach that casts ``GradBucket`` tensor to half-precision floating-point format (``torch.float16``)
    and then divides it by the process group size.
    It allreduces those ``float16`` gradient tensors. Once compressed gradient
    tensors are allreduced, the chained callback ``decompress`` casts it back to the input data type (such as ``float32``).

    Example::
        >>> # xdoctest: +SKIP
        >>> ddp_model.register_comm_hook(process_group, fp16_compress_hook)
    NTr   c                    s      }||  d  |S r   r   Zcopy_r   r   Zdecompressed_tensorr   r   r   
decompressB   s    z&fp16_compress_hook.<locals>.decompress)r   r   r   r   r   totorchfloat16r   r   r   r   r	   r   r   Z
world_sizeZcompressed_tensorr   r#   r   r"   r   r   +   s      
c                    s\   | dk	r| nt jj}| }  tj|}t j	||dd
 } fdd}||S )a  
    Warning: This API is experimental, and it requires NCCL version later than 2.9.6.

    This DDP communication hook implements a simple gradient compression
    approach that casts ``GradBucket`` tensor to half-precision
    `Brain floating point format <https://en.wikipedia.org/wiki/Bfloat16_floating-point_format>`_ (``torch.bfloat16``)
    and then divides it by the process group size.
    It allreduces those ``bfloat16`` gradient tensors. Once compressed gradient
    tensors are allreduced, the chained callback ``decompress`` casts it back to the input data type (such as ``float32``).

    Example::
        >>> # xdoctest: +SKIP
        >>> ddp_model.register_comm_hook(process_group, bf16_compress_hook)
    NTr   c                    s      }||  d  |S r   r    r!   r"   r   r   r#   f   s    z&bf16_compress_hook.<locals>.decompress)r   r   r   r   r   r$   r%   bfloat16r   r   r   r   r'   r   r"   r   r   L   s      
)hookr   c                    s$   t jtjjtj d fdd}|S )aZ  
    This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
    floating point format (``torch.float16``), and casts the resulting tensor of the given hook back to
    the input data type, such as ``float32``.

    Therefore, ``fp16_compress_hook`` is equivalent to ``fp16_compress_wrapper(allreduce_hook)``.

    Example::
        >>> # xdoctest: +SKIP
        >>> state = PowerSGDState(process_group=process_group, matrix_approximation_rank=1, start_powerSGD_iter=10)
        >>> ddp_model.register_comm_hook(state, fp16_compress_wrapper(powerSGD_hook))
    r   r   c                    s6       tj |  } fdd}||S )Nc                    s      }||   |S Nr    r!   r"   r   r   r#      s    zMfp16_compress_wrapper.<locals>.fp16_compress_wrapper_hook.<locals>.decompress)
set_bufferr   r$   r%   r&   r   Z
hook_stater   r   r#   r)   r"   r   fp16_compress_wrapper_hook   s    
z9fp16_compress_wrapper.<locals>.fp16_compress_wrapper_hookr   
GradBucketr%   futuresFutureTensor)r)   r/   r   r.   r   r   p   s    c                    s$   t jtjjtj d fdd}|S )a  
    Warning: This API is experimental, and it requires NCCL version later than 2.9.6.

    This wrapper casts the input gradient tensor of a given DDP communication hook to half-precision
    `Brain floating point format <https://en.wikipedia.org/wiki/Bfloat16_floating-point_format> `_  (``torch.bfloat16``),
    and casts the resulting tensor of the given hook back to the input data type, such as ``float32``.

    Therefore, ``bf16_compress_hook`` is equivalent to ``bf16_compress_wrapper(allreduce_hook)``.

    Example::
        >>> # xdoctest: +SKIP
        >>> state = PowerSGDState(process_group=process_group, matrix_approximation_rank=1, start_powerSGD_iter=10)
        >>> ddp_model.register_comm_hook(state, bf16_compress_wrapper(powerSGD_hook))
    r*   c                    s6       tj |  } fdd}||S )Nc                    s      }||   |S r+   r    r!   r"   r   r   r#      s    zMbf16_compress_wrapper.<locals>.bf16_compress_wrapper_hook.<locals>.decompress)r,   r   r$   r%   r(   r   r-   r.   r"   r   bf16_compress_wrapper_hook   s    
z9bf16_compress_wrapper.<locals>.bf16_compress_wrapper_hookr0   )r)   r5   r   r.   r   r      s    )typingr   r   r%   Ztorch.distributedZdistributedr   __all__ZProcessGroupr4   r2   r3   r   r1   r   r   r   r   r   r   r   r   r   <module>   s2      " %%