a
    OSic                     @   s   d dl Z d dlmZmZ ddlmZ d dlmZ dd Z	d,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d0d!d"Zd1d$d%Zd2d&d'Zd3d(d)Zd4d*d+ZdS )5    N)TupleList   )
forward_ad)_vmapc                 C   s*   t | tr| S t | tr t| S | fS d S N)
isinstancetuplelist)x r   U/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/autograd/functional.py_as_tuple_nocheck   s
    

r   c              	   C   s   |d u r|d u rt | S d}t| ts0| f} d}t| D ]J\}}t|tjs8|rjtd|||t|q8td|||t|q8|| 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 {}.)	r   r   r	   	enumeratetorchTensor	TypeErrorformattype)inparg_namefn_nameZis_inp_tupleielr   r   r   	_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   r   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 r   )requires_grad	is_sparseappendview_asclonedetachrequires_grad_r	   )inputscreate_graph
need_graphr    r   r   r   r   _grad_preprocess7   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   S   r   z$_grad_postprocess.<locals>.<genexpr>c                 3   s   | ]}t | V  qd S r   )_grad_postprocessr-   r*   r   r   r   W   r   )r   r   r   r	   )r)   r*   r   r/   r   r.   N   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_vY   s    
r8   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rt d	|q t d
|q d S )N)outputsgrad_inputsjacobianhessianz*Invalid input_type to _check_requires_gradhThe output of the user-provided function is independent of input {}. This is not allowed in strict mode.r<   zThe 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.r;   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).r:   zThe gradient with respect to input {} is independent of the inputs of the user-provided function. This is not allowed in strict mode.zOutput {} 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.)r1   r   r   r"   )r)   
input_typestrictr   r   r   r   r   _check_requires_gradk   s2    r@   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rdt| S tjj|||d|||dS d S )Nr   r   T)allow_unusedr*   retain_graphis_grads_batched)r   r	   r   r2   r"   r   autogradgrad)
r9   r)   grad_outputsr*   rB   rC   Znew_outputsZnew_grad_outputsoutgrad_outr   r   r   _autograd_grad   s"    
rI   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rt d|nt d	|t|| }n4|r|r|jsd
|vrt d|nt d|||f7 }q$|S )N)back
back_trickdouble_backdouble_back_trickz-Invalid stage argument '{}' to _fill_in_zerosrJ   r=   rK   zThe 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.rL   zjThe jacobian of the user-provided function is independent of input {}. This is not allowed in strict mode.zThe 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.doubleThe jacobian of the user-provided function is independent of input {}. This is not allowed in strict mode when create_graph=True.zThe hessian of the user-provided function is independent of input {}. This is not allowed in strict mode when create_graph=True.)r1   r   r	   r   r   
zeros_liker"   )gradsrefsr?   r*   stager    r   Zgrads_ir   r   r   _fill_in_zeros   s@    rT   c                 C   sH  t   t|dd\}}t||dd}| | }t|dd\}}t|d|d |durt|d	d\}}t||d
d}t||| n$t|dks|d  dkrtdW d   n1 s0    Y  |rd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 functionr9   r?   Nr4   Fr   r   zjThe vector v can only be None if the user-provided function returns a single Tensor with a single element.r/   rJ   )r   enable_gradr   r,   r@   r8   r   nelementr1   is_grad_enabledset_grad_enabledrI   rT   r.   r!   )funcr)   r4   r*   r?   is_inputs_tupler9   is_outputs_tuple_rY   grad_resrU   r   r   r   rU      s&    ;
&0

rU   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rtd
| | }t|dd\}}t|d|d t	dd |D }	t
|||	dd}
t|
d|d W d   n1 s0    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.

    Note:
        ``autograd.functional.jvp`` computes the jvp by using the backward of
        the backward (sometimes called the double backwards trick). This is not
        the most performant way of computing the jvp. Please consider using
        `functorch's jvp <https://github.com/pytorch/functorch#jvp>`_
        or the :ref:`low-level forward-mode AD API <forward-mode-ad>` instead.

    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.]))

    r)   jvpTrV   Nr4   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.rW   r9   rX   c                 s   s   | ]}t j|d dV  qdS T)r"   Nr   rP   )r   rG   r   r   r   r   y  r   zjvp.<locals>.<genexpr>r/   r:   rK   )r   rY   r   r,   r8   r   rZ   r1   r@   r	   rI   rT   r.   r!   )r]   r)   r4   r*   r?   r^   r`   r9   r_   rF   r:   ra   rb   r   r   r   rb   (  s0    =
,
2

