a
    –¥»a6­  ã                   @   sÔ   d dl Z d dlmZmZ d dlmZ dd„ Zdd„ Zdd	„ Zd
d„ Z	dd„ Z
dd„ Zd%dd„Zdd„ Zd&dd„Zd'dd„Zee jdf eedf ee jdf dœdd„Zd(dd„Zd)dd „Zd*d!d"„Zd+d#d$„ZdS ),é    N)ÚTupleÚList)Ú_vmapc              	   C   st   d}t | tƒs| f} d}t| ƒD ]J\}}t |tjƒs |rRtd |||t|ƒ¡ƒ‚q td |||t|ƒ¡ƒ‚q || fS )NTFzgThe {} given to {} must be either a Tensor or a tuple of Tensors but the value at index {} has type {}.z^The {} given to {} must be either a Tensor or a tuple of Tensors but the given {} has type {}.)Ú
isinstanceÚtupleÚ	enumerateÚtorchÚTensorÚ	TypeErrorÚformatÚtype)ÚinpZarg_nameÚfn_nameZis_inp_tupleÚiÚel© r   úS/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/autograd/functional.pyÚ	_as_tuple   s    
ÿÿr   c                 C   sV   t |tƒrFt|ƒdksJ ‚|d s4tdd„ | D ƒƒ} |d sR| d } n|sR| d } | S )Né   é   c                 s   s   | ]}|d  V  qdS )r   Nr   )Ú.0r   r   r   r   Ú	<genexpr>#   ó    z%_tuple_postprocess.<locals>.<genexpr>r   )r   r   Úlen)ÚresZ	to_unpackr   r   r   Ú_tuple_postprocess   s    

r   c                 C   s\   g }| D ]J}|r>|j r>|js.| | |¡¡ qR| | ¡ ¡ q| | ¡  |¡¡ qt|ƒS ©N)Úrequires_gradZ	is_sparseÚappendZview_asÚcloneÚdetachZrequires_grad_r   )ÚinputsÚcreate_graphÚ
need_graphr   r   r   r   r   Ú_grad_preprocess+   s    
r$   c                    sF   t | d tjƒr,ˆ s&tdd„ | D ƒƒS | S nt‡ fdd„| D ƒƒS d S )Nr   c                 s   s   | ]}|  ¡ V  qd S r   )r    ©r   r   r   r   r   r   G   r   z$_grad_postprocess.<locals>.<genexpr>c                 3   s   | ]}t |ˆ ƒV  qd S r   )Ú_grad_postprocessr%   ©r"   r   r   r   K   r   )r   r   r	   r   )r!   r"   r   r'   r   r&   B   s
    r&   c                 C   s’   t |ƒt | ƒkr6|r.td t |ƒt | ƒ¡ƒ‚ntdƒ‚tt| |ƒƒD ]H\}\}}| ¡ | ¡ krDd}|rrd |¡}td || ¡ | ¡ ¡ƒ‚qDd S )Nz8v is a tuple of invalid length: should be {} but got {}.z+The given v should contain a single Tensor.Ú zEntry {} in z.{}v has invalid size: should be {} but got {}.)r   ÚRuntimeErrorr   r   ÚzipÚsize)ÚvÚotherZis_other_tupleÚidxZel_vZel_otherÚprependr   r   r   Ú_validate_vM   s    
ÿr0   c                 C   s    |sd S |dvrt dƒ‚t| ƒD ]z\}}|d u r>t d |¡ƒ‚|js |dkr\t d |¡ƒ‚q |dkrtt d |¡ƒ‚q |dkrŒt d	 |¡ƒ‚q t d
 |¡ƒ‚q d S )N)ÚoutputsÚgrad_inputsÚjacobianÚhessianz*Invalid input_type to _check_requires_gradúhThe output of the user-provided function is independent of input {}. This is not allowed in strict mode.r4   zíThe hessian of the user-provided function with respect to input {} is independent of the input. This is not allowed in strict mode. You should ensure that your function is thrice differentiable and that the hessian depends on the inputs.r3   aP  While computing the hessian, found that the jacobian of the user-provided function with respect to input {} is independent of the input. This is not allowed in strict mode. You should ensure that your function is twice differentiable and that the jacobian depends on the inputs (this would be violated by a linear function for example).r2   z…The gradient with respect to input {} is independent of the inputs of the user-provided function. This is not allowed in strict mode.z§Output {} of the user-provided function does not require gradients. The outputs must be computed in a differentiable manner from the input when running in strict mode.)r)   r   r   r   )r!   Z
