
    Pg?                         d dl mZmZ d dlZd dlmZ ddlmZ g dZ	d Z
ddZd	 Zd
 Zd Zd Zd Z	 	 	 	 ddZd ZddZddZdeej*                  df   deedf   deej*                  df   fdZddZ	 	 	 	 d dZ	 	 	 	 d dZddZddZy)!    )ListTupleN)_vmap   )
forward_ad)vjpjvpjacobianhessianhvpvhpc                 b    t        | t              r| S t        | t              rt        |       S | fS N)
isinstancetuplelist)xs    `/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/autograd/functional.py_as_tuple_nocheckr      s+    !U	At	Qxt    c                 8   ||t        |       S d}t        | t              s| f} d}t        |       D ]c  \  }}t        |t        j
                        r!|r!t        d| d| d| dt        |       d	      t        d| d| d| dt        |       d	       || fS )	NTFzThe z
 given to zF must be either a Tensor or a tuple of Tensors but the value at index z
 has type .z= must be either a Tensor or a tuple of Tensors but the given )r   r   r   	enumeratetorchTensor	TypeErrortype)inparg_namefn_nameis_inp_tupleiels         r   	_as_tupler$      s     GO %%Lc5!f3 2"ell+8*Jwi 8''(cDH:Q@ 
  8*Jwi 8&Zz$r(1>  r   c                     t        |t              r3t        |      dk(  sJ |d   st        d | D              } |d   s| d   } | S |s| d   } | S )N   r   c              3   &   K   | ]	  }|d      yw)r   N ).0r#   s     r   	<genexpr>z%_tuple_postprocess.<locals>.<genexpr><   s     ,"1,s   r   )r   r   len)res	to_unpacks     r   _tuple_postprocessr.   3   sa     )U#9~"""|,,,C|a&C J a&CJr   c                 <   g }| D ]  }|rY|j                   rM|j                  s!|j                  |j                  |             >|j                  |j	                                ^|j                  |j                         j                  |              t        |      S r   )requires_grad	is_sparseappendview_asclonedetachrequires_grad_r   )inputscreate_graph
need_graphr,   r   s        r   _grad_preprocessr:   E   s~     C 
@C--==

3;;s+, 

399;'JJszz|22:>?
@ :r   c                     t        | d   t        j                        rst        d | D              S | S t        fd| D              S )Nr   c              3   <   K   | ]  }|j                           y wr   )r5   r)   r   s     r   r*   z$_grad_postprocess.<locals>.<genexpr>a   s     8#8   c              3   6   K   | ]  }t        |        y wr   )_grad_postprocess)r)   r   r8   s     r   r*   z$_grad_postprocess.<locals>.<genexpr>e   s     Lc&sL9Ls   )r   r   r   r   )r7   r8   s    `r   r@   r@   \   sA     &)U\\*8888MLVLLLr   c           	         t        |      t        |       k7  r1|r$t        dt        |       dt        |        d      t        d      t        t        | |            D ]c  \  }\  }}|j	                         |j	                         k7  s+d}|rd| d}t        | d|j	                          d|j	                          d       y )	Nz*v is a tuple of invalid length: should be z	 but got r   z+The given v should contain a single Tensor. zEntry z in zv has invalid size: should be )r+   RuntimeErrorr   zipsize)votheris_other_tupleidxel_vel_otherprepends          r   _validate_vrM   h   s     5zSV<SZL	RUVWRXQYYZ[  LMM!*3q%=!9 dH99;(--/)G"3%t,)9(--/9J)TXT]T]T_S``ab r   c                    |sy |dvrt        d      t        |       D ]m  \  }}|t        d| d      |j                  r$|dk(  rt        d| d      |dk(  rt        d	| d
      |dk(  rt        d| d      t        d| d       y )N)outputsgrad_inputsr
   r   z*Invalid input_type to _check_requires_gradAThe output of the user-provided function is independent of input %. This is not allowed in strict mode.r   z@The hessian of the user-provided function with respect to input z 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
   ziWhile computing the hessian, found that the jacobian of the user-provided function with respect to input z 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).rP   z#The gradient with respect to input z` is independent of the inputs of the user-provided function. This is not allowed in strict mode.Output z 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.)rC   r   r0   )r7   
input_typestrictr"   r   s        r   _check_requires_gradrV   }   s   JJGHHF# !3;STUSV W7 7    Y&"VWXVY::  z)"778c :CC  },"9! =S S 
 #aS !4 4 ;!r   c           	         t        | t              sJ |dt        |       z  }t        |t              sJ t        |       t        |      k(  sJ d}d}t        | |      D ]!  \  }}	|	|j                  s||fz  }||	fz  }# t        |      dk(  rdt        |      z  S t
        j                  j                  |||d|||      S )Nr   r(   r   T)allow_unusedr8   retain_graphis_grads_batched)r   r   r+   rD   r0   r   autogradgrad)
