a
    ßñhm  ã                   @   s,  d dl 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Zd dlmZmZmZmZmZ dd„ Zd	d
„ Zd$ee jee j f eee j dœdd„Zd%dd„Zd&dd„Zdd„ Zdd„ Zd'edee f eeeeeeeeeedœdd „Zd(edef eee eeeeeeeeed!œd"d#„ZdS ))é    N)Ú_TensorOrTensors)Úcontainer_abcsÚistuple)Úis_tensor_like)Úproduct)ÚCallableÚUnionÚOptionalÚIterableÚListc                 C   sN   t | tjƒr,| jd urJ| j ¡  | j ¡  nt | tjƒrJ| D ]}t|ƒ q<d S ©N)	Ú
isinstanceÚtorchÚTensorÚgradZdetach_Úzero_r   r
   Úzero_gradients)ÚxÚelem© r   úX/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/autograd/gradcheck.pyr   
   s    

r   c                    s”   t | ƒrB|  ¡ s|  ¡ sd S | js&d S | j|  ¡ ˆ f| jtjd�S t	| t
jƒrŒt	| tƒsŒttdd„ ‡ fdd„| D ƒƒƒ}|s€d S t| ƒ|ƒS d S d S )N)ÚdtypeÚlayoutc                 S   s   | d uS r   r   ©r   r   r   r   Ú<lambda>   ó    zmake_jacobian.<locals>.<lambda>c                 3   s   | ]}t |ˆ ƒV  qd S r   )Úmake_jacobian)Ú.0r   ©Únum_outr   r   Ú	<genexpr>   r   z make_jacobian.<locals>.<genexpr>)r   Úis_floating_pointÚ
is_complexÚrequires_gradZ	new_zerosZnelementr   r   Ústridedr   r   r
   ÚstrÚlistÚfilterÚtype)Úinputr   Z	jacobiansr   r   r   r      s    ÿr   F)r   Úonly_requiring_gradÚreturnc                 c   sT   t | ƒr| js|sP| V  n6t| tjƒrPt| tƒsP| D ]}t||ƒD ]
}|V  qBq4d S r   )r   r#   r   r   r
   r%   Úiter_tensors)r   r*   r   Úresultr   r   r   r,   %   s    
r,   çü©ñÒMbP?ç      ð?c              	      sÒ  |du rˆ}ˆˆƒ  ¡ }t||ƒ}t|dƒ}t|ƒ}d‡ ‡‡‡fdd„	}	t||ƒD �]x\}
}|
j�r dd„ }|
 ¡ }t|
 ¡ ƒ}|
 ¡  	¡ }|
 
¡ }||ƒ‰|j}t|ƒD ]r}|| }tdd	„ | ¡ d
d… D ƒŽ D ]F}||  ¡ t|ƒ ‰t‡‡fdd„tt|ƒƒD ƒƒ}|	||||ƒ qÔqªqR|
jtjk�r’|
j}
tˆƒd
k�rPtdtˆƒƒ‚ttdd	„ |
 ¡ D ƒŽ ƒD ]$\}}|
 ¡ }|	||||dd� �qjqR|
j}
ttdd	„ |
 ¡ D ƒŽ ƒD ]\}}|	|
|||ƒ �q²qR|S )a)  
    input: input to `fn`
    target: the Tensors wrt whom Jacobians are calculated (default=`input`)
    grad_out: grad output value used to calculate gradients.

    Note that `target` may not even be part of `input` to `fn`, so please be
    **very careful** in this to not clone `target`.
    NTFc                    s´   ‡‡‡ ‡‡‡fdd„}|ˆƒ}ˆ  ¡ rp|ˆd ƒ}d||d   }d||d   }	ˆ ¡ | ˆ|	 ¡   ||< n@|  ¡ r¤dˆ ¡ | ˆ| ¡    }