input_typeÚstrictr   r   r   r   r   Ú_check_requires_grad_   s2    ÿýüÿþr7   Fc           	      C   sº   t | tƒsJ ‚|d u r"dt| ƒ }t |tƒs0J ‚t| ƒt|ƒksDJ ‚tƒ }tƒ }t| |ƒD ]*\}}|d urZ|jrZ||f7 }||f7 }qZt|ƒdkrždt|ƒ S tjj|||d||d�S d S )Nr   r   T)Zallow_unusedr"   Úretain_graph)r   r   r   r*   r   r   ZautogradZgrad)	r1   r!   Úgrad_outputsr"   r8   Znew_outputsZnew_grad_outputsÚoutZgrad_outr   r   r   Ú_autograd_grad   s     
ÿr;   c                 C   sâ   |dvrt d |¡ƒ‚tƒ }t| ƒD ]¸\}}|d u rž|rŽ|dkrPt d |¡ƒ‚n>|dkrht d |¡ƒ‚n&|dkr€t d |¡ƒ‚nt d	 |¡ƒ‚t || ¡}n4|rÒ|rÒ|jsÒd
|vrÄt d |¡ƒ‚nt d |¡ƒ‚||f7 }q$|S )N)ÚbackÚ
back_trickÚdouble_backÚdouble_back_trickz-Invalid stage argument '{}' to _fill_in_zerosr<   r5   r=   zÁThe gradient with respect to the input is independent of entry {} in the grad_outputs when using the double backward trick to compute forward mode gradients. This is not allowed in strict mode.r>   zjThe jacobian of the user-provided function is independent of input {}. This is not allowed in strict mode.zÍThe hessian of the user-provided function is independent of entry {} in the grad_jacobian. This is not allowed in strict mode as it prevents from using the double backward trick to replace forward mode AD.Údoubleú�The jacobian of the user-provided function is independent of input {}. This is not allowed in strict mode when create_graph=True.z€The hessian of the user-provided function is independent of input {}. This is not allowed in strict mode when create_graph=True.)r)   r   r   r   r   Ú
zeros_liker   )ZgradsÚrefsr6   r"   Zstager   r   Zgrads_ir   r   r   Ú_fill_in_zeros–   s@    ÿþÿýÿÿrD   c                 C   sH  t  ¡ �¬ t|ddƒ\}}t||dd�}| |Ž }t|ddƒ\}}t|d|d� |dur‚t|d	dƒ\}}t||d
d�}t|||ƒ n$t|ƒdksž|d  ¡ dkr¦tdƒ‚W d  ƒ n1 sº0    Y  |rÌdnt  	¡ }	t  
|	¡�0 t||||d�}
t|
|||dƒ}W d  ƒ n1 �s0    Y  t||ƒ}t||ƒ}t||ƒt||ƒfS )av
  Function that computes the dot product between a vector ``v`` and the
    Jacobian of the given function at the point given by the inputs.

    Args:
        func (function): a Python function that takes Tensor inputs and returns
            a tuple of Tensors or a Tensor.
        inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
        v (tuple of Tensors or Tensor): The vector for which the vector
            Jacobian product is computed.  Must be the same size as the output
            of ``func``. This argument is optional when the output of ``func``
            contains a single element and (if it is not provided) will be set
            as a Tensor containing a single ``1``.
        create_graph (bool, optional): If ``True``, both the output and result
            will be computed in a differentiable way. Note that when ``strict``
            is ``False``, the result can not require gradients or be
            disconnected from the inputs.  Defaults to ``False``.
        strict (bool, optional): If ``True``, an error will be raised when we
            detect that there exists an input such that all the outputs are
            independent of it. If ``False``, we return a Tensor of zeros as the
            vjp for said inputs, which is the expected mathematical value.
            Defaults to ``False``.

    Returns:
        output (tuple): tuple with:
            func_output (tuple of Tensors or Tensor): output of ``func(inputs)``

            vjp (tuple of Tensors or Tensor): result of the dot product with
            the same shape as the inputs.

    Example:

        >>> def exp_reducer(x):
        ...   return x.exp().sum(dim=1)
        >>> inputs = torch.rand(4, 4)
        >>> v = torch.ones(4)
        >>> vjp(exp_reducer, inputs, v)
        (tensor([5.7817, 7.2458, 5.7830, 6.7782]),
         tensor([[1.4458, 1.3962, 1.3042, 1.6354],
                [2.1288, 1.0652, 1.5483, 2.5035],
                [2.2046, 1.1292, 1.1432, 1.3059],
                [1.3225, 1.6652, 1.7753, 2.0152]]))

        >>> vjp(exp_reducer, inputs, v, create_graph=True)
        (tensor([5.7817, 7.2458, 5.7830, 6.7782], grad_fn=<SumBackward1>),
         tensor([[1.4458, 1.3962, 1.3042, 1.6354],
                [2.1288, 1.0652, 1.5483, 2.5035],
                [2.2046, 1.1292, 1.1432, 1.3059],
                [1.3225, 1.6652, 1.7753, 2.0152]], grad_fn=<MulBackward0>))

        >>> def adder(x, y):
        ...   return 2 * x + 3 * y
        >>> inputs = (torch.rand(2), torch.rand(2))
        >>> v = torch.ones(2)
        >>> vjp(adder, inputs, v)
        (tensor([2.4225, 2.3340]),
         (tensor([2., 2.]), tensor([3., 3.])))
    r!   ÚvjpT©r"   r#   ú%outputs of the user-provided functionr1   ©r6   Nr,   Fr   r   zjThe vector v can only be None if the user-provided function returns a single Tensor with a single element.r'   r<   )r   Úenable_gradr   r$   r7   r0   r   Únelementr)   Úis_grad_enabledÚset_grad_enabledr;   rD   r&   r   )Úfuncr!   r,   r"   r6   Úis_inputs_tupler1   Úis_outputs_tupleÚ_rI   Úgrad_resrE   r   r   r   rE   Â   s&    ;