rO   r7   grad_outputsr8   rY   rZ   new_outputsnew_grad_outputsoutgrad_outs
             r   _autograd_gradrb      s     gu%%%W-lE***w<3|,,,,,.K13Wl3 ,X?s00C6!K+,
 ;1V$$~~""%%- # 
 	
r   c                    |dvrt        d| d      d}t        |       D ]  \  }}|f|rK|dk(  rt        d| d      |dk(  rt        d	| d
      |dk(  rt        d| d      t        d| d      t        j                  ||         }n2|r0|r.|j                  s"d|vrt        d| d      t        d| d      ||fz  } |S )N)back
back_trickdouble_backdouble_back_trickzInvalid stage argument 'z' to _fill_in_zerosr(   rd   rQ   rR   re   z?The gradient with respect to the input is independent of entry z in the grad_outputs when using the double backward trick to compute forward mode gradients. This is not allowed in strict mode.rf   CThe jacobian of the user-provided function is independent of input zBThe hessian of the user-provided function is independent of entry z 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<. This is not allowed in strict mode when create_graph=True.zBThe hessian of the user-provided function is independent of input )rC   r   r   
zeros_liker0   )gradsrefsrU   r8   stager,   r"   grads_is           r   _fill_in_zerosrp      sl   
 NN5eW<OPQQ$&C& )
7?F?&!!"#HJ  l*&YZ[Y\WW 
 m+&!!"#HJ 
 '!!" $33  &&tAw/G,w/D/D5(&!!"#_a 
 '!!"#_a 
 	zS)V Jr   c                    t        j                         5  t        |dd      \  }}t        ||d      } | | }t        |dd      \  }}t	        |d|       |,t        |d	d      \  }}t        ||d
      }t        |||       n/t        |      dk7  s|d   j                         dk7  rt        d      ddd       |rdnt        j                         }	t        j                  |	      5  t        |||      }
t        |
|||d      }ddd       t        |      }t        |      }t        |      t        |      fS # 1 sw Y   xY w# 1 sw Y   ExY w)a
  Compute 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:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> def exp_reducer(x):
        ...     return x.exp().sum(dim=1)
        >>> inputs = torch.rand(4, 4)
        >>> v = torch.ones(4)
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> 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.])))
    r7   r   Tr8   r9   %outputs of the user-provided functionrO   rU   NrF   Fr   r   zjThe vector v can only be None if the user-provided function returns a single Tensor with a single element.r8   rd   )r   enable_gradr$   r:   rV   rM   r+   nelementrC   is_grad_enabledset_grad_enabledrb   rp   r@   r.   )funcr7   rF   r8   rU   is_inputs_tuplerO   is_outputs_tuple_rv   grad_resr   s               r   r   r     st   v 
			 "+FHe"D!&|PTU-$-<e%
!' 	Wi?=QU+DAq %PA7$457|q GAJ$7$7$9Q$>"= !, '$E,A,A,CK				, M!'61<PXvv|VLM
  6G
C
.Cg'78:L_;  ? .M Ms   BE )E E	Ec                    t        j                         5  t        |dd      \  }}t        ||d      }|,t        |dd      \  }}t        ||d      }t	        |||       n/t        |      dk7  s|d	   j                         dk7  rt        d
       | | }t        |dd      \  }}t        |d|       t        d |D              }	t        |||	d      }