t |
¡||< n|ˆ ||< d S )Nc                    s€   | ˆ ks| ˆ d ksJ ‚‡‡‡‡fdd„}ˆˆ   ¡ }||  ˆˆ< |ƒ }||  ˆˆ< |ƒ }|ˆˆ< || dˆ   }| ¡  d¡S )Nù              ð?c                      s"   ˆsˆ ˆƒ  ¡ S ˆ ˆ ¡ gƒS d S r   )ÚcloneZ	to_mkldnnr   )Úfnr)   Ú	is_mkldnnr   r   r   Úfn_outK   s    zZget_numerical_jacobian.<locals>.update_jacobians.<locals>.compute_gradient.<locals>.fn_outé   éÿÿÿÿ)ÚitemÚdetachZreshape)Údeltar4   ÚorigZoutaZoutbÚr)Úepsr2   Úidxr)   r3   r   r   r   Úcompute_gradientG   s    zJget_numerical_jacobian.<locals>.update_jacobians.<locals>.compute_gradientr0   g      à?)r"   Ú	conjugateZconjr   Úreal)r   r=   ÚdÚd_idxr3   r>   Zds_dxZds_dyZconj_w_dZw_dZ
dL_dz_conj)r<   r2   Úgrad_outr)   )r=   r3   r   r   Úupdate_jacobiansC   s    z0get_numerical_jacobian.<locals>.update_jacobiansc                 S   s@   t | ƒ}d}dg| }tt|ƒƒD ]}|||< || | 9 }q"|S )Né   r   )ÚlenÚreversedÚrange)ÚsizeZdimÚtmpÚstrideÚir   r   r   Ú
get_stridew   s    
z*get_numerical_jacobian.<locals>.get_stridec                 S   s   g | ]}t |ƒ‘qS r   ©rH   ©r   Úmr   r   r   Ú
<listcomp>‹   r   z*get_numerical_jacobian.<locals>.<listcomp>rE   c                 3   s   | ]}ˆ | ˆ|  V  qd S r   r   )r   Úk)ÚindicesÚx_strider   r   r    �   r   z)get_numerical_jacobian.<locals>.<genexpr>zCgradcheck currently only supports functions with 1 input, but got: c                 S   s   g | ]}t |ƒ‘qS r   rN   rO   r   r   r   rQ   •   r   )r3   c                 S   s   g | ]}t |ƒ‘qS r   rN   rO   r   r   r   rQ   �   r   )F)Únumelr   r,   ÚzipÚ	is_sparseZ_nnzr&   rI   Z_indicesÚtÚ_valuesÚdatarH   r   ÚtolistÚsumrF   r   r   Ú_mkldnnÚ
ValueErrorÚ	enumerateÚto_dense)r2   r)   Útargetr<   rC   Zoutput_sizeÚjacobianZ	x_tensorsZ	j_tensorsrD   Zx_tensorZd_tensorrM   Zx_nnzZx_sizeZ	x_indicesZx_valuesrL   Zx_valueZx_idxrB   Zx_tensor_denser   )r<   r2   rC   rS   r)   rT   r   Úget_numerical_jacobian/   sF    	

