o
    hv                  
   @   s  U d dl Z d dlZd dlZd dlZd dlZd dlmZmZ d dlm	Z	m
Z
mZmZmZ d dlmZmZmZmZmZmZmZmZ d dlmZ d dlmZmZ d dlZd dlmZ d dlm Z  d d	l!m"Z" erkd d
l#m$Z$ g dZ%e&e'Z(G dd de j)Z*deej+df de*fddZ,G dd deZ-dej+de-fddZ.deej+e
ej+ f ddfddZ/G dd dZ0G dd de0Z1ej2de3de	d fdd Z4G d!d" d"e"Z5d#d$d%eej+ d&eeeeej+  gdf eej+gdf f d'ed( de"fd)d*Z6d+a7e8e9d,< e:e;e;e;f Z<ee9d-< e:e;e;f Z=ee9d.< dej+de<fd/d0Z>dej+de=fd1d2Z?G d3d4 d4Z@G d5d6 d6e0ZAG d7d8 d8e ZBG d9d: d:ZCej2de	eCddf fd;d<ZDd=eeej+e-f  deg df fd>d?ZEd=eeej+e-f  d@edAede:ej+dBf fdCdDZFdS )E    N)defaultdictdeque)	GeneratorIterableIteratorMutableMappingSequence)AnyCallablecastLiteral
NamedTupleOptionalTYPE_CHECKINGUnion)	TypeAlias)WeakKeyDictionaryWeakValueDictionary)Variable)TorchDispatchMode)RemovableHandle)
OpOverload)	saved_tensors_hookssave_on_cpudisable_saved_tensors_hooksregister_multi_grad_hookallow_mutation_on_saved_tensorsNodeGradientEdgeget_gradient_edgeincrement_versionc                   @   s   e Zd ZejdefddZeejdeee	d  e
f df fddZejdefddZeejdee fd	d
ZejdejddfddZejdedef defddZejdedef defddZededefddZdS )r   returnc                 C      t )a6  Return the name.

        Example::

            >>> import torch
            >>> a = torch.tensor([0., 0., 0.], requires_grad=True)
            >>> b = a.clone()
            >>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
            >>> print(b.grad_fn.name())
            CloneBackward0
        NotImplementedErrorself r'   h/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/autograd/graph.pyname0   s   z	Node.name.c                 C   r"   Nr#   r%   r'   r'   r(   next_functions?      zNode.next_functionsc                 C   r"   )zReturn the metadata.r#   r%   r'   r'   r(   metadataD   r,   zNode.metadatac                 C   r"   r*   r#   r%   r'   r'   r(   _input_metadataI   r,   zNode._input_metadatatensorNc                 C   r"   r*   r#   )r&   r/   r'   r'   r(   _register_hook_dictN   s   zNode._register_hook_dictfnc                 C   r"   )a  Register a backward hook.

        The hook will be called every time a gradient with respect to the
        Node is computed. The hook should have the following signature::

            hook(grad_inputs: Tuple[Tensor], grad_outputs: Tuple[Tensor]) -> Tuple[Tensor] or None


        The hook should not modify its argument, but it can optionally return
        a new gradient which will be used in place of :attr:`grad_inputs`.

        This function returns a handle with a method ``handle.remove()``
        that removes the hook from the module.

        .. note::
            See :ref:`backward-hooks-execution` for more information on how when this hook
            is executed, and how its execution is ordered relative to other hooks.

        .. note::
            In the rare case where the hook is registered while the Node has already
            begun execution, there is no longer any guarantee on :attr:`grad_outputs`
            content (it might be as usual or empty depending on other factors). The
            hook can still optionally return a new gradient to be used in place of
            :attr:`grad_inputs` independent of :attr:`grad_outputs`.

        Example::

            >>> import torch
            >>> a = torch.tensor([0., 0., 0.], requires_grad=True)
            >>> b = a.clone()
            >>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
            >>> handle = b.grad_fn.register_hook(lambda gI, gO: (gO[0] * 2,))
            >>> b.sum().backward(retain_graph=True)
            >>> print(a.grad)
            tensor([2., 2., 2.])
            >>> handle.remove() # Removes the hook
            >>> a.grad = None
            >>> b.sum().backward(retain_graph=True)
            >>> print(a.grad)
            tensor([1., 1., 1.])
        r#   r&   r1   r'   r'   r(   register_hookR   s   +zNode.register_hookc                 C   r"   )a  Register a backward pre-hook.

        The hook will be called every time a gradient with respect to the
        Node is computed. The hook should have the following signature::

            hook(grad_outputs: Tuple[Tensor]) -> Tuple[Tensor] or None

        The hook should not modify its argument, but it can optionally return
        a new gradient which will be used in place of :attr:`grad_outputs`.

        This function returns a handle with a method ``handle.remove()``
        that removes the hook from the module.

        .. note::
            See :ref:`backward-hooks-execution` for more information on how when this hook
            is executed, and how its execution is ordered relative to other hooks.

        Example::

            >>> a = torch.tensor([0., 0., 0.], requires_grad=True)
            >>> b = a.clone()
            >>> assert isinstance(b.grad_fn, torch.autograd.graph.Node)
            >>> handle = b.grad_fn.register_prehook(lambda gI: (gI[0] * 2,))
            >>> b.sum().backward(retain_graph=True)
            >>> print(a.grad)
            tensor([2., 2., 2.])
            >>> handle.remove()
            >>> a.grad = None
            >>> b.sum().backward(retain_graph=True)
            >>> print(a.grad)
            tensor([1., 1., 1.])
        r#   r2   r'   r'   r(   register_prehook   s   "zNode.register_prehooksubclassc                 C   s>   | t u r|d ur|ttjj|jd u st|tjjj	rdS t