&0

rE   c                 C   sŽ  t  ¡ �Ü t|ddƒ\}}t||dd�}|dur\t|ddƒ\}}t||dd�}t|||ƒ n$t|ƒdksx|d	  ¡ dkr€td
ƒ‚| |Ž }t|ddƒ\}}t|d|d� t	dd„ |D ƒƒ}	t
|||	dd�}
t|
d|d� W d  ƒ n1 sê0    Y  |�rFt  ¡ �0 t
|
|	||d�}t||||dƒ}W d  ƒ n1 �s:0    Y  n t
|
|	||d�}t||||dƒ}t||ƒ}t||ƒ}t||ƒt||ƒfS )a$
  Function that computes the dot product between  the Jacobian of
    the given function at the point given by the inputs and a vector ``v``.

    Args:
        func (function): a Python function that takes Tensor inputs and returns
            a tuple of Tensors or a Tensor.
        inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
        v (tuple of Tensors or Tensor): The vector for which the Jacobian
            vector product is computed. Must be the same size as the input of
            ``func``. This argument is optional when the input to ``func``
            contains a single element and (if it is not provided) will be set
            as a Tensor containing a single ``1``.
        create_graph (bool, optional): If ``True``, both the output and result
            will be computed in a differentiable way. Note that when ``strict``
            is ``False``, the result can not require gradients or be
            disconnected from the inputs.  Defaults to ``False``.
        strict (bool, optional): If ``True``, an error will be raised when we
            detect that there exists an input such that all the outputs are
            independent of it. If ``False``, we return a Tensor of zeros as the
            jvp for said inputs, which is the expected mathematical value.
            Defaults to ``False``.

    Returns:
        output (tuple): tuple with:
            func_output (tuple of Tensors or Tensor): output of ``func(inputs)``

            jvp (tuple of Tensors or Tensor): result of the dot product with
            the same shape as the output.

    Example:

        >>> def exp_reducer(x):
        ...   return x.exp().sum(dim=1)
        >>> inputs = torch.rand(4, 4)
        >>> v = torch.ones(4, 4)
        >>> jvp(exp_reducer, inputs, v)
        (tensor([6.3090, 4.6742, 7.9114, 8.2106]),
         tensor([6.3090, 4.6742, 7.9114, 8.2106]))

        >>> jvp(exp_reducer, inputs, v, create_graph=True)
        (tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SumBackward1>),
         tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SqueezeBackward1>))

        >>> def adder(x, y):
        ...   return 2 * x + 3 * y
        >>> inputs = (torch.rand(2), torch.rand(2))
        >>> v = (torch.ones(2), torch.ones(2))
        >>> jvp(adder, inputs, v)
        (tensor([2.2399, 2.5005]),
         tensor([5., 5.]))

    Note:
        The jvp is currently computed by using the backward of the backward
        (sometimes called the double backwards trick) as we don't have support
        for forward mode AD in PyTorch at the moment.
    r!   ÚjvpTrF   Nr,   Fr   r   úrThe vector v can only be None if the input to the user-provided function is a single Tensor with a single element.rG   r1   rH   c                 s   s   | ]}t j|d d�V  qdS ©T)r   N©r   rB   )r   r:   r   r   r   r   i  r   zjvp.<locals>.<genexpr>r'   r2   r=   )r   rI   r   r$   r0   r   rJ   r)   r7   r   r;   rD   r&   r   )rM   r!   r,   r"   r6   rN   rP   r1   rO   r9   r2   rQ   rR   r   r   r   rR     s0    :
