U
    ©Ê¹j/  ã                
   @   sè  d dl Z d dlZd dlmZmZmZmZmZmZm	Z	m
Z
mZmZ d dl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 g Zeee
e
edf e
edf f dœd	d
„Zeej eee
eef dœdd„Ze
edf e
edf e
e
edf eeef f dœdd„Zedeee ƒZ!edej"eƒZ#ee!ej$e%ee! dœdd„ƒZ&ee#ej$e%e
e# dœdd„ƒZ&dd„ Z&d8eee%ddœdd„Z'ej"ej(e%dœdd„Z)ej"e%dœd d!„Z*ed"ƒZ+ed#eee e,e	eeƒZ-eeej"ge+f ej"e+d$œd%d&„ƒZ.eeej"gef e-e-d$œd'd&„ƒZ.d(d&„ Z.e
edf eeeef  ej$e%e
e
edf e
eeef df f d)œd*d+„Z/d9ej0eej" eej1 d,œd-d.„Z2d:ej3ej0e4e4ee e%dd/œd0d1„Z5ej0eej" e4e4dd2œd3d4„Z6eeef eedd5œd6d7„Z7dS );é    N)
ÚAnyÚCallableÚ	ContainerÚDictÚListÚOptionalÚOrderedDictÚTupleÚTypeVarÚoverload)Únn)Ú_get_stream)Ú_is_namedtuple)ÚPackedSequence.)ÚargsÚkwargsÚreturnc                  O   sB   g }t | ƒ}| ¡ D ]\}}| |¡ | |¡ qt|ƒt|ƒfS )aˆ  
    Turn argument list into separate key list and value list (unpack_kwargs does the opposite)
    Inspiration: https://github.com/facebookresearch/fairscale/blob/eeb6684/fairscale/internal/containers.py#L70
    Usage::

        kwarg_keys, flat_args = pack_kwargs(1, 2, a=3, b=4)
        assert kwarg_keys == ("a", "b")
        assert flat_args == (1, 2, 3, 4)
        args, kwargs = unpack_kwargs(kwarg_keys, flat_args)
        assert args == (1, 2)
        assert kwargs == {"a": 3, "b": 4}
    Returns:
        Tuple[Tuple[Any, ...], Tuple[str, ...]]: The first tuple element gives
        gives both positional args and kwarg values, where the positional args
        proceed kwarg values and kwarg values are ordered consistently with the
        kwarg keys. The second tuple element gives the kwarg keys.
        The second tuple element's length is at most the first tuple element's length.
    )ÚlistÚitemsÚappendÚtuple)r   r   Ú
kwarg_keysÚ	flat_argsÚkÚv© r   úV/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torch/distributed/utils.pyÚ_pack_kwargs   s    
r   )Údtyper   r   r   c                    s<   ˆ dkr||fS t jt jdœ‡ fdd„}t||ƒt||ƒfS )z–
    Casts floating point tensors in ``args`` and ``kwargs`` to ``input_dtype``.
    This respects the existing ``requires_grad`` on the tensors.
    N)Úxr   c                    s"   t  | ¡r| jˆ kr| S |  ˆ ¡S ©N)ÚtorchZis_floating_pointr   Úto)r   ©r   r   r   Úcast_fn6   s    z%_cast_forward_inputs.<locals>.cast_fn)r!   ÚTensorÚ_apply_to_tensors)r   r   r   r$   r   r#   r   Ú_cast_forward_inputs*   s    	r'   )r   r   r   c                 C   sv   t |ƒt | ƒks,tdt |ƒ› dt | ƒ› �ƒ‚t |ƒdkr@| i fS | dt |ƒ … }tt|| t |ƒ d… ƒƒ}||fS )zSee _pack_kwargs.ztoo many keys z vs. r   N)ÚlenÚAssertionErrorÚdictÚzip)r   r   r   r   r   r   r   Ú_unpack_kwargs=   s    ÿþr,   ÚSÚT)ÚinputsÚtarget_deviceÚ!use_side_stream_for_tensor_copiesr   c                 C   s   d S r    r   ©r/   r0   r1   r   r   r   Ú_recursive_toM   s    r3   c                 C   s   d S r    r   r2   r   r   r   r3   R   s    c                    s(   ‡ ‡‡fdd„‰zˆ| ƒ}W 5 d‰X |S )z7
    Recursively moves input to the target_device.
    c              	      sÀ  t ˆ tjtfƒrüt ˆ tƒr"ˆ jjnˆ j}|ˆkr6ˆ fS ˆsFˆ  ˆ¡fS tt|jd ƒ}|jdksf|d krrˆ  ˆ¡fS t	ˆƒ}| 