t        |
d|       ddd       |r<t        j                         5  t        
	||      }t        |||d      }ddd       nt        
	||      }t        |||d      }t        |      }t        |      }t        |      t        ||      fS # 1 sw Y   xY w# 1 sw Y   ExY w)a  Compute 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
        :func:`torch.func.jvp` or the
        :ref:`low-level forward-mode AD API <forward-mode-ad>` instead.

    Example:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> def exp_reducer(x):
        ...     return x.exp().sum(dim=1)
        >>> inputs = torch.rand(4, 4)
        >>> v = torch.ones(4, 4)
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> 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.]))

    r7   r	   Trr   NrF   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.rs   rO   rt   c              3   J   K   | ]  }t        j                  |d         ywT)r0   Nr   rk   )r)   r`   s     r   r*   zjvp.<locals>.<genexpr>  s%      
:=ES55
   !#ru   rP   re   )r   rv   r$   r:   rM   r+   rw   rC   rV   r   rb   rp   r@   r.   )rz   r7   rF   r8   rU   r{   r}   rO   r|   r]   rP   r~   r	   s                r   r	   r	   g  s   z 
			 H"+FHe"D!&|PTU=QU+DAq %PA6?36{a6!9#5#5#71#<"-  -$-<e%
!' 	Wi?  
AH
 
 %WflQUV[-G;H>   	X%\1<H !7FL,WC		X 	X "q|
 XwlS  6G
C
.Cg'78:L;  _H H@	X 	Xs   CE7F7F Ftensors.tensor_numelsreturnc                 "   t        |       t        |      k(  sJ t        |       dkD  sJ t        |      t        fdt        | |      D              }d}t        ||      D ]*  \  }}|j	                  |      j                  d       ||z  }, |S )Nr   c              3   H   K   | ]  \  }}|j                  |        y wr   )	new_zeros)r)   tensortensor_numeltotal_numels      r   r*   z0_construct_standard_basis_for.<locals>.<genexpr>  s*       FL 	l3s   "r   )r+   sumr   rD   diagonalfill_)r   r   chunksdiag_start_idxchunknumelr   s         @r   _construct_standard_basis_forr     s    * w<3}----w<!m$K $'$? F NFM2  u~&,,Q/%  Mr   c           	      P    |rt        d      t        dd      \  }g |rt        d D              }t        |      } fd} t	        |      |      }\  }	}
g }t        ||
      D ]  \  }}g }t        |j                  |d            D ]f  \  }} |j                  g t        d|j                        d j                  g |j                  |j                        }|j                  |       h |j                  |        t        ||	|f      S t        d	      )
Nztorch.autograd.functional.jacobian: `strict=True` and `strategy="forward-mode"` are not supported together (yet). Please either set `strict=False` or `strategy="reverse-mode"`.r7   r
   c              3   <   K   | ]  }|j                           y wr   r   )r)   inputs     r   r*   z_jacfwd.<locals>.<genexpr>  s     ?uU[[]?r>   c                    t        j                         5  t        d t        
|       D              }t	         	| d      \  }}j                  |       g }g }|D ]c  }t        j                  |      \  }}|j                  |       ||j                  |       @|j                  t        j                  |             e j                  |       t        |      cd d d        S # 1 sw Y   y xY w)Nc              3   l   K   | ],  \  }}t        j                  ||j                  |             . y wr   )fwAD	make_dualr3   )r)   r   tangents      r   r*   z'_jacfwd.<locals>.jvp.<locals>.<genexpr>  s0      $&w NN5'//%*@A$s   24rO   )	r   
dual_levelr   rD   r$   r2   unpack_dualr   rk   )tangentsdual_inputs_is_outputs_tupledual_outputsjvprimal_outsdual_outprimalr   rz   r7   output_infos            r   r	   z_jacfwd.<locals>.jvp  s    " !# $*-fh*?$  3<+&	3/!< ""#45  , <H&*&6&6x&@OFG&&v.*		'*		%"2"26":;< "";/Ry'! ! !s   CC''C0r   dimr   zlComputing Jacobian using forward-AD or forward-over-reverse Hessian isonly implemented for `vectorize=True`.)rC   r$   r   r   r   rD   splitpermuterangendimreshapeshaper2   r.   NotImplementedError)rz   r7   rU   	vectorizer{   input_numelsr   r	   outputs_before_splitr|   rO   jacobian_input_outputjac_output_ioutput_ijacobian_output_i_outputjacinput_jjacobian_input_i_output_jr   s   ``                @r   _jacfwdr     sb   )
 	
 (*EOVK??? 1F	!,  *uSz(3$/!' "&)*>&H 
	C"L(')$ #L$6$6|$6$KV T KW -8CKK,Oq#((9K,OQ,O,W,W5hnn5w}}5-) )//0IJK "(()AB
	C "!$4o#F
 	
 "5
 	
r   c           
          |dv sJ d       |dk(  rrt        d      t        | ||      S t        j                         5  t	        dd      \  }t        d       |  }t	        |d	d      \  }}t        |d
|       |r|rt        d      t        d |D               t        |       }	t        d |D               fd}
 |
|	      }g }t        |      D ]v  \  }}g }t        |j                   d      |      D ]>  \  }}|j                  |j                  |j                  z         }|j                  |       @ |j                  |       x t        t        |       }t        |      }t!        |||f      cddd       S d}t#        |      D ]  \  }t        d t%        t'                    D              }t%        j)                               D ]  }t+        j-                  d      |   fd      }t#        t        ||            D ]x  \  }\  }}}|3|rr|j.                  sd| d}t        |      |j                  |       ?|rd| d| d}t        |      |j                  t        j0                  |             z  |t        fdt#        |      D              fz  }  t        |      }t!        |||f      cddd       S # 1 sw Y   yxY w)aI  Compute 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 :func:`torch.func.jacrev` or
            :func:`torch.func.jacfwd` 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:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> def exp_reducer(x):
        ...     return x.exp().sum(dim=1)
        >>> inputs = torch.rand(2, 2)
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> 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-modereverse-modezExpected 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"`.r7   r
   Trr   rs   rO   rt   ztorch.autograd.functional.jacobian: `strict=True` and `vectorized=True` are not supported together. Please either set `strict=False` or `vectorize=False`.c              3   <   K   | ]  }|j                           y wr   r   r)   outputs     r   r*   zjacobian.<locals>.<genexpr>  s     !GV&,,.!Gr>   c              3   >   K   | ]  }|j                  d         yw)N)r   r   s     r   r*   zjacobian.<locals>.<genexpr>  s      J!3 J   c           	          t        t        | d            }t        |      D ]L  \  }}|	t        j                  |         j                  t              f|   j                  z         ||<   N t        |      S )NT)r8   rZ   )	r   rb   r   r   rk   expandr   r   r   )grad_outputvjel_idxvj_elr8   flat_outputsr7   output_numelss       r   r   zjacobian.<locals>.vjp  s    "$#%1)- &/r] MFE( !&!1!1&.!A!H!H]+-v0D0DD"BvJ Ry r   r   r   Nr(   c              3       K   | ]  }g   y wr   r(   )r)   r}   s     r   r*   zjacobian.<locals>.<genexpr>  s     4TAR4Ts   r   )rY   r8   rh   rj   rS   z7 of the user-provided function is independent of input rR   c              3      K   | ]O  \  }}t        j                  |d       j                  j                         |   j                         z          Q yw)r   r   N)r   stackviewrE   )r)   r   jac_i_elr7   r`   s      r   r*   zjacobian.<locals>.<genexpr>3  sP       + KKa055
VF^%8%8%::s   AA)r   r   r   rv   r$   r:   rV   rC   r   r   rD   r   r   r   r2   r@   r.   r   r   r+   rw   rb   r   r0   rk   )!rz   r7   r8   rU   r   strategyr{   rO   r|   r]   r   jacobians_of_flat_outputr   jac_input_iinput_ijacobian_input_i_outputr   output_jr   jacobian_output_inputr
   r"   jac_ijr   r   r   r   inp_elmsgr   r`   r   s!    ``                           @@@r   r
   r
   ?  s   f 77 	37
 >!%-  tVVY77				 \Q"+FHj"I!&|PTU-$-<j%