,
2

rR   .)ÚtensorsÚtensor_numelsÚreturnc                    sš   t | ƒt |ƒksJ ‚t | ƒdks$J ‚t|ƒ‰ dgt |¡jdd�d d…  ¡  ¡ ¢R }t‡ fdd„t| |ƒD ƒƒ}t||ƒD ]\}}| 	|¡ 
d¡ q||S )Nr   ©Zdiméÿÿÿÿc                 3   s   | ]\}}|  ˆ |¡V  qd S r   )Z	new_zeros)r   ÚtensorZtensor_numel©Ztotal_numelr   r   r   ”  s   ÿz0_construct_standard_basis_for.<locals>.<genexpr>r   )r   Úsumr   r[   ZcumsumÚnegZunbindr   r*   ZdiagonalZfill_)rV   rW   Zdiag_start_indicesÚchunksÚchunkZdiag_start_idxr   r\   r   Ú_construct_standard_basis_for}  s    *ÿra   c              	      sˆ  t  ¡ ��h tˆddƒ\}‰tˆˆ dd�‰| ˆŽ }t|ddƒ\}}t|d|d� |�r>|rbtdƒ‚td	d
„ |D ƒƒ}t||ƒ}	tdd
„ |D ƒƒ‰‡ ‡‡fdd„}
t|
ƒ|	ƒ}g }t	|ˆƒD ]P\}}g }t	|j
|dd�|ƒD ]$\}}| |j|j ¡}| |¡ qÚ| |¡ qºtt	|Ž ƒ}t|ˆ ƒ}t|||fƒW  d  ƒ S tƒ }t|ƒD ]þ\}‰tdd
„ ttˆƒƒD ƒƒ}tˆ ¡ ƒD ]ª}tˆ d¡| fˆdˆ d�}tt	||ˆƒƒD ]v\}\}}}|du�rô|�rèˆ �rè|j�sèd |¡}t|ƒ‚| |¡ n*|�rd ||¡}t|ƒ‚| t  |¡¡ �qª�qz|t‡‡fdd
„t|ƒD ƒƒf7 }�qLt|ˆ ƒ}t|||fƒW  d  ƒ S 1 �sz0    Y  dS )a¤  Function that computes the Jacobian of a given function.

    Args:
        func (function): a Python function that takes Tensor inputs and returns
            a tuple of Tensors or a Tensor.
        inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
        create_graph (bool, optional): If ``True``, the Jacobian will be
            computed in a differentiable manner. Note that when ``strict`` is
            ``False``, the result can not require gradients or be disconnected
            from the inputs.  Defaults to ``False``.
        strict (bool, optional): If ``True``, an error will be raised when we
            detect that there exists an input such that all the outputs are
            independent of it. If ``False``, we return a Tensor of zeros as the
            jacobian for said inputs, which is the expected mathematical value.
            Defaults to ``False``.
        vectorize (bool, optional): This feature is experimental, please use at
            your own risk. When computing the jacobian, usually we invoke
            ``autograd.grad`` once per row of the jacobian. If this flag is
            ``True``, we use the vmap prototype feature as the backend to
            vectorize calls to ``autograd.grad`` so we only invoke it once
            instead of once per row. This should lead to performance
            improvements in many use cases, however, due to this feature
            being incomplete, there may be performance cliffs. Please
            use `torch._C._debug_only_display_vmap_fallback_warnings(True)`
            to show any performance warnings and file us issues if
            warnings exist for your use case. Defaults to ``False``.

    Returns:
        Jacobian (Tensor or nested tuple of Tensors): if there is a single
        input and output, this will be a single Tensor containing the
        Jacobian for the linearized inputs and output. If one of the two is
        a tuple, then the Jacobian will be a tuple of Tensors. If both of
        them are tuples, then the Jacobian will be a tuple of tuple of
        Tensors where ``Jacobian[i][j]`` will contain the Jacobian of the
        ``i``\th output and ``j``\th input and will have as size the
        concatenation of the sizes of the corresponding output and the
        corresponding input and will have same dtype and device as the
        corresponding input.

    Example:

        >>> def exp_reducer(x):
        ...   return x.exp().sum(dim=1)
        >>> inputs = torch.rand(2, 2)
        >>> jacobian(exp_reducer, inputs)
        tensor([[[1.4917, 2.4352],
                 [0.0000, 0.0000]],
                [[0.0000, 0.0000],
                 [2.4369, 2.3799]]])

        >>> jacobian(exp_reducer, inputs, create_graph=True)
        tensor([[[1.4917, 2.4352],
                 [0.0000, 0.0000]],
                [[0.0000, 0.0000],
                 [2.4369, 2.3799]]], grad_fn=<ViewBackward>)

        >>> def exp_adder(x, y):
        ...   return 2 * x.exp() + 3 * y
        >>> inputs = (torch.rand(2), torch.rand(2))
        >>> jacobian(exp_adder, inputs)
        (tensor([[2.8052, 0.0000],
                [0.0000, 3.3963]]),
         tensor([[3., 0.],
                 [0., 3.]]))
    r!   r3   TrF   rG   r1   rH   zštorch.autograd.functional.jacobian: `strict=True` and `vectorized=True` are not supported together. Please either set `strict=False` or `vectorize=False`.c                 s   s   | ]}|  ¡ V  qd S r   )Znumel©r   Úoutputr   r   r   r     r   zjacobian.<locals>.<genexpr>c                 s   s   | ]}|  d ¡V  qdS )rZ   N)Úreshaperb   r   r   r   r     r   c                    sJ   t tˆˆ| ˆ d�ƒ}t|ƒD ]$\}}|d ur.qt ˆ| ¡||< qt|ƒS )Nr'   )Úlistr;   r   r   rB   r   )Zgrad_outputÚvjÚel_idxÚvj_el)r"   Úflat_outputsr!   r   r   rE     s    zjacobian.<locals>.vjpr   rY   Nc                 s   s   | ]
}g V  qd S r   r   )r   rP   r   r   r   r   A  r   rZ   )r8   r"   rA   zgOutput {} of the user-provided function is independent of input {}. This is not allowed in strict mode.c                 3   s6   | ].\}}t j|d d� ˆ ¡ ˆ |  ¡  ¡V  qdS )r   rY   N)r   ÚstackÚviewr+   )r   rg   Újac_i_el)r!   r:   r   r   r   V  s   ÿ
ÿ)r   rI   r   r$   r7   r)   r   ra   r   r*   Úsplitrk   Úshaper   r&   r   r   Úranger   rJ   r;   rd   r   r   rB   )rM   r!   r"   r6   Ú	vectorizerN   r1   rO   Zoutput_numelsr9   rE   Zjacobians_of_flat_outputZjacobian_input_outputÚjacZinput_iZjacobian_input_i_outputZoutput_jZjacobian_input_i_output_jZjacobian_output_inputr3   r   Zjac_iÚjrf   rg   rl   rh   Zinp_elÚmsgr   )r"   ri   r!   r:   r   r3   ›  sj    Cþ-