|¡� ˆ  ˆ¡}W 5 Q R X | ˆj¡�J | ¡ }| |¡ t ˆ tƒrÒ|j |¡ nt |tjƒsât‚| |¡ W 5 Q R X |fS tˆ ƒ�r"‡ fdd„ttˆˆ ƒŽ D ƒS t ˆ tƒ�rNtˆ ƒdk�rNtttˆˆ ƒŽ ƒS t ˆ tƒ�r€tˆ ƒdk�r€dd„ ttˆˆ ƒŽ D ƒS t ˆ tƒ�rºtˆ ƒdk�rº‡ fdd„ttˆˆ  ¡ ƒŽ D ƒS ˆ gS )NÚcpuc                    s   g | ]}t ˆ ƒ|Ž ‘qS r   ©Útype)Ú.0r   ©Úobjr   r   Ú
<listcomp>{   s     z1_recursive_to.<locals>.to_map.<locals>.<listcomp>r   c                 S   s   g | ]}t |ƒ‘qS r   )r   ©r7   Úir   r   r   r:      s     c                    s   g | ]}t ˆ ƒ|ƒ‘qS r   r5   r;   r8   r   r   r:   �   s     )Ú
isinstancer!   r%   r   ÚdataÚdevicer"   Úgetattrr6   r   ÚstreamÚindexÚcurrent_streamZwait_streamZrecord_streamr)   r   r+   Úmapr   r(   r   r*   r   )r9   r?   Z
device_modrA   ÚoutputrC   ©r0   Úto_mapr1   r8   r   rG   \   s:    


 z_recursive_to.<locals>.to_mapNr   )r/   r0   r1   Úresr   rF   r   r3   W   s
    )T)ÚcondÚsÚraise_assertion_errorr   c                 C   s$   | s t |ƒ t ¡  |r t|ƒ‚dS )zŽThis is used as an alternate to ``assert`` when in the backward context
    to print the error message ``s`` since otherwise, it is swallowed.N)ÚprintÚ	tracebackÚprint_stackr)   )rI   rJ   rK   r   r   r   Ú	_p_assertŒ   s
    rO   )ÚtensorÚsizer   c              
   C   sp   t  ¡ �^ |  ¡  ¡ | ¡ k}|sT|  ¡  ¡ }t|dkd|› �ƒ |  ¡  | ¡ ¡ | W  5 Q R £ S Q R X dS )zÀ
    Allocate storage for ``tensor`` with the given size.

    Returns:
        bool: ``True`` if this method allocated storage and ``False`` if the
        storage was already allocated.
    r   z8Tensor storage should have been resized to be 0 but got N)r!   Úno_gradÚ_typed_storageÚ_sizeZnumelrO   Ú_resize_)rP   rQ   Zalready_allocatedZtensor_storage_sizer   r   r   Ú_alloc_storage–   s    
þrV   )rP   r   c              
   C   sz   t  ¡ �h |  ¡  ¡ dk}|s^t|  ¡ dkd|  ¡ › d|  ¡  ¡ › d| j› �ƒ |  ¡  d¡ | W  5 Q R £ S Q R X dS )z²
    Frees the underlying storage of ``tensor``.

    Returns:
        bool: ``True`` if the method freed the storage and ``False`` if the
        storage was already freed.
    r   zVFreeing a tensor's storage is unsafe when it is not the sole occupant
storage offset: z
storage size: z
tensor shape: N)r!   rR   rS   rT   rO   Zstorage_offsetÚshaperU   )rP   Zalready_freedr   r   r   Ú_free_storageª   s    

