@@ -2705,34 +2705,53 @@ def jvp(
27052705 create_graph : bool = False ,
27062706 strict : bool = False ,
27072707 ) -> Tuple [Any , Any ]:
2708- """Jacobian-vector product via central finite differences (NOT exact forward-mode AD).
2709-
2710- Approximates J(x)v as (f(x+eps*v) - f(x-eps*v)) / (2*eps) with
2711- eps=1e-3, giving O(eps^2) truncation error plus float32 rounding
2712- (~1e-4 relative on O(1) outputs). Use only for gradient checks and
2713- prototyping; unlike torch.func.jvp this is not exact to machine
2714- precision.
2715- """
2708+ """Exact forward-mode Jacobian-vector product via reverse-over-reverse (double backward) AD."""
27162709 is_tuple = isinstance (inputs , tuple )
27172710 t_inputs = inputs if is_tuple else (inputs ,)
27182711 if v is None :
27192712 v_tuple = tuple (ones_like (inp ) for inp in t_inputs )
27202713 else :
27212714 v_tuple = v if isinstance (v , tuple ) else (v ,)
2715+ if len (t_inputs ) != len (v_tuple ):
2716+ raise ValueError (f"jvp: inputs length ({ len (t_inputs )} ) must match v length ({ len (v_tuple )} )" )
27222717
2723- eps = 1e-3
2724- outputs = func (* t_inputs )
2725- fwd_inputs = tuple (inp + eps * vi for inp , vi in zip (t_inputs , v_tuple ))
2726- bwd_inputs = tuple (inp - eps * vi for inp , vi in zip (t_inputs , v_tuple ))
2727- fwd_outputs = func (* fwd_inputs )
2728- bwd_outputs = func (* bwd_inputs )
2718+ p_leaves = tuple (inp .detach ().requires_grad_ (True ) for inp in t_inputs )
2719+ outputs = func (* p_leaves )
2720+ out_is_tuple = isinstance (outputs , tuple )
2721+ out_tuple = outputs if out_is_tuple else (outputs ,)
27292722
2730- if isinstance (outputs , tuple ):
2731- jvp_res = tuple ((p - m ) * (0.5 / eps ) for p , m in zip (fwd_outputs , bwd_outputs ))
2723+ u_dummies = tuple (zeros_like (o ).detach ().requires_grad_ (True ) for o in out_tuple )
2724+ vjps = _AutogradModule .grad (
2725+ out_tuple ,
2726+ p_leaves ,
2727+ grad_outputs = u_dummies ,
2728+ create_graph = True ,
2729+ allow_unused = not strict ,
2730+ )
2731+ terms = []
2732+ for g , vi in zip (vjps , v_tuple ):
2733+ if g is not None :
2734+ terms .append ((g * vi ).sum ())
2735+ if not terms :
2736+ jvp_tuple = tuple (zeros_like (o ) for o in out_tuple )
27322737 else :
2733- jvp_res = (fwd_outputs - bwd_outputs ) * (0.5 / eps )
2734-
2735- return outputs , jvp_res
2738+ scalar = terms [0 ]
2739+ for t_item in terms [1 :]:
2740+ scalar = scalar + t_item
2741+ raw_jvps = _AutogradModule .grad (
2742+ scalar ,
2743+ u_dummies ,
2744+ create_graph = create_graph ,
2745+ allow_unused = True ,
2746+ )
2747+ jvp_tuple = tuple (
2748+ zeros_like (o ) if g is None else g
2749+ for g , o in zip (raw_jvps , out_tuple )
2750+ )
2751+
2752+ res_out = outputs if out_is_tuple else outputs .detach () if not create_graph else outputs
2753+ res_jvp = jvp_tuple if out_is_tuple else jvp_tuple [0 ]
2754+ return res_out , res_jvp
27362755
27372756 @staticmethod
27382757 def jacobian (
@@ -2798,53 +2817,31 @@ def hessian(
27982817 strict : bool = False ,
27992818 vectorize : bool = False ,
28002819 ) -> Union [_Tensor , Tuple [Any , ...]]:
2801- """Hessian via central finite differences of autograd gradients (approximate).
2802-
2803- Inputs that do not affect the output yield zero rows/columns.
2804- """
2820+ """Exact Hessian via reverse-over-reverse automatic differentiation."""
28052821 is_tuple = isinstance (inputs , tuple )
28062822 t_inputs = inputs if is_tuple else (inputs ,)
28072823
2808- eps = 1e-3
2809- all_hessians = []
2810-
2811- for k , inp_k in enumerate (t_inputs ):
2812- n = inp_k .numel ()
2813- arr_k = inp_k .to_numpy ().astype (np .float32 )
2814- flat_k = arr_k .flatten ()
2815- H_k = np .zeros ((n , n ), dtype = np .float32 )
2816-
2817- for j in range (n ):
2818- e_j = np .zeros (n , dtype = np .float32 )
2819- e_j [j ] = eps
2820-
2821- flat_pos = flat_k + e_j
2822- flat_neg = flat_k - e_j
2823-
2824- pos_inputs = list (t_inputs )
2825- neg_inputs = list (t_inputs )
2826- pos_inputs [k ] = tensor (flat_pos .reshape (arr_k .shape ), dtype = inp_k .dtype , device = inp_k .device , requires_grad = True )
2827- neg_inputs [k ] = tensor (flat_neg .reshape (arr_k .shape ), dtype = inp_k .dtype , device = inp_k .device , requires_grad = True )
2828-
2829- out_pos = func (* pos_inputs ) if is_tuple else func (pos_inputs [0 ])
2830- out_neg = func (* neg_inputs ) if is_tuple else func (neg_inputs [0 ])
2831-
2832- out_pos .backward ()
2833- out_neg .backward ()
2834-
2835- # Unused inputs have no grad (None); their Hessian block is zero.
2836- g_pos_t = pos_inputs [k ].grad
2837- g_neg_t = neg_inputs [k ].grad
2838- g_pos = g_pos_t .to_numpy ().flatten () if g_pos_t is not None else np .zeros (n , dtype = np .float32 )
2839- g_neg = g_neg_t .to_numpy ().flatten () if g_neg_t is not None else np .zeros (n , dtype = np .float32 )
2840- H_k [:, j ] = (g_pos - g_neg ) / (2.0 * eps )
2824+ def _hessian_block (k : int , target_k : int ):
2825+ def grad_fn (x_target ):
2826+ leaves = [
2827+ x_target if idx == k else inp .detach ().requires_grad_ (True )
2828+ for idx , inp in enumerate (t_inputs )
2829+ ]
2830+ out = func (* leaves )
2831+ if strict :
2832+ g = _AutogradModule .grad (out , leaves [target_k ], create_graph = True , allow_unused = False )[0 ]
2833+ else :
2834+ g = _AutogradModule .grad (out , leaves [target_k ], create_graph = True , allow_unused = True )[0 ]
2835+ return zeros_like (leaves [target_k ]) if g is None else g
28412836
2842- H_k = 0.5 * (H_k + H_k .T )
2843- shape = list (inp_k .shape ) + list (inp_k .shape )
2844- res_t = _from_numpy (_contig (H_k .reshape (shape ), dtype = inp_k .to_numpy ().dtype ))
2845- all_hessians .append (res_t )
2837+ return _FunctionalAutograd .jacobian (grad_fn , t_inputs [k ], create_graph = create_graph , strict = strict )
28462838
2847- return tuple (all_hessians ) if is_tuple else all_hessians [0 ]
2839+ if not is_tuple :
2840+ return _hessian_block (0 , 0 )
2841+ return tuple (
2842+ tuple (_hessian_block (j , i ) for j in range (len (t_inputs )))
2843+ for i in range (len (t_inputs ))
2844+ )
28482845
28492846 @staticmethod
28502847 def hvp (
0 commit comments