ÿ
þþÿ
r3   c                    sL   t |ddƒ\}}‡‡fdd„‰ ‡ ‡fdd„}t|||ˆ|d�}t|||fƒS )a¹  Function that computes the Hessian of a given scalar function.

    Args:
        func (function): a Python function that takes Tensor inputs and returns
            a Tensor with a single element.
        inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
        create_graph (bool, optional): If ``True``, the Hessian will be computed in
            a differentiable manner. Note that when ``strict`` is ``False``, the result can not
            require gradients or be disconnected from the inputs.
            Defaults to ``False``.
        strict (bool, optional): If ``True``, an error will be raised when we detect that there exists an input
            such that all the outputs are independent of it. If ``False``, we return a Tensor of zeros as the
            hessian for said inputs, which is the expected mathematical value.
            Defaults to ``False``.
        vectorize (bool, optional): This feature is experimental, please use at
            your own risk. When computing the hessian, usually we invoke
            ``autograd.grad`` once per row of the hessian. If this flag is
            ``True``, we use the vmap prototype feature as the backend to
            vectorize calls to ``autograd.grad`` so we only invoke it once
            instead of once per row. This should lead to performance
            improvements in many use cases, however, due to this feature
            being incomplete, there may be performance cliffs. Please
            use `torch._C._debug_only_display_vmap_fallback_warnings(True)`
            to show any performance warnings and file us issues if
            warnings exist for your use case. Defaults to ``False``.

    Returns:
        Hessian (Tensor or a tuple of tuple of Tensors): if there is a single input,
        this will be a single Tensor containing the Hessian for the input.
        If it is a tuple, then the Hessian will be a tuple of tuples where
        ``Hessian[i][j]`` will contain the Hessian of the ``i``\th input
        and ``j``\th input with size the sum of the size of the ``i``\th input plus
        the size of the ``j``\th input. ``Hessian[i][j]`` will have the same
        dtype and device as the corresponding ``i``\th input.

    Example:

        >>> def pow_reducer(x):
        ...   return x.pow(3).sum()
        >>> inputs = torch.rand(2, 2)
        >>> hessian(pow_reducer, inputs)
        tensor([[[[5.2265, 0.0000],
                  [0.0000, 0.0000]],
                 [[0.0000, 4.8221],
                  [0.0000, 0.0000]]],
                [[[0.0000, 0.0000],
                  [1.9456, 0.0000]],
                 [[0.0000, 0.0000],
                  [0.0000, 3.2550]]]])

        >>> hessian(pow_reducer, inputs, create_graph=True)
        tensor([[[[5.2265, 0.0000],
                  [0.0000, 0.0000]],
                 [[0.0000, 4.8221],
                  [0.0000, 0.0000]]],
                [[[0.0000, 0.0000],
                  [1.9456, 0.0000]],
                 [[0.0000, 0.0000],
                  [0.0000, 3.2550]]]], grad_fn=<ViewBackward>)


        >>> def pow_adder_reducer(x, y):
        ...   return (2 * x.pow(2) + 3 * y.pow(2)).sum()
        >>> inputs = (torch.rand(2), torch.rand(2))
        >>> hessian(pow_adder_reducer, inputs)
        ((tensor([[4., 0.],
                  [0., 4.]]),
          tensor([[0., 0.],
                  [0., 0.]])),
         (tensor([[0., 0.],
                  [0., 0.]]),
          tensor([[6., 0.],
                  [0., 6.]])))
    r!   r4   c                     sZ   ˆ | Ž }t |ddƒ\}}t|dˆd� |s6t|tjƒs>tdƒ‚| ¡ dkrRtdƒ‚| ¡ S )NrG   r4   r1   rH   z;The function given to hessian should return a single Tensorr   zTThe Tensor returned by the function given to hessian should contain a single element)r   r7   r   r   r	   r)   rJ   Zsqueeze)r   r:   Zis_out_tupleZt_out)rM   r6   r   r   Úensure_single_output_function«  s    z.hessian.<locals>.ensure_single_output_functionc                     s    t ˆ | dd�}t|dˆd� |S )NTr'   r3   rH   )r3   r7   )r   rq   )rt   r6   r   r   Újac_func¸  s    zhessian.<locals>.jac_func)r"   r6   rp   )r   r3   r   )rM   r!   r"   r6   rp   rN   ru   r   r   )rt   rM   r6   r   r4   ]  s
    Lr4   c                 C   sœ  t  ¡ �ü t|ddƒ\}}t||dd�}|dur\t|ddƒ\}}t||dd�}t|||ƒ n$t|ƒdksx|d	  ¡ dkr€td