S )NT)r   getattrtorch_C
_functions__name__
issubclassautogradfunctionBackwardCFunctionNotImplemented)clsr5   r'   r'   r(   __subclasshook__   s   zNode.__subclasshook__)r:   
__module____qualname__abcabstractmethodstrr)   propertytupler   intr+   dictr-   listr	   r.   r7   Tensorr0   r
   r   r3   r4   classmethodtypeboolrA   r'   r'   r'   r(   r   /   s&    &,#r   tr   r!   c                 C   sv   t | tr| jS | jr0| jd u r0t  | | jjd d }W d    n1 s*w   Y  n| j}|d us9J |S Nr   )	
isinstancer   noderequires_gradgrad_fnr7   enable_gradview_asr+   )rP   rS   r'   r'   r(   _get_grad_fn_or_grad_acc   s   

rX   c                   @   s"   e Zd ZU dZeed< eed< dS )r   zObject representing a given gradient edge within the autograd graph.

    To get the gradient edge where a given Tensor gradient will be computed,
    you can do ``edge = autograd.graph.get_gradient_edge(tensor)``.
    rS   	output_nrN)r:   rB   rC   __doc__r   __annotations__rI   r'   r'   r'   r(   r      s   
 r/   c                 C   s"   | j stdt| }t|| jS )zGet the gradient edge for computing the gradient of the given Tensor.

    In particular, it is equivalent to call
    ``g = autograd.grad(loss, input)`` and ``g = autograd.grad(loss, get_gradient_edge(input))``.
    zXIt is not possible to get the gradient edge for a Tensor that does not require gradients)rT   RuntimeErrorrX   r   rY   )r/   rU   r'   r'   r(   r      s   r   c                 C   s"   t | tjr	| f} tj|  dS )ay  Update autograd metadata tracking whether the given Tensor was modified in place.

    This is to enable more accurate error checking within the autograd engine.
    It is already done automatically by PyTorch functions and within custom Function
    when mark_dirty() is called appropriately so you only need to call this explicitly
    if you are doing inplace operation on the Tensor data in a way that Pytorch doesn't
    know about. For example a custom kernel that reads the Tensor data_ptr and modifies
    the memory inplace based on this pointer. Can accept either a tensor, or a list of tensors.

    Note that incrementing the version counter multiple times for a single inplace operation
    is not problematic.

    Note that if you pass in tensor constructed under torch.inference_mode(),
    we will not bump its version counter (because your tensor does not have one).
    N)rR   r7   rL   r8   _increment_version)r/   r'   r'   r(   r       s   r    c                   @   sZ   e Zd ZdZdeejgef deegejf ddfddZddd	Z	d
e
ddfddZdS )r   a	  Context-manager that sets a pair of pack / unpack hooks for saved tensors.

    Use this context-manager to define how intermediary results of an operation
    should be packed before saving, and unpacked on retrieval.

    In that context, the ``pack_hook`` function will be called everytime an
    operation saves a tensor for backward (this includes intermediary results
    saved using
    :func:`~torch.autograd.function._ContextMethodMixin.save_for_backward` but
    also those recorded by a PyTorch-defined operation). The output of
    ``pack_hook`` is then stored in the computation graph instead of the
    original tensor.

    The ``unpack_hook`` is called when the saved tensor needs to be accessed,
    namely when executing :func:`torch.Tensor.backward()` or
    :func:`torch.autograd.grad()`. It takes as argument the *packed* object
    returned by ``pack_hook`` and should return a tensor which has the same
    content as the original tensor (passed as input to the corresponding
    ``pack_hook``).

    The hooks should have the following signatures:

        pack_hook(tensor: Tensor) -> Any

        unpack_hook(Any) -> Tensor

    where the return value of ``pack_hook`` is a valid input to ``unpack_hook``.

    In general, you want ``unpack_hook(pack_hook(t))`` to be equal to ``t`` in terms
    of value, size, dtype and device.

    Example::

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> def pack_hook(x):
        ...     print("Packing", x)
        ...     return x
        >>>
        >>> def unpack_hook(x):
        ...     print("Unpacking", x)
        ...     return x
        >>>
        >>> a = torch.ones(5, requires_grad=True)
        >>> b = torch.ones(5, requires_grad=True) * 2
        >>> with torch.autograd.graph.saved_tensors_hooks(pack_hook, unpack_hook):
        ...     y = a * b
        Packing tensor([1., 1., 1., 1., 1.], requires_grad=True)
        Packing tensor([2., 2., 2., 2., 2.], grad_fn=<MulBackward0>)
        >>> y.sum().backward()
        Unpacking tensor([1., 1., 1., 1., 1.], requires_grad=True)
        Unpacking tensor([2., 2., 2., 2., 2.], grad_fn=<MulBackward0>)

    .. warning ::
        Performing an inplace operation on the input to either hooks may lead
        to undefined behavior.

    .. warning ::
        Only one pair of hooks is allowed at a time. When recursively nesting this
        context-manager, only the inner-most pair of hooks will be applied.
    	pack_hookunpack_hookr!   Nc                 C   s   || _ || _d S r*   )r^   r_   )r&   r^   r_   r'   r'   r(   __init__,  s   
zsaved_tensors_hooks.__init__c                 C   s   t jj| j| j d S r*   )r7   r8   	_autograd!_push_saved_tensors_default_hooksr^   r_   r%   r'   r'   r(   	__enter__4  s   zsaved_tensors_hooks.__enter__argsc                 G   s   t jj  d S r*   )r7   r8   ra    _pop_saved_tensors_default_hooks)r&   rd   r'   r'   r(   __exit__9  s   zsaved_tensors_hooks.__exit__r!   N)r:   rB   rC   rZ   r
   r7   rL   r	   r`   rc   objectrf   r'   r'   r'   r(   r      s    =

r   c                       s0   e Zd ZdZd
dededdf fdd	Z  ZS )r   az  Context manager under which tensors saved by the forward pass will be stored on cpu, then retrieved for backward.

    When performing operations within this context manager, intermediary
    results saved in the graph during the forward pass will be moved to CPU,
    then copied back to the original device when needed for the backward pass.
    If the graph was already on CPU, no tensor copy is performed.

    Use this context-manager to trade compute for GPU memory usage (e.g.
    when your model doesn't fit in GPU memory during training).

    Args:
        pin_memory (bool): If ``True`` tensors will be saved to CPU pinned memory
                           during packing and copied to GPU asynchronously during unpacking.
                           Defaults to ``False``.
                           Also see :ref:`cuda-memory-pinning`.


    Example::

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> a = torch.randn(5, requires_grad=True, device="cuda")
        >>> b = torch.randn(5, requires_grad=True, device="cuda")
        >>> c = torch.randn(5, requires_grad=True, device="cuda")
        >>>
        >>> def f(a, b, c):
        ...     prod_1 = a * b           # a and b are saved on GPU
        ...     with torch.autograd.graph.save_on_cpu():
        ...         prod_2 = prod_1 * c  # prod_1 and c are saved on CPU
        ...     y = prod_2 * a           # prod_2 and a are saved on GPU
        ...     return y
        >>>
        >>> y = f(a, b, c)
        >>> del a, b, c  # for illustration only
        >>> # the content of a, b, and prod_2 are still alive on GPU
        >>> # the content of prod_1 and c only live on CPU
        >>> y.sum().backward()  # all CPU tensors are moved back to GPU, for backward
        >>> # all intermediary tensors are released (deleted) after the call to backward
    Fcuda
pin_memorydevice_typer!   Nc                    sj   t t|tj dtjdttjtjf f fdd}dttjtjf dtjffdd}t || d S )Nr/   r!   c                    sL   s	| j |  fS tj|  | j| j  o| j d}|	|  | j |fS )N)dtypelayoutrj   )
devicecpur7   emptysizerl   rm   is_available	is_sparsecopy_)r/   packeddevice_modulerj   r'   r(   pack_to_cpui  s   

z)save_on_cpu.__init__.<locals>.pack_to_cpuru   c                    s   | \}}|j | dS )N)non_blocking)to)ru   rn   r/   )rj   r'   r(   unpack_from_cpuu  s   z-save_on_cpu.__init__.<locals>.unpack_from_cpu)r6   r7   ri   rL   rH   rn   superr`   )r&   rj   rk   rx   r{   	__class__rv   r(   r`   f  s   &$zsave_on_cpu.__init__)Fri   )r:   rB   rC   rZ   rO   rF   r`   __classcell__r'   r'   r}   r(   r   =  s    $(r   error_message)NNNc              	   c   sz    d}z&t jj }t jj|  dV  W |du r!t jj  dS t jj| dS |du r5t jj  w t jj| w )a  Context-manager that disables the saved tensors default hooks feature.

    Useful for if you are creating a feature that does not work with saved
    tensors default hooks.

    Args:
        error_message (str): When saved tensors default hooks are used when they
                             have been are disabled, a RuntimeError with this
                             error message gets raised.

    Example::

        >>> # xdoctest: +SKIP(failing)
        >>> message = "saved tensors default hooks are disabled"
        >>> with torch.autograd.graph.disable_saved_tensors_hooks(message):
        ...     # Raises RuntimeError: saved tensors default hooks are disabled
        ...     with torch.autograd.graph.save_on_cpu():
        ...         pass
    N)r7   r8   ra   /_saved_tensors_hooks_get_disabled_error_message_saved_tensors_hooks_disable_saved_tensors_hooks_enable)r   maybe_prev_messager'   r'   r(   r   |  s   
r   c                   @   sr   e Zd ZU eedf ed< deedf ddfddZdddZdeedf fd	d
Zdeedf ddfddZ	dS )_MultiHandle.handlesr!   Nc                 C   
   || _ d S r*   r   )r&   r   r'   r'   r(   r`        
z_MultiHandle.__init__c                 C   s   | j D ]}|  qd S r*   )r   remove)r&   handler'   r'   r(   r     s   

z_MultiHandle.removec                 C   s   | j S r*   r   r%   r'   r'   r(   __getstate__  s   z_MultiHandle.__getstate__statec                 C   r   r*   r   )r&   r   r'   r'   r(   __setstate__  r   z_MultiHandle.__setstate__rg   )
r:   rB   rC   rH   r   r[   r`   r   r   r   r'   r'   r'   r(   r     s   
 
r   all)modetensorsr1   r   r   anyc                   s  d}t  ||vrtd| d| |dkrQi di  ttt| t| dtdtt	j
gdf f fdd	tfd
dt| D }t|S |dkrttt	j
gdf tttdt	j
ddffdd	t	fdd| D }t|S )aM  Register a multi-grad backward hook.

    There are two supported modes: ``"all"`` and ``"any"``.

    Under the ``"all"`` mode, the hook will be called after gradients with respect to every tensor in
    :attr:`tensors` have been computed. If a tensor is in :attr:`tensors` but
    is not part of the graph, or if a tensor is not needed to compute the gradients
    for any ``inputs`` specified for the current ``.backward()`` or ``.grad()`` call,
    this tensor will be ignored and the hook will not wait for its gradient to be
    computed.

    After every non-ignored tensor's gradient has been computed, :attr:`fn` will be
    called with those gradients. ``None`` will be passed for tensors that did not
    have their gradients computed.

    Under the ``"any"`` mode, the hook will be called after the first gradient
    with respect to a tensor in :attr:`tensors` has been computed. The hook
    will be called with that gradient as its argument.

    The hook should not modify its arguments.

    This function returns a handle with a method ``handle.remove()`` that removes the hook.

    .. note::
        See :ref:`backward-hooks-execution` for more information on how when this hook
        is executed, and how its execution is ordered relative to other hooks.

    Example::

        >>> import torch
        >>>
        >>> a = torch.rand(2, 3, requires_grad=True)
        >>> b = torch.rand(2, 3, requires_grad=True)
        >>> c = a * b
        >>> d = a * b
        >>>
        >>> def fn(grads):
        ...     print([g is not None for g in grads])
        ...
        >>> torch.autograd.graph.register_multi_grad_hook((a, b, c, d), fn)
        >>>
        >>> c.sum().backward(retain_graph=True)
        [True, True, True, False]
        >>> c.sum().backward(inputs=(a,), retain_graph=True)
        [True, False, True, False]
        >>>
    r   zExpects mode to be one of z	 but got r   Nidxr!   c              	      s*   dt jdd f fdd}|S )Ngradr!   c                    s   t j }|dksJ d|d|<  |d g  |< " | | d }|< |dkr=ttt jjW d    n1 sGw   Y  |  | < d usXJ |d kr{ttt	t