rb   .)tensorstensor_numelsreturnc                    s|   t | t |ksJ t | dks$J t| t fddt| |D }d}t||D ] \}}||d ||8 }qV|S )Nr   c                 3   s   | ]\}}|  |V  qd S r   )	new_zeros)r   tensorZtensor_numelZtotal_numelr   r   r     s   z0_construct_standard_basis_for.<locals>.<genexpr>r   )r   sumr	   r2   diagonalfill_)rf   rg   chunksZdiag_start_idxchunknumelr   rk   r   _construct_standard_basis_for  s    
rr   c                    s   |rt dtdd\}g |rtdd D }t|} fdd}t||}\}	}
g }t||
D ]p\}}g }t|j|dd	D ]D\}}|jg td
|j	dR  
tg |j|j}|| q|| qrt||	|fS tdd S )Nztorch.autograd.functional.jacobian: `strict=True` and `strategy="forward-mode"` are not supported together (yet). Please either set `strict=False` or `strategy="reverse-mode"`.r)   r;   c                 s   s   | ]}|  V  qd S r   rq   )r   inputr   r   r   r     r   z_jacfwd.<locals>.<genexpr>c           	         s   t   tdd t| D }t | d\}}| g }g }|D ]@}t |\}}|| |d urz|| qJ|t| qJ| t|W  d    S 1 s0    Y  d S )Nc                 s   s$   | ]\}}t |||V  qd S r   )fwAD	make_dualr%   )r   rt   tangentr   r   r   r     s   z'_jacfwd.<locals>.jvp.<locals>.<genexpr>r9   )	ru   
dual_levelr	   r2   r   r$   unpack_dualr   rP   )	tangentsdual_inputsZ_is_outputs_tupledual_outputsZjvZprimal_outsZdual_outprimalrw   r]   r)   Zoutput_infor   r   rb     s     