ƒ‚| |Ž }t|ddƒ\}}t|d|d� |sºt	|d	 t j
ƒsÂtdƒ‚|d	  ¡ dkrÚtdƒ‚t||dd�}	t|	d|d� W d  ƒ n1 �s0    Y  |�r dnt  ¡ }
t  |
¡�0 t|	|||d�}t||||dƒ}W d  ƒ n1 �sj0    Y  t||ƒ}t||ƒ}t||ƒt||ƒfS )a	  Function that computes the dot product between a vector ``v`` and the
    Hessian of a given scalar function at the point given by the inputs.

    Args:
        func (function): a Python function that takes Tensor inputs and returns
            a Tensor with a single element.
        inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
        v (tuple of Tensors or Tensor): The vector for which the vector Hessian
            product is computed. Must be the same size as the input of
            ``func``. This argument is optional when ``func``'s input contains
            a single element and (if it is not provided) will be set as a
            Tensor containing a single ``1``.
        create_graph (bool, optional): If ``True``, both the output and result
            will be computed in a differentiable way. Note that when ``strict``
            is ``False``, the result can not require gradients or be
            disconnected from the inputs.
            Defaults to ``False``.
        strict (bool, optional): If ``True``, an error will be raised when we
            detect that there exists an input such that all the outputs are
            independent of it. If ``False``, we return a Tensor of zeros as the
            vhp for said inputs, which is the expected mathematical value.
            Defaults to ``False``.

    Returns:
        output (tuple): tuple with:
            func_output (tuple of Tensors or Tensor): output of ``func(inputs)``

            vhp (tuple of Tensors or Tensor): result of the dot product with the
            same shape as the inputs.

    Example:

        >>> def pow_reducer(x):
        ...   return x.pow(3).sum()
        >>> inputs = torch.rand(2, 2)
        >>> v = torch.ones(2, 2)
        >>> vhp(pow_reducer, inputs, v)
        (tensor(0.5591),
         tensor([[1.0689, 1.2431],
                 [3.0989, 4.4456]]))
        >>> vhp(pow_reducer, inputs, v, create_graph=True)
        (tensor(0.5591, grad_fn=<SumBackward0>),
         tensor([[1.0689, 1.2431],
                 [3.0989, 4.4456]], grad_fn=<MulBackward0>))
        >>> def pow_adder_reducer(x, y):
        ...   return (2 * x.pow(2) + 3 * y.pow(2)).sum()
        >>> inputs = (torch.rand(2), torch.rand(2))
        >>> v = (torch.zeros(2), torch.ones(2))
        >>> vhp(pow_adder_reducer, inputs, v)
        (tensor(4.8053),
         (tensor([0., 0.]),
          tensor([6., 6.])))
    r!   ÚvhpTrF   Nr,   Fr   r   rS   rG   r1   rH   z7The function given to vhp should return a single TensorzPThe Tensor returned by the function given to vhp should contain a single elementr'   r3   r>   )r   rI   r   r$   r0   r   rJ   r)   r7   r   r	   r;   rK   rL   rD   r&   r   )rM   r!   r,   r"   r6   rN   rP   r1   rO   rq   rI   rQ   rv   r   r   r   rv   Á  s2    7