!' 	Wi?") ^ "!Gw!GGM8-PL  J' JJL!$ (+<'8$ %'!(+,Df(M F$W*,'%(%%m%;W& NMC 14'--9W0X-+223LM	N
 &,,-DEF %*#/D*E$F!$5%|%! &%(8/'JU\Q \Q\ .0( (	FAs/44Ts6{AS4T/TE3<<>* B#[[_Q')!%!-	 :Cr6*: B5F5Xuf (!l5;N;N!889s ;F!F  
 #/s"33 .!")! -88>x @/!/  
 #/s"33 (8(8(@A)BB<   /8.>	  HC(	T %X|<!(-=,OPy\Q \Q \Qs   EK#EK##K,c                     	 t        |dd      \  }}dv sJ d        fd		fd}t        ||||      }t        |||f      S )a  Compute 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 :func:`torch.func.hessian`
            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:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> def pow_reducer(x):
        ...     return x.pow(3).sum()
        >>> inputs = torch.rand(2, 2)
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> 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.]])))
    r7   r   r   z@Expected strategy to be either "forward-mode" or "reverse-mode".c                       |  }t        |dd      \  }}t        |d       |st        |t        j                        st        d      |j                         dk7  rt        d      |j                         S )Nrs   r   rO   rt   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$   rV   r   r   r   rC   rw   squeeze)r   r`   is_out_tuplet_outrz   rU   s       r   ensure_single_output_functionz.hessian.<locals>.ensure_single_output_function  s    Cj'8)
e 	UIf=z#u||<M  <<>Qf  {{}r   c                  n    dk(  rt        d | D              } t        | d      }t        |d       |S )Nr   c              3   >   K   | ]  }|j                  d         yw)TN)r6   )r)   ts     r   r*   z,hessian.<locals>.jac_func.<locals>.<genexpr>  s     <1((.<r   Tru   r
   rt   )r   r
   rV   )r   r   r   outer_jacobian_strategyrU   s     r   jac_funczhessian.<locals>.jac_func  s=    "n4 <<<C4cMS*V<
r   )r8   rU   r   r   )r$   r
   r.   )
rz   r7   r8   rU   r   r   r{   r   r,   r   s
   `  ` `   @r   r   r   @  sy    z ()DOV" '  J JJ 
