From 84825961d04083270e27614b2edccc2e663f3a0e Mon Sep 17 00:00:00 2001 From: Zitong Zhan Date: Sat, 24 Oct 2026 21:37:31 -0400 Subject: [PATCH 1/2] Add block-Jacobi preconditioning for Schur and speed up matrix-free solves - Add BlockJacobiPCG, a PCG subclass whose preconditioner for warp BSR systems inverts the diagonal blocks instead of warp's scalar Jacobi. Schur uses the solver's preconditioner when it provides one. - Matrix-free Schur now preconditions with the block diagonal of the Schur complement S = U - W V^-1 W^T, computed per observation by a warp kernel, instead of with U. - Convert the assembled Jacobian CSR in LM.step to int32 indices when they fit (COO -> CSR widens them to int64). - NormalMatVec: precompute damping * diag in set_damping so matvec has no host sync, fuse the damping term with addcmul_, and return a copy from diagonal() since PCG modifies it in place. On BAL Ladybug-1723 (20 LM steps, RTX 3080), matrix-free Schur with BlockJacobiPCG runs in 2.75 s vs 2.83 s, and explicit Schur in 8.1 s vs 12.4 s. Co-Authored-By: Claude Opus 5.5 --- bae/optim/optimizer.py | 32 +++++++++++++++++++++++++++----- bae/sparse/py_ops.py | 17 +++++++++++++++++ bae/sparse/warp_wrappers.py | 6 ++++++ bae/utils/linear_operator.py | 30 +++++++++++++----------------- bae/utils/pysolvers.py | 11 +++++++++++ 5 files changed, 74 insertions(+), 22 deletions(-) diff --git a/bae/optim/optimizer.py b/bae/optim/optimizer.py index f122b4c..3e8c024 100644 --- a/bae/optim/optimizer.py +++ b/bae/optim/optimizer.py @@ -1,11 +1,12 @@ from functools import partial +from typing import Any import torch from pypose.optim import LevenbergMarquardt as ppLM import pypose as pp from ..autograd.graph import jacobian from ..autograd.function import TrackingTensor -from ..sparse.py_ops import diagonal_op_, inv_op +from ..sparse.py_ops import compact_indices, diagonal_op_, inv_op from ..sparse.spgemm import CuSparse from ..utils.linear_operator import NormalMatVec from ..utils.parameter import parameter_update_shape @@ -13,7 +14,7 @@ import warp as wp from warp import sparse from warp.optim import linear -from bae.sparse.warp_wrappers import format_vec_for_bsr, torchbsr2wp, wp2torchbsr +from bae.sparse.warp_wrappers import block_diag_wp, format_vec_for_bsr, torchbsr2wp, wp2torchbsr class LM(ppLM): @@ -32,6 +33,7 @@ def step(self, input, target=None, weight=None): if isinstance(R, TrackingTensor): R = R.tensor() J = torch.cat([j.to_sparse_coo() for j in J], dim=-1).to_sparse_csr() + J = compact_indices(J) # COO -> CSR widens indices to int64 self.last = self.loss = self.loss if hasattr(self, 'loss') else self.model.loss(input, target) self.reject_count = 0 @@ -96,6 +98,20 @@ def update_parameter(self, params, step): param.add_(step_view) +@wp.kernel +def _schur_diag_kernel( + J0: wp.array(dtype=Any), J1: wp.array(dtype=Any), + cam: wp.array(dtype=int), pt: wp.array(dtype=int), + V_inv: wp.array(dtype=Any), S: wp.array(dtype=Any), +): + # Block diagonal of the Schur complement: S_cc = U_cc - sum_o W_o V_p^-1 W_o^T with + # W_o = J0_o^T J1_o, assuming one block per row in J0 and J1 (exact when each camera + # observes each point once). S holds diag(U) on entry. + o = wp.tid() + W = wp.transpose(J0[o]) @ J1[o] + wp.atomic_sub(S, cam[o], W @ V_inv[pt[o]] @ wp.transpose(W)) + + class Schur(LM): @torch.no_grad() def step(self, input, target=None, weight=None): @@ -138,6 +154,7 @@ def step(self, input, target=None, weight=None): solver_tol = getattr(self.solver, "tol", None) solver_maxiter = getattr(self.solver, "maxiter", 0) or 0 + precond = getattr(self.solver, "preconditioner", linear.preconditioner) while self.last <= self.loss: damp = partial(torch.mul, other=1+pg['damping']) @@ -161,7 +178,12 @@ def schur_matvec(x, y, z, alpha, beta, _V_i=V_i): shape=U.shape, dtype=U.values.dtype, device=U.device, matvec=schur_matvec, ) - schur_M = linear.preconditioner(U) + # Precondition with the block diagonal of S instead of U. + S_diag = sparse.bsr_get_diag(U) + wp.launch(_schur_diag_kernel, dim=J0wp.nnz, inputs=[ + J0wp.values, J1wp.values, J0wp.columns, J1wp.columns, + sparse.bsr_get_diag(V_i), S_diag]) + schur_M = precond(block_diag_wp(wp.to_torch(S_diag))) wp.copy(src=Ic, dest=rhs_c) sparse.bsr_mv(V_i, Ip, y=scratch_pts2, beta=0.0) @@ -177,7 +199,7 @@ def schur_matvec(x, y, z, alpha, beta, _V_i=V_i): size=Upt.shape, device=Upt.device, dtype=Upt.dtype, ) schur_op = sparse.bsr_axpy(WVi_Wt, torchbsr2wp(U_clone_torch), alpha=-1.0) - schur_M = linear.preconditioner(schur_op) + schur_M = precond(schur_op) wp.copy(src=Ic, dest=rhs_c) sparse.bsr_mv(V_i, Ip, y=scratch_pts2, beta=0.0) sparse.bsr_mv(W, scratch_pts2, y=rhs_c, alpha=-1.0, beta=1.0) @@ -209,7 +231,7 @@ def schur_matvec(x, y, z, alpha, beta, _V_i=V_i): x=D_p, tol=solver_tol, maxiter=solver_maxiter, - M=linear.preconditioner(V), + M=precond(V), ) D_c_t = wp.to_torch(D_c).flatten() diff --git a/bae/sparse/py_ops.py b/bae/sparse/py_ops.py index 058daee..8173b91 100644 --- a/bae/sparse/py_ops.py +++ b/bae/sparse/py_ops.py @@ -166,6 +166,23 @@ def spdiags_(diagonal, offset, shape, layout): return torch.sparse_csr_tensor(crow_indices, col_indices, diagonal) +def compact_indices(input): + """ + Returns the CSR/BSR tensor with int32 indices if the nnz and both dimensions fit in int32, + otherwise the input unchanged. SpMV/SpGEMM are memory bound and int64 indices are a large + share of the bytes read. + """ + if input.layout not in (torch.sparse_csr, torch.sparse_bsr): + return input + if input.col_indices().dtype == torch.int32: + return input + if max(input._nnz(), *input.shape) > torch.iinfo(torch.int32).max: + return input + ctor = torch.sparse_csr_tensor if input.layout == torch.sparse_csr else torch.sparse_bsr_tensor + return ctor(input.crow_indices().to(torch.int32), input.col_indices().to(torch.int32), + input.values(), size=input.shape) + + def inv_op(input): crow_indices = input.crow_indices() # b + 1 dimensional col_indices = input.col_indices() # b + 1 dimensional diff --git a/bae/sparse/warp_wrappers.py b/bae/sparse/warp_wrappers.py index dd3f4bb..102ad14 100644 --- a/bae/sparse/warp_wrappers.py +++ b/bae/sparse/warp_wrappers.py @@ -19,6 +19,12 @@ def torchbsr2wp(tbsr): bsr.offsets = wp.from_torch(tbsr.crow_indices().to(torch.int32)) return bsr +def block_diag_wp(blocks): + """Warp BSR matrix with the (n, b, b) torch tensor `blocks` on its diagonal.""" + n, bm, bn = blocks.shape + idx = torch.arange(n + 1, dtype=torch.int32, device=blocks.device) + return torchbsr2wp(torch.sparse_bsr_tensor(idx, idx[:-1], blocks.contiguous(), size=(n * bm, n * bn))) + def wp2torchbsr(bsr): """ Convert a Warp BSR matrix back into a PyTorch sparse BSR tensor. diff --git a/bae/utils/linear_operator.py b/bae/utils/linear_operator.py index 070badf..f2eac07 100644 --- a/bae/utils/linear_operator.py +++ b/bae/utils/linear_operator.py @@ -44,18 +44,24 @@ def __init__( self.set_damping(damping) def set_damping(self, damping: Union[float, Tensor]) -> None: + # Precompute damping * diag once here so matvec needs no host sync or + # host-to-device copy of the damping scalar. if isinstance(damping, Tensor): if damping.numel() != 1: raise ValueError("damping tensor must be scalar") - self.damping = damping.to(device=self.device, dtype=self.dtype) + self.damping = damping.to(device=self.device, dtype=self.dtype).reshape(()) + self._damp_diag = (self.damping * self._diag).unsqueeze(-1) else: self.damping = float(damping) + self._damp_diag = ( + None if self.damping == 0.0 else (self.damping * self._diag).unsqueeze(-1) + ) def diagonal(self) -> Tensor: - damp = self._damping_value() - if damp is None: - return self._diag - return self._diag * (1.0 + damp) + # Always a new tensor: callers (e.g. PCG) modify the result in place. + if self._damp_diag is None: + return self._diag.clone() + return self._diag + self._damp_diag.squeeze(-1) def matvec(self, x: Tensor) -> Tensor: if x.ndim == 1: @@ -72,9 +78,8 @@ def matvec(self, x: Tensor) -> Tensor: Jt = self._get_Jt() z = Jt @ y - damp = self._damping_value() - if damp is not None: - z = z + damp * self._diag.unsqueeze(-1) * x2d + if self._damp_diag is not None: + z.addcmul_(self._damp_diag, x2d) return z.squeeze(-1) if x.ndim == 1 else z @@ -113,15 +118,6 @@ def _get_Jt(self) -> Tensor: self._Jt = Jt return self._Jt - def _damping_value(self) -> Optional[Tensor]: - if isinstance(self.damping, Tensor): - if self.damping.item() == 0.0: - return None - return self.damping - if self.damping == 0.0: - return None - return torch.tensor(self.damping, device=self.device, dtype=self.dtype) - @staticmethod def _compute_diag(J: Tensor) -> Tensor: if J.layout == torch.strided: diff --git a/bae/utils/pysolvers.py b/bae/utils/pysolvers.py index 0a61e3e..a9d1eec 100644 --- a/bae/utils/pysolvers.py +++ b/bae/utils/pysolvers.py @@ -2,7 +2,10 @@ import torch from torch import Tensor from pypose.optim.solver import CG +import warp as wp +from warp import sparse from bae.sparse.py_ops import spdiags_ +from bae.sparse.warp_wrappers import block_diag_wp try: from bae.sparse.solve import CuDirectSparseSolver as CuDSS @@ -37,6 +40,14 @@ def forward(self, A, b, x=None, M=None) -> torch.Tensor: res = res.squeeze(-1) return res + +class BlockJacobiPCG(PCG): + """PCG whose preconditioner for warp BSR systems (used by `Schur`) is the + inverse of the diagonal blocks of A, instead of warp's scalar Jacobi.""" + def preconditioner(self, A): + return block_diag_wp(torch.linalg.inv(wp.to_torch(sparse.bsr_get_diag(A)))) + + class SciPySpSolver(torch.nn.Module): def __init__(self, ): super().__init__() From 236a509169b6c6bf95b2443d4382a69a03b5c88a Mon Sep 17 00:00:00 2001 From: Zitong Zhan Date: Sun, 15 Nov 2026 23:30:09 -0500 Subject: [PATCH 2/2] Keep J^T in matrix-free Schur instead of transposed matvecs The matrix-free branch of Schur.step now keeps the transposed Jacobians built for U and V and uses plain bsr_mv on them for the J^T products. Warp's bsr_mv(..., transpose=True) scatters with atomics and is several times slower (J0^T product 530 us -> 212 us on Ladybug-1723). One Schur matvec: 0.93 ms -> 0.60 ms; 20 LM steps with BlockJacobiPCG: 2.75 s -> 2.16 s at the same loss. Warp pool peak +~40 MiB (the transposes now live through the solve); torch peak unchanged. Co-Authored-By: Claude Opus 5.5 --- bae/optim/optimizer.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/bae/optim/optimizer.py b/bae/optim/optimizer.py index 3e8c024..ae34e84 100644 --- a/bae/optim/optimizer.py +++ b/bae/optim/optimizer.py @@ -129,9 +129,9 @@ def step(self, input, target=None, weight=None): U = sparse.bsr_mm(J0twp, J0wp) V = sparse.bsr_mm(J1twp, J1wp) - if self.matrix_free_normal: - del J0twp, J1twp - else: + # Matrix-free keeps J^T for the J^T products: Warp's bsr_mv(..., transpose=True) + # scatters with atomics and is ~5x slower than a plain bsr_mv on J^T. + if not self.matrix_free_normal: W = sparse.bsr_mm(J0twp, J1wp) Wt = sparse.bsr_transposed(W) del J0twp, J1twp @@ -166,12 +166,12 @@ def step(self, input, target=None, weight=None): if self.matrix_free_normal: def schur_matvec(x, y, z, alpha, beta, _V_i=V_i): sparse.bsr_mv(J0wp, x, y=scratch_obs, beta=0.0) - sparse.bsr_mv(J1wp, scratch_obs, y=scratch_pts, beta=0.0, transpose=True) + sparse.bsr_mv(J1twp, scratch_obs, y=scratch_pts, beta=0.0) sparse.bsr_mv(_V_i, scratch_pts, y=scratch_pts2, beta=0.0) sparse.bsr_mv(J1wp, scratch_pts2, y=scratch_obs, beta=0.0) if z.ptr != y.ptr and beta != 0.0: wp.copy(src=y, dest=z) - sparse.bsr_mv(J0wp, scratch_obs, y=z, alpha=-alpha, beta=beta, transpose=True) + sparse.bsr_mv(J0twp, scratch_obs, y=z, alpha=-alpha, beta=beta) sparse.bsr_mv(U, x, y=z, alpha=alpha, beta=1.0) schur_op = linear.LinearOperator( @@ -188,7 +188,7 @@ def schur_matvec(x, y, z, alpha, beta, _V_i=V_i): wp.copy(src=Ic, dest=rhs_c) sparse.bsr_mv(V_i, Ip, y=scratch_pts2, beta=0.0) sparse.bsr_mv(J1wp, scratch_pts2, y=scratch_obs, beta=0.0) - sparse.bsr_mv(J0wp, scratch_obs, y=rhs_c, alpha=-1.0, beta=1.0, transpose=True) + sparse.bsr_mv(J0twp, scratch_obs, y=rhs_c, alpha=-1.0, beta=1.0) else: WV_i = sparse.bsr_mm(W, V_i) WVi_Wt = sparse.bsr_mm(WV_i, Wt) @@ -219,8 +219,7 @@ def schur_matvec(x, y, z, alpha, beta, _V_i=V_i): if self.matrix_free_normal: sparse.bsr_mv(J0wp, D_c, y=scratch_obs, beta=0.0) - sparse.bsr_mv(J1wp, scratch_obs, y=rhs_p, - alpha=-1.0, beta=1.0, transpose=True) + sparse.bsr_mv(J1twp, scratch_obs, y=rhs_p, alpha=-1.0, beta=1.0) else: sparse.bsr_mv(Wt, D_c, y=rhs_p, alpha=-1.0, beta=1.0)