"þrX   ÚQÚR)ÚfnÚ	containerr   c                 C   s   d S r    r   ©r[   r\   r   r   r   r&   Ä   s    r&   c                 C   s   d S r    r   r]   r   r   r   r&   É   s    c                    s   ‡ ‡fdd„‰ ˆ |ƒS )zFRecursively apply to all tensor in different kinds of container types.c                    s  t | tjƒrˆ| ƒS t| dƒrXt | ¡}t |¡D ] }|j}t||ˆ t	||ƒƒƒ q2|S t | t
ƒrŒ|  ¡ }|  ¡ D ]\}}ˆ |ƒ||< qr|S t | tƒr¤ˆ | jƒ | S t | tƒrÄ‡ fdd„|  ¡ D ƒS t| ƒrê‡ fdd„| D ƒ}t| ƒ|Ž S t | tttfƒ�rt| ƒ‡ fdd„| D ƒƒS | S d S )NÚ__dataclass_fields__c                    s   i | ]\}}|ˆ |ƒ“qS r   r   )r7   ÚkeyÚvalue©Úapplyr   r   Ú
<dictcomp>ã   s      z4_apply_to_tensors.<locals>.apply.<locals>.<dictcomp>c                 3   s   | ]}ˆ |ƒV  qd S r    r   ©r7   Úelra   r   r   Ú	<genexpr>å   s     z3_apply_to_tensors.<locals>.apply.<locals>.<genexpr>c                 3   s   | ]}ˆ |ƒV  qd S r    r   rd   ra   r   r   rf   è   s     )r=   r!   r%   ÚhasattrÚdataclassesÚreplaceÚfieldsÚnameÚsetattrr@   r   Ú	__class__r   r   r>   r*   r   r6   r   r   Úset)r   ZdcÚfrk   Zodr_   r`   rH   ©rb   r[   r   r   rb   Ñ   s0    





z _apply_to_tensors.<locals>.applyr   r]   r   rp   r   r&   Î   s    )r/   r   r0   r1   r   c                 C   s¢   | rt | ||ƒng }|r$t |||ƒng }t|ƒt|ƒk r^| dd„ tt|ƒt| ƒ ƒD ƒ¡ n4t|ƒt|ƒk r’| dd„ tt|ƒt|ƒ ƒD ƒ¡ t|ƒt|ƒfS )Nc                 S   s   g | ]}d ‘qS )r   r   ©r7   Ú_r   r   r   r:      s     z_to_kwargs.<locals>.<listcomp>c                 S   s   g | ]}i ‘qS r   r   rq   r   r   r   r:     s     )r3   r(   ÚextendÚranger   )r/   r   r0   r1   Zmoved_inputsZmoved_kwargsr   r   r   Ú
_to_kwargsï   s    ÿýÿý&$ru   ©Úprocess_groupZtensorsÚloggerc                 C   s   t  | ||¡S r    )ÚdistZ_verify_params_across_processesrv   r   r   r   Ú$_verify_param_shape_across_processes  s    rz   )Úmodulerw   Úbroadcast_bucket_sizeÚsrcÚparams_and_buffers_to_ignoreÚbroadcast_buffersr   c           
      C   sj   g }|   ¡ D ]\}}||kr| | ¡ ¡ q|rX|  ¡ D ]\}}	||kr8| |	 ¡ ¡ q8t||||ƒ dS )a2  
    Syncs ``module``'s parameters and buffers state so that all ranks contain
    the same module state across all ranks. Note that this API assumes that all
    parameter shapes are consistent before running the synchronization. This can
    be checked with ``_verify_param_shape_across_processes``.
    N)Znamed_parametersr   ÚdetachZnamed_buffersÚ_sync_params_and_buffers)
r{   rw   r|   r}   r~   r   Úmodule_statesrk   ÚparamÚbufferr   r   r   Ú_sync_module_states  s    r…   )rw   r‚   r|   r}   r   c                 C   s    t |ƒdkrt | |||¡ dS )zu
    Synchronizes ``module_states`` (list of tensors) across all processes by
    broadcasting them from rank 0.
    r   N)r(   ry   Z_broadcast_coalesced)rw   r‚   r|   r}   r   r   r   r�   '  s    
   ÿr�   )Ú
state_dictÚ
old_prefixÚ
new_prefixr   c                 C   sX   ||krt dƒ‚t|  ¡ ƒD ]6}| |¡s,q||t|ƒd…  }| | | |< | |= qdS )a  
    Replace all keys that match a given old_prefix with a new_prefix (in-place).

    Usage::

        state_dict = {"layer.xyz": torch.tensor(1)}
        replace_by_prefix_(state_dict, "layer.", "module.layer.")
        assert state_dict == {"module.layer.xyz": torch.tensor(1)}
    z*old_prefix and new_prefix must be distinctN)Ú
ValueErrorr   ÚkeysÚ
startswithr(   )r†   r‡   rˆ   r_   Znew_keyr   r   r   Ú_replace_by_prefix7  s    
rŒ   )T)N)T)8rh   rM   Útypingr   r   r   r   r   r   r   r	   r
   r   r!   Ztorch.distributedÚdistributedry   r   Ztorch.nn.parallel._functionsr   Z torch.nn.parallel.scatter_gatherr   Ztorch.nn.utils.rnnr   Ú__all__Ústrr   r   r'   r,   r*   r   r   r-   r%   r.   r?   Úboolr3   rO   ÚSizerV   rX   rY   rn   rZ   r&   ru   ZProcessGroupÚLoggerrz   ÚModuleÚintr…   r�   rŒ   r   r   r   r   Ú<module>   s„   0*
ü:5
" "
"û ÿ  ÿ úùû
ü