2	" ÿ""rc   ç        c              	   C   sÚ  |j rtdƒ‚|jtjkr"tdƒ‚tt| dƒƒ}t| | ¡ ƒ}t| | ¡ ƒ}tj	|tj
d�}| d¡}d}	d}
d}t| ¡ ƒD �]}| ¡  |||< ||fD ]ð}tjj|||ddd�}t|||ƒD ]È\}}}|d urê| ¡ | ¡ krêd}
qÂ|d u�r|j|jk�rd}qÂ| ¡ dkrÂ|d u �r4|d d …|f  ¡  qÂ|jtjk�sJ| ¡ n|}|d d …|f  ¡ | ¡ k�spJ ‚| ¡  d¡|d d …|f< qÂqœq~t||ƒD ]2\}}| ¡ dk�rš||  ¡  ¡ |k�ršd}	�qš||	|
|fS )	NzjSparse output is not supported at gradcheck yet. Please call to_dense() on the output of fn for gradcheck.zjMKLDNN output is not supported at gradcheck yet. Please call to_dense() on the output of fn for gradcheck.T©Zmemory_formatr6   )Zretain_graphÚallow_unusedFr   )rW   r^   r   r   r]   r&   r,   r   rU   Ú
zeros_likeÚlegacy_contiguous_formatÚviewrH   r   Úautogradr   rV   rI   r   r$   r`   Ú
contiguousÚabsÚmax)r)   ÚoutputÚ
nondet_tolrC   Údiff_input_listrb   Zjacobian_reentrantZgrad_outputZflat_grad_outputÚ	reentrantÚcorrect_grad_sizesÚcorrect_grad_typesrL   Z
jacobian_cÚgrads_inputZ
jacobian_xZd_xr   Z	d_x_denseZjacobian_reentrant_xr   r   r   Úget_analytical_jacobian£   sD    
ÿ
" $ru   c                 C   s(   t | ƒr| S t| tƒrt| ƒS | fS d S r   )r   r   r&   Útupler   r   r   r   Ú	_as_tupleÏ   s
    
rw   c                 C   s   t dd„ t| ƒD ƒƒS )Nc                 s   s   | ]}|j r|V  qd S r   ©r#   ©r   Úor   r   r   r    Ù   r   z*_differentiable_outputs.<locals>.<genexpr>)rv   rw   r   r   r   r   Ú_differentiable_outputsØ   s    r{   ç�íµ ÷Æ°>çñhãˆµøä>T.)ÚfuncÚinputsr<   ÚatolÚrtolÚraise_exceptionÚcheck_sparse_nnzro   Úcheck_undefined_gradÚcheck_grad_dtypesr+   c
           ,         s\  ‡fdd„‰t |ƒ}
|s2tdd„ |
D ƒƒr2ˆdƒS d}t|
ƒD ]Š\}}t|ƒr>|jr>|jtjksv|jtjksvt	 
d¡ |jr„| ¡ n|}|jtjur¼tdd„ t| ¡ | ¡ ƒD ƒƒs¼td	ƒ‚d
}| ¡  q>|sÖtdƒ‚ˆ|
Ž }t|ƒ}|�sPt|ƒD ]V\‰}‡‡fdd„}t||
|d�}|D ],}t |d¡ ¡ dk�rˆdƒ    S �qqôd
S t|ƒD �]À\‰}|j�sn�qX‡‡fdd„}t|
|ˆd�\}}}}t||
|d�}| ¡ }|�rÖt|
|ˆdd�\}}}}t||
|dd�}|�sî|	�rîˆdƒ  S |�r|�s|	�rˆdƒ  S |�sˆdƒ  S |�r6|�s6ˆdƒ  S d7‡ ‡‡‡fdd„	}t|
d
ƒ} tt||| ƒƒD ]z\}!\}"}}|" ¡ dk�sŽ| ¡ dk�rd| ¡ �r¶||! }#||! }$||#|$|!dƒ | ¡ �rÐ||"||!dƒ n||"||!ƒ �qdd8‡‡fdd „	}%|�s |%ƒ   S |�rX|�sX|%d!ƒ  S �qXtˆ|
Ž ƒ}td"d#„ |D ƒƒ�rXtt|
d
ƒƒ‰ˆ�sXtd$ƒ‚tjj |ˆd%d#„ |D ƒd
d&�}&t|&ˆƒD �]4\}'}(|'d'u �r˜�q€t!|'tj"ƒ�rD|'jtj#k�rD|'j|(jk�rêˆd(t$|'jƒ d) t$|(jƒ d* ƒ  S |'jtj%k�r4|' &¡ |( &¡ k�rˆd+ƒ  S |' '¡ |( '¡ k�r4ˆd,ƒ  S |' (¡ }'|( (¡ }(|' )d¡ ¡ �s`ˆd-ƒ  S |'j|(jk�sŠ|'j*|(j*k�sŠ|'j|(jk�r–ˆd.ƒ  S |' ¡ |( ¡ k�r€ˆd/ƒ  S �q€|�rXd0d1„ ‰	‡‡‡	fd2d3„})d4d#„ tˆ|
Ž ƒD ƒg}*t+|*d ƒd5k�r<t,t+|ƒƒD ].‰tˆ|
Ž ƒ}+|* -‡fd6d#„t|+ƒD ƒ¡ �q|*D ]}+|)|+ƒ�s@ dS �q@d
S )9aP
  Check gradients computed via small finite differences against analytical
    gradients w.r.t. tensors in :attr:`inputs` that are of floating point or complex type
    and with ``requires_grad=True``.

    The check between numerical and analytical gradients uses :func:`~torch.allclose`.

    For complex functions, no notion of Jacobian exists. Gradcheck verifies if the numerical and
    analytical values of Wirtinger and Conjugate Wirtinger derivative are consistent. The gradient
    computation is done under the assumption that the overall function has a real valued output.
    For functions with complex output, gradcheck compares the numerical and analytical gradients
    for two values of :attr:`grad_output`: 1 and 1j. For more details, check out
    :ref:`complex_autograd-doc`.

    .. note::
        The default values are designed for :attr:`input` of double precision.
        This check will likely fail if :attr:`input` is of less precision, e.g.,
        ``FloatTensor``.

    .. warning::
       If any checked tensor in :attr:`input` has overlapping memory, i.e.,
       different indices pointing to the same memory address (e.g., from
       :func:`torch.expand`), this check will likely fail because the numerical
       gradients computed by point perturbation at such indices will change
       values at all other indices that share the same memory address.

    Args:
        func (function): a Python function that takes Tensor inputs and returns
            a Tensor or a tuple of Tensors
        inputs (tuple of Tensor or Tensor): inputs to the function
        eps (float, optional): perturbation for finite differences
        atol (float, optional): absolute tolerance
        rtol (float, optional): relative tolerance
        raise_exception (bool, optional): indicating whether to raise an exception if
            the check fails. The exception gives more information about the
            exact nature of the failure. This is helpful when debugging gradchecks.
        check_sparse_nnz (bool, optional): if True, gradcheck allows for SparseTensor input,
            and for any SparseTensor at input, gradcheck will perform check at nnz positions only.
        nondet_tol (float, optional): tolerance for non-determinism. When running
            identical inputs through the differentiation, the results must either match
            exactly (default, 0.0) or be within this tolerance.
        check_undefined_grad (bool, options): if True, check if undefined output grads
            are supported and treated as zeros

    Returns:
        True if all differences satisfy allclose condition
    c                    s   ˆ rt | ƒ‚dS )NF)ÚRuntimeError)Úmsg)r‚   r   r   Ú	fail_test  s    zgradcheck.<locals>.fail_testc                 s   s    | ]}t |tjƒr|jV  qd S r   )r   r   r   rW   )r   rX   r   r   r   r    %  r   zgradcheck.<locals>.<genexpr>zTgradcheck expects all tensor inputs are dense when check_sparse_nnz is set to False.Fz¿The {}th input requires gradient and is not a double precision floating point or complex. This check will likely fail if all the inputs are not of double precision floating point or complex. c                 s   s"   | ]\}}|d kp|dkV  qdS )r   rE   Nr   )r   ÚstÚszr   r   r   r    6  r   zçThe {}th input has a dimension with stride 0. gradcheck only supports inputs that are non-overlapping to be able to compute the numerical gradients correctly. You should call .contiguous on the input before passing it to gradcheck.Tzngradcheck expects at least one input tensor to require gradient, but none of the them have requires_grad=True.c                    s   t ˆ | Ž ƒˆ S r   ©rw   ©r)   ©r~   rL   r   r   r2   H  s    zgradcheck.<locals>.fn)r<   r   z3Numerical gradient for function expected to be zeroc                    s   t ˆ | Ž ƒˆ S r   r‹   rŒ   r�   r   r   r2   T  s    )ro   r0   )ro   rC   )r<   rC   zGradient has dtype mismatchzIGradient (calculated using complex valued grad output) has dtype mismatchz&Analytical gradient has incorrect sizezTAnalytical gradient (calculated using complex valued grad output) has incorrect sizeÚ c                    s,   t  | |ˆˆ ¡s(ˆ|dˆ||| f  ƒS d S )NzUJacobian mismatch for output %d with respect to input %d,