.0

rv   c                 C   sÎ  t  ¡ ��, t|ddƒ\}}t||dd�}|dur^t|ddƒ\}}t||dd�}t|||ƒ n$t|ƒdksz|d	  ¡ dkr‚td
ƒ‚| |Ž }t|ddƒ\}}t|d|d� |s¼t	|d	 t j
ƒsÄtdƒ‚|d	  ¡ dkrÜtdƒ‚t||dd�}	t|	d|d� tdd„ |D ƒƒ}
t|	||
dd�}t|	d|d� W d  ƒ n1 �s>0    Y  |�rRdnt  ¡ }t  |¡�0 t||
||d�}t||||dƒ}W d  ƒ n1 �sœ0    Y  t||ƒ}t||ƒ}t||ƒt||ƒfS )aÑ
  Function that computes the dot product between the Hessian of a given scalar
    function and a vector ``v`` at the point given by the inputs.

    Args:
        func (function): a Python function that takes Tensor inputs and returns
            a Tensor with a single element.
        inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
        v (tuple of Tensors or Tensor): The vector for which the Hessian vector
            product is computed. Must be the same size as the input of
            ``func``. This argument is optional when ``func``'s input contains
            a single element and (if it is not provided) will be set as a
            Tensor containing a single ``1``.
        create_graph (bool, optional): If ``True``, both the output and result will be
            computed in a differentiable way. Note that when ``strict`` is
            ``False``, the result can not require gradients or be disconnected
            from the inputs.  Defaults to ``False``.
        strict (bool, optional): If ``True``, an error will be raised when we
            detect that there exists an input such that all the outputs are
            independent of it. If ``False``, we return a Tensor of zeros as the
            hvp for said inputs, which is the expected mathematical value.
            Defaults to ``False``.
    Returns:
        output (tuple): tuple with:
            func_output (tuple of Tensors or Tensor): output of ``func(inputs)``

            hvp (tuple of Tensors or Tensor): result of the dot product with
            the same shape as the inputs.

    Example:

        >>> def pow_reducer(x):
        ...   return x.pow(3).sum()
        >>> inputs = torch.rand(2, 2)
        >>> v = torch.ones(2, 2)
        >>> hvp(pow_reducer, inputs, v)
        (tensor(0.1448),
         tensor([[2.0239, 1.6456],
                 [2.4988, 1.4310]]))

        >>> hvp(pow_reducer, inputs, v, create_graph=True)
        (tensor(0.1448, grad_fn=<SumBackward0>),
         tensor([[2.0239, 1.6456],
                 [2.4988, 1.4310]], grad_fn=<MulBackward0>))


        >>> def pow_adder_reducer(x, y):
        ...   return (2 * x.pow(2) + 3 * y.pow(2)).sum()
        >>> inputs = (torch.rand(2), torch.rand(2))
        >>> v = (torch.zeros(2), torch.ones(2))
        >>> hvp(pow_adder_reducer, inputs, v)
        (tensor(2.3030),
         (tensor([0., 0.]),
          tensor([6., 6.])))

    Note:

        This function is significantly slower than `vhp` due to backward mode AD constraints.
        If your functions is twice continuously differentiable, then hvp = vhp.t(). So if you
        know that your function satisfies this condition, you should use vhp instead that is
        much faster with the current implementation.

    r!   ÚhvpTrF   Nr,   Fr   r   rS   rG   r1   rH   z7The function given to hvp should return a single TensorzPThe Tensor returned by the function given to hvp should contain a single elementr'   r3   c                 s   s   | ]}t j|d d�V  qdS rT   rU   r%   r   r   r   r   u  r   zhvp.<locals>.<genexpr>r4   r?   )r   rI   r   r$   r0   r   rJ   r)   r7   r   r	   r;   r   rK   rL   rD   r&   r   )rM   r!   r,   r"   r6   rN   rP   r1   rO   rq   Zgrad_jacr>   rI   rQ   rw   r   r   r   rw     s8    @.0

rw   )NFN)NFF)NFF)FFF)FFF)NFF)NFF)r   Útypingr   r   Ztorch._vmap_internalsr   r   r   r$   r&   r0   r7   r;   rD   rE   rR   r	   Úintra   r3   r4   rv   rw   r   r   r   r   Ú<module>   s$    
,
Y
b.
 C
d
[