t j  gd f  |  |=  |= d S d S )N6expected this hook to be called inside a backward callr      )r7   r8   _current_graph_task_idgetsummap_will_engine_execute_noder   r
   r   r   rL   )r   id
curr_count)buffercountr1   grad_fnsr   len_tensorslocknb_callsr'   r(   
inner_hook  s,   

	
zDregister_multi_grad_hook.<locals>.get_inner_hook.<locals>.inner_hook)r7   rL   )r   r   )r   r   r1   r   r   r   r   )r   r(   get_inner_hook  s   &z0register_multi_grad_hook.<locals>.get_inner_hookc                 3   s"    | ]\}}|  |V  qd S r*   )r3   ).0irP   )r   r'   r(   	<genexpr>  s    
z+register_multi_grad_hook.<locals>.<genexpr>r   r   c                    sd   t j }|dksJ d | d}|< W d    n1 s#w   Y  |r,d S  |  d S )Nr   r   T)r7   r8   r   )r   r   prev)r1   r   ran_hookr'   r(   
wrapped_fn  s   
z,register_multi_grad_hook.<locals>.wrapped_fnc                 3   s     | ]}|j r| V  qd S r*   )rT   r3   )r   r/   )r   r'   r(   r   '  s    
)	threadingLock
ValueErrorrK   r   rX   lenrI   r
   r7   rL   rH   	enumerater   r   rO   	functoolswrapsr   )r   r1   r   supported_modesr   r'   )
