Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/test-graph-jacobian.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ jobs:

- name: Install dependencies
run: |
python -m pip install --break-system-packages --no-cache-dir --target /tmp/pydeps pytest warp-lang matplotlib
python -m pip install --break-system-packages --no-cache-dir "setuptools>=70.1" wheel packaging
python -m pip install --break-system-packages --no-cache-dir --target /tmp/pydeps pytest
python -m pip install --break-system-packages --no-cache-dir --target /tmp/pydeps --no-deps --no-build-isolation "git+https://github.com/pypose/pypose.git"
env:
PIP_CACHE_DIR: /tmp/pip-cache
Expand All @@ -42,4 +43,4 @@ jobs:
PYTHONPATH: /tmp/pydeps:${{ github.workspace }}
run: |
python -c "import torch; print('torch', torch.__version__)"
python -m pytest -q tests/autograd
python -m pytest -q tests/autograd tests/test_normal_operator.py tests/sparse/tuple
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
build/*
bae.egg-info/*
*.so
*.air
*.metallib
*.pyc
**/bal_data/
.ipynb_checkpoints/*
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@

- **Sparse Block Matrix Operations**: Optimized implementations of sparse matrix operations for large-scale optimization
- **CUDA Acceleration**: Custom CUDA kernels for high-performance sparse linear algebra
- **Apple Silicon Acceleration**: Metal BSR products and matrix-free LM with PCG
- **PyTorch Integration**: Seamlessly integrates with PyTorch's automatic differentiation framework
- **Levenberg-Marquardt Optimizer**: The vanilla LM algorithm for non-linear least squares problems
- **Schur Complement Optimizer**: Solve a Schur-reduce linear system for [optimized memory consumption](https://github.com/pypose/bae/blob/release/doc/memory_performance.md)
Expand All @@ -109,15 +110,15 @@
- [ ] Reduce kernel launching cost in PCG solver by kernel fusion
- [ ] Distributed Tensor (DTensor) and FSDP support for multi-GPU and distributed optimization (WIP in `distributed_dt`)
- [x] Schur complement (added in [PR #35](https://github.com/pypose/bae/pull/35))
- [ ] Add Apple Silicon GPU support, [PyTorch PR WIP](https://github.com/pytorch/pytorch/pull/177757)
- [x] Apple Silicon GPU support through [tuple Jacobians and matrix-free LM](#apple-silicon--mps)
- [ ] **Community-requested features:** Need support for a new framework, hardware backend, or more efficient memory allocation? Open an issue and tell us about your use case; we’d love to hear what you need.


## Installation

### Prerequisites

- CUDA toolkit (tested with CUDA 12.x)
- CUDA toolkit for the CUDA backend (tested with CUDA 12.x)
- PyTorch (2.0+)
- (Optional) [CUDSS](https://developer.nvidia.com/cudss) (CUDA Sparse Solver library)

Expand Down
45 changes: 37 additions & 8 deletions ba_example.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from time import perf_counter
import argparse

import pypose as pp
import torch
Expand Down Expand Up @@ -54,12 +55,36 @@ def least_square_error(camera_params, points, cidx, pidx, observes):
return torch.sum(loss**2, dim=-1).mean()


def main():
dataset = get_problem(TARGET_PROBLEM, TARGET_DATASET)
print(f"Fetched {TARGET_PROBLEM} from {TARGET_DATASET}")
def _synchronize(device):
if device.type == "cuda":
torch.cuda.synchronize(device)
elif device.type == "mps":
torch.mps.synchronize()


def main(argv=None):
parser = argparse.ArgumentParser(description="Bundle adjustment with BAE")
parser.add_argument("--device", choices=("cpu", "cuda", "mps"), default=DEVICE)
parser.add_argument("--dataset", default=TARGET_DATASET)
parser.add_argument("--problem", default=TARGET_PROBLEM)
parser.add_argument("--iterations", type=int, default=20)
args = parser.parse_args(argv)
if args.iterations < 1:
parser.error("--iterations must be positive")
device = torch.device(args.device)
if device.type == "mps":
if not torch.backends.mps.is_available():
parser.error("MPS is unavailable; use an Apple Silicon Mac with MPS-enabled PyTorch")
if device.type == "cuda" and not torch.cuda.is_available():
parser.error("CUDA is unavailable; choose --device mps or --device cpu")
dataset = get_problem(
args.problem, args.dataset,
dtype=torch.float32 if device.type == "mps" else torch.float64,
)
print(f"Fetched {args.problem} from {args.dataset}")

dataset = {
key: value.to(DEVICE)
key: value.to(device)
for key, value in dataset.items()
if isinstance(value, torch.Tensor)
}
Expand All @@ -72,10 +97,13 @@ def main():
model = Residual(
dataset["camera_params"][:, :NUM_CAMERA_PARAMS].clone(),
dataset["points_3d"].clone(),
).to(DEVICE)
).to(device)
strategy = pp.optim.strategy.TrustRegion(up=2.0, down=0.5**4)
solver = PCG(tol=1e-4, maxiter=250)
optimizer = LM(model, strategy=strategy, solver=solver, reject=30)
optimizer = LM(
model, strategy=strategy, solver=solver, reject=30,
matrix_free_normal=device.type in ("cpu", "mps"),
)

print('Loss:', least_square_error(
model.pose,
Expand All @@ -87,12 +115,13 @@ def main():

print("Initial loss", optimizer.model.loss(input, None).item())

_synchronize(device)
start = perf_counter()
for idx in range(20):
for idx in range(args.iterations):
loss = optimizer.step(input)
print("Iteration", idx, "loss", loss.item(), "time", perf_counter() - start)

torch.cuda.synchronize()
_synchronize(device)
end = perf_counter()
print("Time", end - start)

Expand Down
8 changes: 5 additions & 3 deletions bae/autograd/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import torch
from torch.func import jacrev

from ..sparse import warp_wrappers as _warp_wrappers # noqa: F401
from ..utils.parameter import trim_parameter_jacobian_values
from ..sparse.tensor import BSRTensor
from .function import _INDEXED_TRACE_TAG


Expand Down Expand Up @@ -424,19 +424,21 @@ def jacobian_components(output, params):
return tuple(result)


def materialize_jacobian_components(components):
def materialize_jacobian_components(components, *, as_tuple: bool = False):
"""Create sparse BSR tensors while preserving parameter alignment.

An empty component group represents a parameter that does not contribute
to the output and is materialized as ``None``.
``as_tuple`` selects tuple-backed :class:`BSRTensor`.
"""
result = []
for param_components in components:
if len(param_components) == 0:
result.append(None)
continue
sparse_components = [
torch.sparse_bsr_tensor(
BSRTensor(*component[:3], size=component.size, is_coalesced=True)
if as_tuple else torch.sparse_bsr_tensor(
component.crow_indices,
component.col_indices,
component.values,
Expand Down
48 changes: 37 additions & 11 deletions bae/optim/optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,63 @@
from pypose.optim import LevenbergMarquardt as ppLM
import pypose as pp

from ..autograd.graph import jacobian
from ..autograd.graph import jacobian, jacobian_components, materialize_jacobian_components
from ..autograd.function import TrackingTensor
from ..sparse.py_ops import diagonal_op_, inv_op
from ..sparse.spgemm import CuSparse
from ..utils.linear_operator import NormalMatVec
from ..utils.parameter import parameter_update_shape

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
try:
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
except ImportError:
pass


class LM(ppLM):
def __init__(self, *args, matrix_free_normal: bool = False, **kwargs):
self.matrix_free_normal = matrix_free_normal
super(LM, self).__init__(*args, **kwargs)
self.mm = CuSparse()
self.tuple_mode = any(param.device.type == 'mps'
for pg in self.param_groups for param in pg['params'])
if self.tuple_mode and not self.matrix_free_normal:
raise ValueError("MPS optimization requires matrix_free_normal=True.")
if not self.matrix_free_normal:
from ..sparse.spgemm import CuSparse
self.mm = CuSparse()

@torch.no_grad()
def step(self, input, target=None, weight=None):
for pg in self.param_groups:
weight = self.weight if weight is None else weight
R = list(self.model(input))
R = R[0]
J = jacobian(R, pg['params'])
if self.tuple_mode:
J = materialize_jacobian_components(
jacobian_components(R, pg['params']), as_tuple=True,
)
else:
J = jacobian(R, pg['params'])
if len(J) != len(pg['params']) or any(block is None for block in J):
raise ValueError("All optimized parameters must contribute to the residual.")
if isinstance(R, TrackingTensor):
R = R.tensor()
J = torch.cat([j.to_sparse_coo() for j in J], dim=-1).to_sparse_csr()
if self.tuple_mode:
J = torch.cat(J, dim=1)
else:
J = torch.cat([j.to_sparse_coo() for j in J], dim=-1).to_sparse_csr()

self.last = self.loss = self.loss if hasattr(self, 'loss') else self.model.loss(input, target)
self.reject_count = 0

if self.matrix_free_normal:
diag = NormalMatVec._compute_diag(J).clamp(min=pg['min'], max=pg['max'])
A = NormalMatVec(J, damping=0.0, diag=diag)
# for A(x) = J.T @ (J @ x) + (s * diag - raw_diag) * x
# can we avoid keeping both diag and raw_diag?
raw_diag = NormalMatVec._compute_diag(J)
diag = raw_diag.clamp(min=pg['min'], max=pg['max'])
A = NormalMatVec(J, damping=0.0, diag=diag, raw_diag=raw_diag)
rhs = -(A._get_Jt() @ R.view(-1, 1))
diag_scale = 1.0
else:
Expand Down Expand Up @@ -97,6 +118,11 @@ def update_parameter(self, params, step):


class Schur(LM):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.tuple_mode:
raise NotImplementedError("Schur requires native sparse tensors; use LM with PCG for tuple/MPS optimization.")

@torch.no_grad()
def step(self, input, target=None, weight=None):
for pg in self.param_groups:
Expand Down
9 changes: 6 additions & 3 deletions bae/optim/strategy.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import pypose as pp
import warp as wp
from warp import sparse as wpsparse
from bae.sparse.warp_wrappers import format_vec_for_bsr
try:
import warp as wp
from warp import sparse as wpsparse
from bae.sparse.warp_wrappers import format_vec_for_bsr
except ImportError:
pass

class TrustRegion(pp.optim.strategy.TrustRegion):
def update(self, pg, last, loss, J, D, R, *args, **kwargs):
Expand Down
21 changes: 12 additions & 9 deletions bae/sparse/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from importlib import import_module

from .py_ops import *
try:
from .solve import *
except ImportError:
# `bae.sparse.solve` depends on NVIDIA cuDSS. Some environments ship cuDSS built
# against a newer CUDA/cuBLAS (e.g. `libcublas.so.13`), which makes importing
# this package fail even if you don't use the direct solver. Keep the rest of
# the sparse ops usable and let callers opt into `bae.sparse.solve` explicitly.
pass
from .conversion import *
from .tuple_ops import bsr_mv, bsr_diagonal, bsr_transposed
from .tensor import BSRTensor, SparseCat
from .warp_wrappers import *


def __getattr__(name):
module = {'gebsr2csr': '.conversion', 'CuDirectSparseSolver': '.solve',
'cusolvesp': '.solve'}.get(name)
if module is not None:
return getattr(import_module(module, __name__), name)
raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
Loading
Loading