numerical:%s
analytical:%s
)r   Zallclose)ÚaÚnÚjÚ	error_str)r€   rˆ   rL   r�   r   r   Ú checkIfNumericalAnalyticAreCloseq  s    
ÿz3gradcheck.<locals>.checkIfNumericalAnalyticAreClosez8Gradients failed to compare equal for grad output = 1j. z7Gradients failed to compare equal for grad output = 1. c                    s   d|  d  ˆ¡ }ˆ |ƒS )NZBackwarda   is not reentrant, i.e., running backward with same                         input and grad_output multiple times gives different values,                         although analytical gradient matches numerical gradient.                         The tolerance for nondeterminism was {}.)Úformat)r’   Ú	error_msg)rˆ   ro   r   r   Únot_reentrant_error‰  s    
ýz&gradcheck.<locals>.not_reentrant_errorz. (calculated using complex valued grad output)c                 S   s   g | ]
}|j ‘qS r   rx   ry   r   r   r   rQ   ˜  r   zgradcheck.<locals>.<listcomp>z(no Tensors requiring grad found in inputc                 S   s   g | ]}t j|t jd �‘qS ©re   ©r   rg   rh   ry   r   r   r   rQ   �  r   ©rf   Nzgrad is incorrect layout (z is not ú)z3grad is sparse tensor, but has incorrect sparse_dimz2grad is sparse tensor, but has incorrect dense_dimz&backward not multiplied by grad_outputzgrad is incorrect typezgrad is incorrect sizec                   S   s   t  d¡ d S )Na   Backwards compatibility: New undefined gradient support checking feature is enabled by default, but it may break existing callers of this function. If this is true for you, you can call this function with "check_undefined_grad=False" to disable the feature)ÚwarningsÚwarnr   r   r   r   Úwarn_bc_breaking´  s    ÿz#gradcheck.<locals>.warn_bc_breakingc                    sˆ   dd„ | D ƒ}zt jj| ˆ |dd�}W n  tyF   ˆƒ  ˆdƒ Y S 0 t|ˆ ƒD ]0\}}|d urR| d¡ ¡ sRˆƒ  ˆdƒ  S qRdS )Nc                 S   s   g | ]}t j|t jd �‘qS r—   r˜   ry   r   r   r   rQ   ¼  r   zCgradcheck.<locals>.check_undefined_grad_support.<locals>.<listcomp>Tr™   z™Expected backward function to handle undefined output grads. Please look at "Notes about undefined output gradients" in "tools/autograd/derivatives.yaml"r   zºExpected all input grads to be undefined or zero when all output grads are undefined or zero. Please look at "Notes about undefined output gradients" in "tools/autograd/derivatives.yaml")r   rj   r   r†   rV   ÚeqÚall)Úoutput_to_checkZgrads_outputrt   ÚgirL   )rp   rˆ   r�   r   r   Úcheck_undefined_grad_support»  s&    ý
ÿ
ÿ
z/gradcheck.<locals>.check_undefined_grad_supportc                 S   s   g | ]}t jj ¡ |ƒ‘qS r   ©r   Z_CZ
_functionsZUndefinedGradry   r   r   r   rQ   Ó  r   rE   c                    s,   g | ]$\}}|ˆ kr$t jj ¡ |ƒn|‘qS r   r£   )r   r=   rz   )Úundef_grad_idxr   r   rQ   Ù  s   ÿ)rŽ   )rŽ   ).rw   Úanyr_   r   r#   r   r   Úfloat64Z
complex128r›   rœ   rW   rY   r   r]   rŸ   rV   rK   rI   r†   Zretain_gradr^   r{   rc   Úner\   ru   r"   r,   rU   r&   rj   r   r   r   r$   r%   Z
sparse_cooZ
sparse_dimZ	dense_dimr`   rž   ZdevicerF   rH   Úappend),r~   r   r<   r€   r�   r‚   rƒ   ro   r„   r…   Útupled_inputsZany_input_requiring_gradr=   ÚinpÚcontentZfunc_outrn   rz   r2   Z	numericalr�   Z
analyticalrq   rr   rs   Zout_is_complexZanalytical_with_imag_grad_outZreentrant_with_imag_grad_outZ%correct_grad_sizes_with_imag_grad_outZ%correct_grad_types_with_imag_grad_outZnumerical_with_imag_grad_outr“   Zinp_tensorsr‘   r�   Za_with_imag_grad_outZn_with_imag_grad_outr–   rt   r¡   Zdir¢   Zoutputs_to_checkr    r   )
r€   rp   rˆ   r~   rL   ro   r‚   r�   r¤   r�   r   Ú	gradcheckå   sì    :ÿ ÿ
ÿþþ

ÿ
ÿ

þ
(*þ

r¬   )r~   r   Úgrad_outputsr<   r€   r�   Úgen_non_contig_grad_outputsr‚   ro   r„   r…   r+   c                    s|   t |ƒ}|du r@‡fdd„‰t ˆ |Ž ƒ}t‡fdd„|D ƒƒ}nt |ƒ}t|ƒ‰‡ ‡fdd„}t||| ||||||	|
d�	S )	ak
  Check gradients of gradients computed via small finite differences
    against analytical gradients w.r.t. tensors in :attr:`inputs` and
    :attr:`grad_outputs` that are of floating point or complex type and with
    ``requires_grad=True``.

    This function checks that backpropagating through the gradients computed
    to the given :attr:`grad_outputs` are correct.

    The check between numerical and analytical gradients uses :func:`~torch.allclose`.

    .. note::
        The default values are designed for :attr:`input` and
        :attr:`grad_outputs` of double precision. This check will likely fail if
        they are of less precision, e.g., ``FloatTensor``.

    .. warning::
       If any checked tensor in :attr:`input` and :attr:`grad_outputs` has
       overlapping memory, i.e., different indices pointing to the same memory
       address (e.g., from :func:`torch.expand`), this check will likely fail
       because the numerical gradients computed by point perturbation at such
       indices will change values at all other indices that share the same
       memory address.

    Args:
        func (function): a Python function that takes Tensor inputs and returns
            a Tensor or a tuple of Tensors
        inputs (tuple of Tensor or Tensor): inputs to the function
        grad_outputs (tuple of Tensor or Tensor, optional): The gradients with
            respect to the function's outputs.
        eps (float, optional): perturbation for finite differences
        atol (float, optional): absolute tolerance
        rtol (float, optional): relative tolerance
        gen_non_contig_grad_outputs (bool, optional): if :attr:`grad_outputs` is
            ``None`` and :attr:`gen_non_contig_grad_outputs` is ``True``, the
            randomly generated gradient outputs are made to be noncontiguous
        raise_exception (bool, optional): indicating whether to raise an exception if
            the check fails. The exception gives more information about the
            exact nature of the failure. This is helpful when debugging gradchecks.
        nondet_tol (float, optional): tolerance for non-determinism. When running
            identical inputs through the differentiation, the results must either match
            exactly (default, 0.0) or be within this tolerance. Note that a small amount
            of nondeterminism in the gradient will lead to larger inaccuracies in
            the second derivative.
        check_undefined_grad (bool, options): if True, check if undefined output grads
            are supported and treated as zeros

    Returns:
        True if all differences satisfy allclose condition
    Nc                    sB   t jj|  ¡ s|  ¡ r| n|  ¡ t jd�}ˆ r:t j |¡}| ¡ S )Nre   )	r   ZtestingÚ
randn_liker!   r"   Údoublerh   Zmake_non_contiguousZrequires_grad_)r   Úy)r®   r   r   r¯   '  s    ÿz!gradgradcheck.<locals>.randn_likec                 3   s   | ]}ˆ |ƒV  qd S r   r   ©r   r   )r¯   r   r   r    .  r   z gradgradcheck.<locals>.<genexpr>c                     sR   | d ˆ … }| ˆ d … }t ˆ |Ž ƒ}tdd„ |D ƒƒ}tjj|||dd�}|S )Nc                 s   s$   | ]}t |tjƒr|jr|V  qd S r   )r   r   r   r#   r²   r   r   r   r    8  r   z2gradgradcheck.<locals>.new_func.<locals>.<genexpr>T)Zcreate_graph)r{   rv   r   rj   r   )ÚargsZ
input_argsr­   ÚoutputsZgrad_inputs)r~   Únum_outputsr   r   Únew_func4  s    zgradgradcheck.<locals>.new_func)ro   r„   r…   )rw   rv   rF   r¬   )r~   r   r­   r<   r€   r�   r®   r‚   ro   r„   r…   r©   r´   Ztupled_grad_outputsr¶   r   )r~   r®   rµ   r¯   r   Úgradgradcheckä  s    >þr·   )F)Nr.   r/   )rd   r/   )r|   r}   r.   TFrd   TF)	Nr|   r}   r.   FTrd   TF)r   Ztorch.typesr   Z
torch._sixr   r   Ztorch.testingZtorch.overridesr   Ú	itertoolsr   r›   Útypingr   r   r	   r
   r   r   r   r   Úboolr,   rc   ru   rw   r{   Úfloatr¬   r·   r   r   r   r   Ú<module>   sx   
*

t
,	        öõ           õ
ô