Skip to content

Commit 3bc79e9

Browse files
committed
fix: exact reverse-over-reverse jvp/hessian, persistent=False buffers, PyLayer named_parameters in Module
1 parent e9b2384 commit 3bc79e9

5 files changed

Lines changed: 140 additions & 70 deletions

File tree

‎python/oxideon/__init__.pyi‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6598,6 +6598,7 @@ class Module:
65986598
def _copy_state_value(target: Any, val: Any, key: Any, owner_name: Any) -> Any: ...
65996599
@staticmethod
66006600
def _move_in_place(tensor: Any, device: Any, dtype: Any) -> Any: ...
6601+
def _named_persistent_buffers(self, prefix: Any = '') -> Any: ...
66016602
def _resolve_key(self, key: Any) -> Any: ...
66026603
def add_module(self, name: str, module: Any) -> None: ...
66036604
def apply(self, fn: Any) -> Any: ...
@@ -6613,7 +6614,7 @@ class Module:
66136614
def load_file(self, path: Any, strict: Any = True, device: Any = None) -> Any: ...
66146615
def load_state_dict(self, state_dict: Any, strict: Any = True) -> Any: ...
66156616
def modules(self) -> Any: ...
6616-
def named_buffers(self, prefix: Any = '', recurse: Any = True) -> Any: ...
6617+
def named_buffers(self, prefix: Any = '', recurse: Any = True, remove_duplicate: Any = True) -> Any: ...
66176618
def named_children(self) -> Any: ...
66186619
def named_modules(self, memo: Any = None, prefix: Any = '') -> Any: ...
66196620
def named_parameters(self, prefix: Any = '', recurse: Any = True) -> Any: ...