r   r   r1   r   r   r   r   r   r   r   r(   r     s0   8.
r   F(_allow_mutation_on_saved_tensors_enabled_TID_SIDc                 C   s8   t | tjjjtjjjfrd}n|  }t| || j	fS rQ   )
rR   r7   _subclassesfake_tensor
FakeTensorfunctional_tensorFunctionalTensordata_ptrr   _versionr/   r   r'   r'   r(   _get_tidD  s   r   c                 C   s2   t | tjjjtjjjfrd}n|  }|| jfS rQ   )	rR   r7   r   r   r   r   r   r   r   r   r'   r'   r(   _get_sidS  s   
r   c                   @   s   e Zd ZdS )_HandleN)r:   rB   rC   r'   r'   r'   r(   r   b  s    r   c                       s   e Zd Zd fddZ  ZS )_swap_with_clonedctx_AllowMutationOnSavedContextr!   Nc                    sB   dt jdtf fdd}dtdt jf fdd}t || d S )Nr/   r!   c                    sZ   t | }t| }d } j| | | jvr&t }| j|< |  j|< |S  j| }|S r*   )r   r   
sid_to_tidaddtid_to_weakhandler   original)r/   tidsidr   r   r'   r(   r^   h  s   



z-_swap_with_cloned.__init__.<locals>.pack_hookr   c                    sH   d}t sJ ||  jv r j|  }|S |  jv sJ | j|  }|S )NzvTrying to backward outside of the 'allow_mutation_on_saved_tensors' contextin which the graph was originally recorded.)r   clonedr   )r   	error_msgresr   r'   r(   r_   {  s   