z_jacfwd.<locals>.jvpr   dimr   zlComputing Jacobian using forward-AD or forward-over-reverse Hessian isonly implemented for `vectorize=True`.)r1   r   r	   rr   r   r2   splitpermuterangendimreshapeshaper$   r!   NotImplementedError)r]   r)   r?   	vectorizer^   Zinput_numelsrz   rb   Zoutputs_before_splitr_   r9   jacobian_input_outputjacZoutput_iZjacobian_output_i_outputZinput_jjacobian_input_i_output_jr   r~   r   _jacfwd  s*    
r   reverse-modec              	      s  |dv sJ d|dkr2 r$t dt| ||S t h tdd\}t dd|  }t|d	d\}}t|d
|d |rp|rtdtdd |D t	|}	tdd |D  fdd}
|
|	}g }t
|D ]R\}}g }t
|jdd|D ]&\}}||j|j }|| q
|| qt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ܐq|tfddt|D f7 }q~t| }t|||fW  d   S 1 s0    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 consider using
            `functorch's jacrev or jacfwd <https://github.com/pytorch/functorch#what-are-the-transforms>`_
            instead if you are looking for something less experimental and more performant.
            When computing the jacobian, usually we invoke
            ``autograd.grad`` once per row of the jacobian. If this flag is
            ``True``, we perform only a single ``autograd.grad`` call with
            ``batched_grad=True`` which uses the vmap prototype feature.
            Though this should lead to performance improvements in many cases,
            because this feature is still experimental, there may be performance
            cliffs. See :func:`torch.autograd.grad`'s ``batched_grad`` parameter for
            more information.
        strategy (str, optional): Set to ``"forward-mode"`` or ``"reverse-mode"`` to
            determine whether the Jacobian will be computed with forward or reverse
            mode AD. Currently, ``"forward-mode"`` requires ``vectorized=True``.
            Defaults to ``"reverse-mode"``. If ``func`` has more outputs than
            inputs, ``"forward-mode"`` tends to be more performant. Otherwise,
            prefer to use ``"reverse-mode"``.

    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. If strategy is ``forward-mode``, the dtype will be
        that of the output; otherwise, the 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.]]))
    forward-moder   zExpected strategy to be either "forward-mode" or "reverse-mode". Hint: If your function has more outputs than inputs, "forward-mode" tends to be more performant. Otherwise, prefer to use "reverse-mode".r   ztorch.autograd.functional.jacobian: `create_graph=True` and `strategy="forward-mode"` are not supported together (yet). Please either set `create_graph=False` or `strategy="reverse-mode"`.r)   r;   TrV   rW   r9   rX   ztorch.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   rs   r   outputr   r   r   r   t  r   zjacobian.<locals>.<genexpr>c                 s   s   | ]}| d V  qdS )N)r   r   r   r   r   r   v  r   c                    sb   t t|  dd}t|D ]:\}}|d ur0qt| tf| j ||< qt|S )NT)r*   rC   )	r
   rI   r   r   rP   expandrl   r   r	   )grad_outputvjel_idxvj_el)r*   flat_outputsr)   output_numelsr   r   rU   y  s    *zjacobian.<locals>.vjpr   r   Nc                 s   s   | ]
}g V  qd S r   r   )r   r`   r   r   r   r     r   r   )rB   r*   rO   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   r   N)r   stackviewr3   )r   r   jac_i_el)r)   rG   r   r   r     s   
)r   r   r   rY   r   r,   r@   r1   r	   rr   r2   r   r   r   r$   r.   r!   r   r   r   rZ   rI   r   r"   r   rP   )r]   r)   r*   r?   r   strategyr^   r9   r_   rF   rU   Zjacobians_of_flat_outputr   r   Zinput_iZjacobian_input_i_outputZoutput_jr   Zjacobian_output_inputr;   r   Zjac_ijr   r   r   r   Zinp_elmsgr   )r*   r   r)   rG   r   r   r;     sx    J
-



r;   c           	         s`   t |dd\}}dv s J dfdd  fdd}t||||d	}t|||fS )
aw  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 consider using
            `functorch <https://github.com/pytorch/functorch#what-are-the-transforms>`_
            instead if you are looking for something less experimental and more performant.
            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``.
        outer_jacobian_strategy (str, optional): The Hessian is computed by
            computing the Jacobian of a Jacobian. The inner Jacobian is always
            computed in reverse-mode AD. Setting strategy to ``"forward-mode"``
            or ``"reverse-mode"`` determines whether the outer Jacobian will be
            computed with forward or reverse mode AD. Currently, computing the outer
            Jacobian in ``"forward-mode"`` requires ``vectorized=True``. Defaults
            to ``"reverse-mode"``.

    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)   r<   r   z@Expected strategy to be either "forward-mode" or "reverse-mode".c                     sZ    |  }t |dd\}}t|dd |s6t|tjs>td| dkrRtd| S )NrW   r<   r9   rX   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   r@   r   r   r   r1   rZ   squeeze)r   rG   Zis_out_tupleZt_out)r]   r?   r   r   ensure_single_output_function  s    z.hessian.<locals>.ensure_single_output_functionc                     s:   dkrt dd | D } t | dd}t|dd |S )Nr   c                 s   s   | ]}| d V  qdS )TN)r(   )r   tr   r   r   r   #  r   z,hessian.<locals>.jac_func.<locals>.<genexpr>Tr/   r;   rX   )r	   r;   r@   )r   r   )r   outer_jacobian_strategyr?   r   r   jac_func  s
    zhessian.<locals>.jac_func)r*   r?   r   r   )r   r;   r!   )	r]   r)   r*   r?   r   r   r^   r   r    r   )r   r]   r   r?   r   r<     s    V
	r<   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rtd
| | }t|dd\}}t|d|d |st	|d	 t j
std|d	  dkrt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)   vhpTrV   Nr4   Fr   r   rc   rW   r9   rX   z7The function given to vhp should return a single TensorzPThe Tensor returned by the function given to vhp should contain a single elementr/   r;   rL   )r   rY   r   r,   r8   r   rZ   r1   r@   r   r   rI   r[   r\   rT   r.   r!   )r]   r)   r4   r*   r?   r^   r`   r9   r_   r   rY   ra   r   r   r   r   r   -  s2    7
.0

r   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rtd
| | }t|dd\}}t|d|d |st	|d	 t j
std|d	  dkrt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 s0    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)   hvpTrV   Nr4   Fr   r   rc   rW   r9   rX   z7The function given to hvp should return a single TensorzPThe Tensor returned by the function given to hvp should contain a single elementr/   r;   c                 s   s   | ]}t j|d dV  qdS rd   re   r-   r   r   r   r     r   zhvp.<locals>.<genexpr>r<   rM   )r   rY   r   r,   r8   r   rZ   r1   r@   r   r   rI   r	   r[   r\   rT   r.   r!   )r]   r)   r4   r*   r?   r^   r`   r9   r_   r   Zgrad_jacrL   rY   ra   r   r   r   r   r     s8    @.0

r   )NN)NFNF)NFF)NFF)FF)FFFr   )FFFr   )NFF)NFF)r   typingr   r   r0   r   ru   torch._vmap_internalsr   r   r   r!   r,   r.   r8   r@   rI   rT   rU   rb   r   intrr   r   r;   r<   r   r   r   r   r   r   <module>   s*   
 
,
Y
e.
9
 T
u
[