‎python/oxideon/func.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -192,16 +192,18 @@ def jvp(
192192
v_np = _to_np(t_tuple[0]).reshape(-1)
193193
out_shape = out.shape
194194
out_numel = int(np.prod(out_shape)) if len(out_shape) > 0 else 1
195-
jvp_np = (jac_np.reshape(out_numel, -1) @ v_np).reshape(out_shape).astype(np.float32)
195+
out_dt = _to_np(out).dtype
196+
jvp_np = (jac_np.reshape(out_numel, -1) @ v_np).reshape(out_shape).astype(out_dt)
196197
return out, _from_numpy(np.ascontiguousarray(jvp_np))
197198

198199
out_shape = out.shape
199200
out_numel = int(np.prod(out_shape)) if len(out_shape) > 0 else 1
200-
total_jvp = np.zeros(out_numel, dtype=np.float32)
201+
out_dt = _to_np(out).dtype
202+
total_jvp = np.zeros(out_numel, dtype=out_dt)
201203
for j_i, v_i in zip(jac, t_tuple):
202204
j_np = _to_np(j_i).reshape(out_numel, -1)
203205
v_np = _to_np(v_i).reshape(-1)
204-
total_jvp += (j_np @ v_np).astype(np.float32)
206+
total_jvp += (j_np @ v_np).astype(out_dt)
205207
return out, _from_numpy(np.ascontiguousarray(total_jvp.reshape(out_shape)))
206208

207209

‎python/oxideon/nn.py‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ def __init__(self):
219219
self._buffers = OrderedDict()
220220
self._forward_pre_hooks = OrderedDict()
221221
self._forward_hooks = OrderedDict()
222+
self._non_persistent_buffers_set = set()
222223
self.training = True
223224

224225
def add_module(self, name: str, module: Optional[Any]) -> None:
@@ -278,10 +279,16 @@ def register_parameter(self, name, param):
278279
super().__setattr__(name, None)
279280

280281
def register_buffer(self, name, tensor, persistent=True):
281-
"""Adds a persistent buffer to the module (e.g. running statistics)."""
282+
"""Adds a buffer to the module (optionally non-persistent so omitted from state_dict)."""
282283
if tensor is not None and not isinstance(tensor, _Tensor):
283284
tensor = _from_numpy(np.asarray(tensor))
284285
self._buffers[name] = tensor
286+
if not hasattr(self, "_non_persistent_buffers_set"):
287+
self._non_persistent_buffers_set = set()
288+
if persistent:
289+
self._non_persistent_buffers_set.discard(name)
290+
else:
291+
self._non_persistent_buffers_set.add(name)
285292
super().__setattr__(name, tensor)
286293

287294
def forward(self, *args, **kwargs):
@@ -315,6 +322,8 @@ def named_parameters(self, prefix="", recurse=True):
315322
full_prefix = f"{prefix}.{mod_name}" if prefix else mod_name
316323
if isinstance(child, Module):
317324
yield from child.named_parameters(prefix=full_prefix, recurse=True)
325+
elif hasattr(child, "named_parameters"):
326+
yield from child.named_parameters(prefix=f"{full_prefix}.")
318327
elif hasattr(child, "parameters"):
319328
for i, p in enumerate(child.parameters()):
320329
p_name = f"{full_prefix}.weight" if i == 0 else f"{full_prefix}.bias" if i == 1 else f"{full_prefix}.param_{i}"
@@ -330,7 +339,7 @@ def buffers(self, recurse=True):
330339
if isinstance(child, Module):
331340
yield from child.buffers(recurse=True)
332341

333-
def named_buffers(self, prefix="", recurse=True):
342+
def named_buffers(self, prefix="", recurse=True, remove_duplicate=True):
334343
"""Returns an iterator over module buffers, yielding both name and buffer."""
335344
for name, b in self._buffers.items():
336345
if b is not None:
@@ -340,7 +349,18 @@ def named_buffers(self, prefix="", recurse=True):
340349
for mod_name, child in self.named_children():
341350
full_prefix = f"{prefix}.{mod_name}" if prefix else mod_name
342351
if isinstance(child, Module):
343-
yield from child.named_buffers(prefix=full_prefix, recurse=True)
352+
yield from child.named_buffers(prefix=full_prefix, recurse=True, remove_duplicate=remove_duplicate)
353+
354+
def _named_persistent_buffers(self, prefix=""):
355+
non_p = getattr(self, "_non_persistent_buffers_set", ())
356+
for name, b in self._buffers.items():
357+
if b is not None and name not in non_p:
358+
full_name = f"{prefix}.{name}" if prefix else name
359+
yield full_name, b
360+
for mod_name, child in self.named_children():
361+
full_prefix = f"{prefix}.{mod_name}" if prefix else mod_name
362+
if isinstance(child, Module):
363+
yield from child._named_persistent_buffers(prefix=full_prefix)
344364

345365
def children(self):
346366
"""Returns an iterator over immediate child modules."""
@@ -476,7 +496,7 @@ def state_dict(self, destination=None, prefix=""):
476496
destination = OrderedDict()
477497
for name, p in self.named_parameters(prefix=prefix):
478498
destination[name] = p.clone() if hasattr(p, "clone") else p
479-
for name, b in self.named_buffers(prefix=prefix):
499+
for name, b in self._named_persistent_buffers(prefix=prefix):
480500
destination[name] = b.clone() if hasattr(b, "clone") else b
481501
return destination
482502

@@ -521,7 +541,7 @@ def load_state_dict(self, state_dict, strict=True):
521541
missing_keys = []
522542
unexpected_keys = list(state_dict.keys())
523543
current_params = dict(self.named_parameters())
524-
current_buffers = dict(self.named_buffers())
544+
current_buffers = dict(self._named_persistent_buffers())
525545

526546
for key, target_param in current_params.items():
527547
if key in state_dict:

‎python/oxideon/primitives.py‎

Lines changed: 58 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -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(

‎tests/test_bug_hunt.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -831,3 +831,53 @@ def test_squeeze_tuple_clamp_tensor_layernorm_affine_bias_utils_and_opt_state_di
831831
]:
832832
m = cls(4, affine=True, track_running_stats=True)
833833
assert m.running_mean is not None and tuple(m(T(inp)).shape) == inp.shape
834+
835+
836+
def test_exact_jvp_hessian_and_persistent_buffers():
837+
from collections import OrderedDict
838+
import oxideon.nn as nn
839+
840+
x_np = np.array([1.2, -0.7, 0.4], dtype=np.float64)
841+
v_np = np.array([0.5, 1.0, -0.3], dtype=np.float64)
842+
f_ox = lambda z: (z.sin() + z * z * 0.5).sum()
843+
f_pt = lambda z: (z.sin() + z * z * 0.5).sum()
844+
845+
o1, j1 = ox.autograd.functional.jvp(f_ox, (T(x_np),), (T(v_np),))
846+
p1, pj1 = torch.autograd.functional.jvp(f_pt, (torch.from_numpy(x_np),), (torch.from_numpy(v_np),))
847+
np.testing.assert_allclose(A(o1), p1.numpy(), atol=1e-12)
848+
np.testing.assert_allclose(A(j1), pj1.numpy(), atol=1e-12)
849+
850+
oh = ox.autograd.functional.hessian(f_ox, T(x_np))
851+
ph = torch.autograd.functional.hessian(f_pt, torch.from_numpy(x_np))
852+
assert oh.dtype == "f64"
853+
np.testing.assert_allclose(A(oh), ph.numpy(), atol=1e-12)
854+
np.testing.assert_allclose(A(ox.func.hessian(f_ox)(T(x_np))), ph.numpy(), atol=1e-12)
855+
856+
f2_ox = lambda a, b: (a * b).sum() + (a ** 2).sum() * 0.5
857+
f2_pt = lambda a, b: (a * b).sum() + (a ** 2).sum() * 0.5
858+
oa = T(np.array([1.0, 2.0]))
859+
ob = T(np.array([3.0, 4.0]))
860+
pa = torch.tensor([1.0, 2.0], dtype=torch.float64)
861+
pb = torch.tensor([3.0, 4.0], dtype=torch.float64)
862+
h2o = ox.autograd.functional.hessian(f2_ox, (oa, ob))
863+
h2p = torch.autograd.functional.hessian(f2_pt, (pa, pb))
864+
for r in range(2):
865+
for c in range(2):
866+
np.testing.assert_allclose(A(h2o[r][c]), h2p[r][c].numpy(), atol=1e-12)
867+
868+
class Net(nn.Module):
869+
def __init__(self):
870+
super().__init__()
871+
self.wn = ox.WeightNormLinear(4, 3)
872+
self.register_buffer("perm", ox.ones(3), persistent=True)
873+
self.register_buffer("scratch", ox.zeros(3), persistent=False)
874+
875+
m = Net()
876+
sd = m.state_dict()
877+
assert set(sd.keys()) == {"wn.weight_g", "wn.weight_v", "wn.bias", "perm"}
878+
assert "scratch" in dict(m.named_buffers())
879+
m.load_state_dict(sd)
880+
881+
s = nn.Sequential(OrderedDict([("fc1", nn.Linear(4, 3)), ("act", nn.ReLU()), ("fc2", nn.Linear(3, 2))]))
882+
assert tuple(s(ox.ones(2, 4)).shape) == (2, 2)
883+
assert s[-1] is s.fc2 and len(s[:2]) == 2

0 commit comments

Comments
 (0)