& !(C cO_#EFFr   c                 ~   t        j                         5  t        |dd      \  }}t        ||d      }|,t        |dd      \  }}t        ||d      }t	        |||       n/t        |      dk7  s|d	   j                         dk7  rt        d
       | | }t        |dd      \  }}t        |d|       |st        |d	   t         j                        st        d      |d	   j                         dk7  rt        d      t        ||d      }	t        |	d|       ddd       |rdnt        j                         }
t        j                  |
      5  t        	|||      }t        ||||d      }ddd       t        |      }t        |      }t!        |      t!        |      fS # 1 sw Y   xY w# 1 sw Y   ExY w)a	  Compute the dot product between vector ``v`` and Hessian of a  given scalar function at a specified point.

    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:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> def pow_reducer(x):
        ...     return x.pow(3).sum()
        >>> inputs = torch.rand(2, 2)
        >>> v = torch.ones(2, 2)
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> 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.])))
    r7   r   Trr   NrF   Fr   r   r   rs   rO   rt   z7The function given to vhp should return a single TensorzPThe Tensor returned by the function given to vhp should contain a single elementru   r
   rf   )r   rv   r$   r:   rM   r+   rw   rC   rV   r   r   rb   rx   ry   rp   r@   r.   )rz   r7   rF   r8   rU   r{   r}   rO   r|   r   rv   r~   r   s                r   r   r     s   n 
			 ="+FHe"D!&|PTU=QU+DAq %PA6?36{a6!9#5#5#71#<"@  -$-<e%
!' 	Wi?:gaj%,,#GI  1: A%b  Wf4@S*V<?=B '$E,A,A,CK				, T!#vq|LXvv|]ST  6G
C
.Cg'78:L_;  S= =DT Ts   DF'F3'F03F<c                    t        j                         5  t        |dd      \  }}t        ||d      }|,t        |dd      \  }}t        ||d      }t	        |||       n/t        |      dk7  s|d	   j                         dk7  rt        d
       | | }t        |dd      \  }}t        |d|       |st        |d	   t         j                        st        d      |d	   j                         dk7  rt        d      t        ||d      }	t        |	d|       t        d |D              }
t        |	||
d      }t        |	d|       ddd       |rdnt        j                         }t        j                  |      5  t        
||      }t        ||||d      }ddd       t!        |      }t!        |      }t#        |      t#        |      fS # 1 sw Y   xY w# 1 sw Y   ExY w)a%  Compute the dot product between the scalar function's Hessian and a vector ``v`` at a specified point.

    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:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD)
        >>> def pow_reducer(x):
        ...     return x.pow(3).sum()
        >>> inputs = torch.rand(2, 2)
        >>> v = torch.ones(2, 2)
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> 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.

    r7   r   Trr   NrF   Fr   r   r   rs   rO   rt   z7The function given to hvp should return a single TensorzPThe Tensor returned by the function given to hvp should contain a single elementru   r
   c              3   J   K   | ]  }t        j                  |d         ywr   r   r=   s     r   r*   zhvp.<locals>.<genexpr>  s      Us))#TBBUr   r   rg   )r   rv   r$   r:   rM   r+   rw   rC   rV   r   r   rb   r   rx   ry   rp   r@   r.   )rz   r7   rF   r8   rU   r{   r}   rO   r|   r   grad_jacrf   rv   r~   r   s                  r   r   r   /  s   @ 
			 $<"+FHe"D!&|PTU=QU+DAq %PA6?36{a6!9#5#5#71#<"@  -$-<e%
!' 	Wi?:gaj%,,#GI  1: A%b  Wf4@S*V<UfUU$S&(NS)F;I$<L '$E,A,A,CK				, 
!+xVffl4G

  6G
C
.Cg'78:L_;  a$< $<N
 
s   D5G?G"G"G+)NN)NFNF)NFF)FF)FFFr   )typingr   r   r   torch._vmap_internalsr   rB   r   r   __all__r   r$   r.   r:   r@   rM   rV   rb   rp   r   r	   r   intr   r   r
   r   r   r   r(   r   r   <module>r      s      '   >
6$.	M*(\ #
L4t\~nb 5<<$% 6;CHo 
5<< FA
N ~QH *GGTbJrr   