z/_swap_with_cloned.__init__.<locals>.unpack_hook)r7   rL   r   r|   r`   )r&   r   r^   r_   r}   r   r(   r`   g  s   z_swap_with_cloned.__init__r   r   r!   N)r:   rB   rC   r`   r   r'   r'   r}   r(   r   f  s    r   c                   @   sR   e Zd ZdddZ		ddd	d
ee deedf dee	eef  def
ddZ
dS )_CloneArgBeforeMutateModer   r   r!   Nc                 C   r   r*   r   )r&   r   r'   r'   r(   r`     r   z"_CloneArgBeforeMutateMode.__init__r'   funcr   typesrd   .kwargsc           	         s   |pi }dt jdd f fdd}t|jjD ]0\}}|jd urF|jjrF|jr-||d  qt|| t	r@|| D ]}|| q8q|||  q||i |S )NrP   r!   c                    sv   t | }t| } j}||jv r7|j| D ]#}||jvrq|j| }||jv r(q|j|  |j|< |j|= qd S d S r*   )r   r   r   r   r   r   r   clone)rP   r   r   r   r   r%   r'   r(   maybe_clone  s   





zA_CloneArgBeforeMutateMode.__torch_dispatch__.<locals>.maybe_cloneout)
r7   rL   r   _schema	arguments
alias_infois_writeis_outrR   rK   )	r&   r   r   rd   r   r   r   argrP   r'   r%   r(   __torch_dispatch__  s   
z,_CloneArgBeforeMutateMode.__torch_dispatch__r   )r'   N)r:   rB   rC   r`   r   rN   rH   r	   r   rJ   r   r'   r'   r'   r(   r     s    

r   c                   @   s    e Zd ZdddZdddZdS )r   r!   Nc                 C   s&   t  | _t  | _t | _tt| _d S r*   )r   r   r   r   r   r   setr   r%   r'   r'   r(   r`     s   z%_AllowMutationOnSavedContext.__init__c                 C   s,   | j   | j  | j  | j  d S r*   )r   clearr   r   r   r%   r'   r'   r(   r     s   


z"_AllowMutationOnSavedContext.clearrg   )r:   rB   rC   r`   r   r'   r'   r'   r(   r     s    
r   c               
   c   s    t  } t| @ t| # ztrtdda| V  W |   dan|   daw W d   n1 s3w   Y  W d   dS W d   dS 1 sKw   Y  dS )a  Context manager under which mutating tensors saved for backward is allowed.

    Under this context manager, tensors saved for backward are cloned on mutation,
    so the original version can still be used during backward. Normally, mutating a tensor
    saved for backward will result in an error raised when it's used during backward.

    To ensure the correct behavior, both the forward and backward should be run under
    the same context manager.

    Returns:
        An _AllowMutationOnSavedContext object storing the state managed by this
        context manager. This object can be useful for debugging purposes. The state
        managed by the context manager is automatically cleared upon exiting.

    Example::

        >>> import torch
        >>> with torch.autograd.graph.allow_mutation_on_saved_tensors():
        ...     # forward
        ...     a = torch.ones(2, 3, requires_grad=True)
        ...     b = a.clone()
        ...     out = (b**2).sum()
        ...     b.sin_()
        ...     # backward
        ...     out.sum().backward()
        ...
        tensor([[0.8415, 0.8415, 0.8415],
                [0.8415, 0.8415, 0.8415]], grad_fn=<SinBackward0>)
    z9allow_mutation_on_saved_tensors contexts cannot be nestedTFN)r   r   r   r   r\   r   r   r'   r'   r(   r     s   #Pr   	t_outputsc                    s   t tt| }dt t dtt fdd}dttj dtfdd dt	ttj  dd f fd	d
fdd||D dfdd}|S )Nrootsr!   c                 s   s    | sd S t  }t }| D ]}|d ur|| || q|rF| }|jD ]\}}||v s3|d u r4q'|| || q'|V  |s d S d S r*   )r   r   r   appendpopleftr+   )r   seenqrS   r1   _r'   r'   r(   
iter_graph  s&   


z:_register_logging_hooks_on_whole_graph.<locals>.iter_graphrP   c                 S   s<   ddl m} | d u rdS || j  ddtt| j dS )Nr   )dtype_abbrsNone[z, ])$torch.testing._internal.common_utilsr   rl   joinr   rF   shape)rP   r   r'   r'   r(   fmt  s   $z3_register_logging_hooks_on_whole_graph.<locals>.fmtgrad_outputsc                    sH   t j }dd fdd| D  d}d| d| }t| d S )Nr   ,c                 3   s    | ]} |V  qd S r*   r'   )r   rP   r   r'   r(   r   "  s    zJ_register_logging_hooks_on_whole_graph.<locals>.prehook.<locals>.<genexpr>r   zExecuting: z with grad_outputs: )r7   r8   _current_autograd_noder   logdebug)r   rS   grad_outputs_strlog_strr   r'   r(   prehook   s   
 z7_register_logging_hooks_on_whole_graph.<locals>.prehookc                    s   g | ]}|  qS r'   )r4   )r   rS   )r   r'   r(   
<listcomp>&  s    z:_register_logging_hooks_on_whole_graph.<locals>.<listcomp>c                     s    D ]} |    qd S r*   )r   )r   r   r'   r(   unregister_hooks(  s   
z@_register_logging_hooks_on_whole_graph.<locals>.unregister_hooksrg   )
rK   r   rX   r   r   r   r7   rL   rF   r   )r   r   r   r   r'   )r   r   r   r(   &_register_logging_hooks_on_whole_graph  s    r   rd   r   .c                 O   sR   t  tjk}|rt| }ztjj| g|R i |W |r!|  S S |r(|  w w r*   )r   getEffectiveLevelloggingDEBUGr   r   _execution_enginerun_backward)r   rd   r   attach_logging_hooksr   r'   r'   r(   _engine_run_backward/  s    r  )GrD   
contextlibr   r   r   collectionsr   r   collections.abcr   r   r   r   r   typingr	   r
   r   r   r   r   r   r   typing_extensionsr   weakrefr   r   r7   torch.autograd.variabler   torch.utils._python_dispatchr   torch.utils.hooksr   
torch._opsr   __all__	getLoggerr:   r   ABCr   rL   rX   r   r   r    r   r   contextmanagerrF   r   r   r   r   rO   r[   rH   rI   r   r   r   r   r   r   r   r   r   r   r  r'   r'   r'   r(   <module>   s   
 (

 "O?#
 %41

0