From 1e94d537bb606a882de2efb97f556eb073e45127 Mon Sep 17 00:00:00 2001 From: zitongzhan Date: Sun, 22 Nov 2026 23:22:51 -0500 Subject: [PATCH 1/6] signoff MPS changes on major components --- .gitignore | 2 + bae/autograd/graph.py | 13 +- bae/optim/optimizer.py | 43 ++++-- bae/optim/strategy.py | 9 +- bae/sparse/bsr_mps.metal | 238 +++++++++++++++++++++++++++++ bae/sparse/cusparse_wrapper.cpp | 2 - bae/sparse/py_ops.py | 34 +---- bae/sparse/tuple_ops.py | 252 +++++++++++++++++++++++++++++++ bae/sparse/warp_wrappers.py | 12 +- bae/utils/config.py | 19 +++ bae/utils/pypose_ambient_grad.py | 10 +- bae/utils/pypose_compile.py | 8 +- bae/utils/pysolvers.py | 40 +++++ pyproject.toml | 9 +- requirements.txt | 8 +- setup.py | 131 +++++++++++++++- 16 files changed, 753 insertions(+), 77 deletions(-) create mode 100644 bae/sparse/bsr_mps.metal create mode 100644 bae/sparse/tuple_ops.py create mode 100644 bae/utils/config.py diff --git a/.gitignore b/.gitignore index 74c9859..6ce5f49 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ build/* bae.egg-info/* *.so +*.air +*.metallib *.pyc **/bal_data/ .ipynb_checkpoints/* diff --git a/bae/autograd/graph.py b/bae/autograd/graph.py index f861faa..b65e45f 100644 --- a/bae/autograd/graph.py +++ b/bae/autograd/graph.py @@ -6,8 +6,9 @@ import torch from torch.func import jacrev -from ..sparse import warp_wrappers as _warp_wrappers # noqa: F401 +from ..utils.config import jacobian_tuple_enabled from ..utils.parameter import trim_parameter_jacobian_values +from ..sparse.tensor import BSRTensor from .function import _INDEXED_TRACE_TAG @@ -424,11 +425,12 @@ def jacobian_components(output, params): return tuple(result) -def materialize_jacobian_components(components): +def materialize_jacobian_components(components, *, as_tuple: Optional[bool] = None): """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: @@ -436,7 +438,8 @@ def materialize_jacobian_components(components): 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, @@ -587,6 +590,10 @@ def backward(output_, is_root=False): def jacobian(output, params): + # TODO: should we deprecate this in favor of jacobian_components + materialize_jacobian_components? + if jacobian_tuple_enabled(): + components = jacobian_components(output, params) + return materialize_jacobian_components(components, as_tuple=True) assert output.optrace[0] in ('map', 'index', 'cat'), "Unsupported last operation in compute graph" _clear_jactrace(output, params) try: diff --git a/bae/optim/optimizer.py b/bae/optim/optimizer.py index f122b4c..fb8588f 100644 --- a/bae/optim/optimizer.py +++ b/bae/optim/optimizer.py @@ -6,21 +6,33 @@ from ..autograd.graph import jacobian from ..autograd.function import TrackingTensor from ..sparse.py_ops import diagonal_op_, inv_op -from ..sparse.spgemm import CuSparse +from ..utils.config import jacobian_tuple_enabled 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 + self.tuple_mode = jacobian_tuple_enabled() super(LM, self).__init__(*args, **kwargs) - self.mm = CuSparse() + has_mps = any(param.device.type == 'mps' + for pg in self.param_groups for param in pg['params']) + if not self.matrix_free_normal and (has_mps or self.tuple_mode): + raise ValueError("MPS and tuple Jacobians require matrix_free_normal=True.") + if has_mps and not self.tuple_mode: + raise RuntimeError("MPS optimization requires BAE_JACOBIAN_TUPLE=1.") + 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): @@ -29,16 +41,24 @@ def step(self, input, target=None, weight=None): R = list(self.model(input)) R = R[0] 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: @@ -97,6 +117,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: diff --git a/bae/optim/strategy.py b/bae/optim/strategy.py index 1026a2e..4003d5f 100644 --- a/bae/optim/strategy.py +++ b/bae/optim/strategy.py @@ -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): diff --git a/bae/sparse/bsr_mps.metal b/bae/sparse/bsr_mps.metal new file mode 100644 index 0000000..d078bf3 --- /dev/null +++ b/bae/sparse/bsr_mps.metal @@ -0,0 +1,238 @@ +// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Metal adaptation of NVIDIA Warp release-1.19 sparse.py's make_bsr_mv_kernel, +// make_bsr_mv_tiled_kernel, make_bsr_mv_transpose_kernel and scale kernel: +// https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L4890-L5172 +// +// BAE tuples use compact BSR storage, so Warp's optional row_counts is absent: +// row_end = crow[row + 1], row_count = crow[row + 1] - crow[row]. Blocks are +// row-major. Python integer arguments use int64; alpha and beta use float32. +// All launches flatten Warp's LAST dimension fastest, including transpose. +#include +using namespace metal; + +template +kernel void bsr_mv( + const device Index* crow [[buffer(0)]], + const device Index* col [[buffer(1)]], + const device float* values [[buffer(2)]], + const device float* x [[buffer(3)]], + device float* y [[buffer(4)]], + constant long& nrows [[buffer(5)]], + constant long& br [[buffer(6)]], + constant long& bc [[buffer(7)]], + constant float& alpha [[buffer(8)]], + constant float& beta [[buffer(9)]], + uint tid [[thread_position_in_grid]]) { + const long yi = tid; + // Specializing common BA block dimensions avoids + // runtime integer division when decoding Warp's flattened (row, subrow). + const long height = BlockRows == 0 ? br : BlockRows; + if (yi >= nrows * height) return; + const long row = yi / height; + const long subrow = yi % height; + const long width = BlockCols == 0 ? bc : BlockCols; + float v = 0.0f; + + // Preserve Warp's zero-scale semantics: unused operands may contain NaNs + // or uninitialized memory, and therefore must not be read. + if (alpha != 0.0f) { + for (long block = crow[row]; block < crow[row + 1]; ++block) { + const long xs = long(col[block]) * width; + const long vs = (block * height + subrow) * width; + if (BlockCols != 0) { + #pragma unroll + for (int c = 0; c < BlockCols; ++c) { + v += values[vs + c] * x[xs + c]; + } + } else { + for (long c = 0; c < width; ++c) { + v += values[vs + c] * x[xs + c]; + } + } + } + v *= alpha; + } + if (beta != 0.0f) v += beta * y[yi]; + y[yi] = v; +} + +template +kernel void bsr_mv_tiled( + const device Index* crow [[buffer(0)]], + const device Index* col [[buffer(1)]], + const device float* values [[buffer(2)]], + const device float* x [[buffer(3)]], + device float* y [[buffer(4)]], + constant long& nrows [[buffer(5)]], + constant long& br [[buffer(6)]], + constant long& bc [[buffer(7)]], + constant float& alpha [[buffer(8)]], + constant float& beta [[buffer(9)]], + constant long& tile_size [[buffer(10)]], + uint yi [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_threadgroup]], + uint simd_lane [[thread_index_in_simdgroup]], + uint simd_group [[simdgroup_index_in_threadgroup]], + uint simd_width [[threads_per_simdgroup]]) { + // Launch exactly nrows * br groups, with tile_size lanes in every group. + // The generic variant supports any tile size up to 1024; fixed variants + // make the lane stride and scratch size compile-time constants, as Warp + // does when constructing make_bsr_mv_tiled_kernel(tile_size). + const long lanes = TileSize == 0 ? tile_size : TileSize; + const long height = BlockRows == 0 ? br : BlockRows; + const long width = BlockCols == 0 ? bc : BlockCols; + if (long(yi) >= nrows * height) return; + const long row = long(yi) / height; + const long subrow = long(yi) % height; + threadgroup float partial[TileSize == 0 ? 1024 : TileSize]; + + if (alpha != 0.0f) { + const long block_beg = crow[row]; + const long col_count = (long(crow[row + 1]) - block_beg) * width; + float lane_sum = 0.0f; + for (long c = lane; c < col_count; c += lanes) { + long block = c / width; + const long block_col = c - block * width; + block += block_beg; + const float xi = x[long(col[block]) * width + block_col]; + lane_sum += values[(block * height + subrow) * width + block_col] * xi; + } + lane_sum *= alpha; + + // Warp's tile_sum reduces the lane sums once per (row, subrow). + // Native SIMD reduction followed by one reduction of SIMD partials + // implements that collective without a barrier at every tree level. + const float simd_total = simd_sum(lane_sum); + if (simd_lane == 0) partial[simd_group] = simd_total; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (simd_group == 0) { + const uint simd_count = (uint(lanes) + simd_width - 1) / simd_width; + float total = simd_lane < simd_count ? partial[simd_lane] : 0.0f; + total = simd_sum(total); + if (simd_lane == 0) { + const float initial = beta == 0.0f ? 0.0f : beta * y[yi]; + y[yi] = initial + total; + } + } + } else if (lane == 0) { + y[yi] = beta == 0.0f ? 0.0f : beta * y[yi]; + } +} + +template +kernel void bsr_mv_transpose( + const device Index* crow [[buffer(0)]], + const device Index* col [[buffer(1)]], + const device float* values [[buffer(2)]], + const device float* x [[buffer(3)]], + device atomic_float* y [[buffer(4)]], + constant long& nrows [[buffer(5)]], + constant long& br [[buffer(6)]], + constant long& bc [[buffer(7)]], + constant float& alpha [[buffer(8)]], + constant float& beta [[buffer(9)]], + uint tid [[thread_position_in_grid]]) { + // Warp's dim=(nnz, block_cols) has subcol as its fastest dimension. + // A Metal grid with (nnz, block_cols) reverses that order; flatten it here. + const long block = long(tid) / bc; + const long subcol = long(tid) % bc; + if (alpha == 0.0f || block >= long(crow[nrows])) return; + + // Exact compact-storage bsr_row_index: lower_bound(crow, block+1) - 1. + // This includes leading and consecutive empty rows. + long lo = 0, hi = nrows + 1; + while (lo < hi) { + const long mid = lo + (hi - lo) / 2; + if (long(crow[mid]) < block + 1) lo = mid + 1; + else hi = mid; + } + const long row = lo - 1; + if (row < 0) return; + + const long height = BlockRows == 0 ? br : BlockRows; + float col_sum = 0.0f; + if (BlockRows != 0) { + #pragma unroll + for (int r = 0; r < BlockRows; ++r) { + col_sum += values[(block * height + r) * bc + subcol] * x[row * height + r]; + } + } else { + for (long r = 0; r < height; ++r) { + col_sum += values[(block * height + r) * bc + subcol] * x[row * height + r]; + } + } + // As in Warp, the caller zeroes/scales y by beta before this scatter. + atomic_fetch_add_explicit( + y + long(col[block]) * bc + subcol, alpha * col_sum, memory_order_relaxed); +} + +kernel void bsr_scale( + constant float& beta [[buffer(0)]], + device float* y [[buffer(1)]], + uint tid [[thread_position_in_grid]]) { + y[tid] = beta == 0.0f ? 0.0f : beta * y[tid]; +} + +#define SCALAR_ARGS(Index) \ + const device Index*, const device Index*, const device float*, \ + const device float*, device float*, constant long&, constant long&, constant long&, \ + constant float&, constant float&, uint + +#define TRANSPOSE_ARGS(Index) \ + const device Index*, const device Index*, const device float*, \ + const device float*, device atomic_float*, constant long&, constant long&, constant long&, \ + constant float&, constant float&, uint + +#define TILED_ARGS(Index) \ + const device Index*, const device Index*, const device float*, \ + const device float*, device float*, constant long&, constant long&, constant long&, \ + constant float&, constant float&, constant long&, uint, uint, uint, uint, uint + +#define SPECIALIZE_BLOCK(Index, suffix, N) \ +template [[host_name("bsr_mv_" #suffix "_c" #N)]] \ +kernel void bsr_mv(SCALAR_ARGS(Index)); \ +template [[host_name("bsr_mv_transpose_" #suffix "_r" #N)]] \ +kernel void bsr_mv_transpose(TRANSPOSE_ARGS(Index)); + +#define SPECIALIZE_TILE(Index, suffix, N) \ +template [[host_name("bsr_mv_tiled_" #suffix "_t" #N)]] \ +kernel void bsr_mv_tiled(TILED_ARGS(Index)); + +#define SPECIALIZE_BA(Index, suffix, Rows, Columns) \ +template [[host_name("bsr_mv_" #suffix "_r" #Rows "_c" #Columns)]] \ +kernel void bsr_mv(SCALAR_ARGS(Index)); + +#define SPECIALIZE_BA_TILE(Index, suffix, Rows, Columns, N) \ +template [[host_name("bsr_mv_tiled_" #suffix "_r" #Rows "_c" #Columns "_t" #N)]] \ +kernel void bsr_mv_tiled(TILED_ARGS(Index)); + +#define INSTANTIATE(Index, suffix) \ +template [[host_name("bsr_mv_" #suffix)]] \ +kernel void bsr_mv(SCALAR_ARGS(Index)); \ +template [[host_name("bsr_mv_transpose_" #suffix)]] \ +kernel void bsr_mv_transpose(TRANSPOSE_ARGS(Index)); \ +template [[host_name("bsr_mv_tiled_" #suffix)]] \ +kernel void bsr_mv_tiled(TILED_ARGS(Index)); \ +SPECIALIZE_BLOCK(Index, suffix, 1) \ +SPECIALIZE_BLOCK(Index, suffix, 2) \ +SPECIALIZE_BLOCK(Index, suffix, 3) \ +SPECIALIZE_BLOCK(Index, suffix, 4) \ +SPECIALIZE_BLOCK(Index, suffix, 6) \ +SPECIALIZE_BLOCK(Index, suffix, 7) \ +SPECIALIZE_BLOCK(Index, suffix, 9) \ +SPECIALIZE_BLOCK(Index, suffix, 10) \ +SPECIALIZE_BLOCK(Index, suffix, 12) \ +SPECIALIZE_BLOCK(Index, suffix, 16) \ +SPECIALIZE_TILE(Index, suffix, 32) \ +SPECIALIZE_TILE(Index, suffix, 64) \ +SPECIALIZE_TILE(Index, suffix, 128) \ +SPECIALIZE_TILE(Index, suffix, 256) \ +SPECIALIZE_BA(Index, suffix, 2, 3) \ +SPECIALIZE_BA(Index, suffix, 2, 9) \ +SPECIALIZE_BA(Index, suffix, 3, 2) \ +SPECIALIZE_BA_TILE(Index, suffix, 9, 2, 64) + +INSTANTIATE(int, i32) +INSTANTIATE(long, i64) diff --git a/bae/sparse/cusparse_wrapper.cpp b/bae/sparse/cusparse_wrapper.cpp index 59b355f..0288e4f 100644 --- a/bae/sparse/cusparse_wrapper.cpp +++ b/bae/sparse/cusparse_wrapper.cpp @@ -332,6 +332,4 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { py::class_(m, "CuSparse") .def(py::init<>()) .def("__call__", &CuSparse::cusparse_spgemm, ""); - m.def("convert_indices_from_csr_to_coo", &at::_convert_indices_from_csr_to_coo, "pytorch aten wrapper"); - m.def("convert_indices_from_coo_to_csr", &at::_convert_indices_from_coo_to_csr, "pytorch aten wrapper"); } diff --git a/bae/sparse/py_ops.py b/bae/sparse/py_ops.py index 058daee..2bfcf86 100644 --- a/bae/sparse/py_ops.py +++ b/bae/sparse/py_ops.py @@ -5,13 +5,10 @@ import torch from torch.utils._triton import has_triton -from .spgemm import convert_indices_from_csr_to_coo -USE_TRITON = True +USE_TRITON = torch.cuda.is_available() and has_triton() -if not USE_TRITON: - print("Skipping because triton is not supported on this device.") -else: +if USE_TRITON: import triton from triton import language as tl @@ -78,28 +75,7 @@ def aggr_kernel( valj = tl.load(source + js) output = tl.sum(valj) tl.store(out_ptr + row, output) -def jtj_diag(Jt): - block_shape = Jt.values().shape[-2:] - col_indices = Jt.col_indices() - nnz = col_indices.shape[-1] - crow_indices = Jt.crow_indices() - srows = crow_indices.shape[-1] - 1 - values = Jt.values() - values = values.flatten(start_dim=0, end_dim=1) - dotp = torch.linalg.vecdot(values, values) - cooa = convert_indices_from_csr_to_coo(crow_indices.contiguous(), col_indices.contiguous(), crow_indices.dtype == torch.int32, False) - row_indices = cooa[0] - if block_shape[0] == 1: - ... - else: - row_indices = row_indices * block_shape[0] - row_indices = row_indices.unsqueeze(-1) - offsets = torch.arange(0, block_shape[0], device=row_indices.device, dtype=row_indices.dtype).unsqueeze(0) - row_indices = row_indices + offsets - row_indices = row_indices.flatten() - diag_values = torch.zeros(srows * block_shape[0], device=values.device, dtype=values.dtype) - diag_values.scatter_add_(0, row_indices.to(torch.int64), dotp) - return diag_values + def diagonal_op_(input, offset: int=0, op: Optional[Callable]=None): crow_indices = input.crow_indices() # b + 1 dimensional @@ -114,7 +90,7 @@ def diagonal_op_(input, offset: int=0, op: Optional[Callable]=None): #simple case(block is square and offset is 0) if dm == dn and offset == 0: - if not USE_TRITON: + if not USE_TRITON or input.device.type != 'cuda': dummy_val = torch.zeros(bsr_values.shape[0], device='cpu') dummy = torch.sparse_csr_tensor(crow_indices=crow_indices.to('cpu'), col_indices=col_indices.to('cpu'), @@ -137,7 +113,7 @@ def diagonal_op_(input, offset: int=0, op: Optional[Callable]=None): else: results_shape = (n_diag_blocks, dm) results = torch.zeros(results_shape, dtype=values.dtype, device=values.device) - results[indices[0, diag_indices]] = values + results[col_indices[diag_indices]] = values assert op is None, "op is not supported for diagonal that has empty values." if bsr_values.ndim > 1: results = torch.flatten(results, start_dim=-2, end_dim=-1) diff --git a/bae/sparse/tuple_ops.py b/bae/sparse/tuple_ops.py new file mode 100644 index 0000000..e88bdbe --- /dev/null +++ b/bae/sparse/tuple_ops.py @@ -0,0 +1,252 @@ +"""BSR operations on ordinary tensor tuples, without native sparse tensors.""" + +from functools import lru_cache +from importlib.resources import files +from ctypes import c_float +import math + +import torch + + +def _validate(A, size): + if not isinstance(A, tuple) or len(A) != 3: + raise TypeError("A must be a (crow_indices, col_indices, values) tuple") + crow, col, values = A + if not all(isinstance(t, torch.Tensor) for t in A): + raise TypeError("All BSR components must be tensors") + if crow.ndim != 1 or col.ndim != 1 or values.ndim != 3: + raise ValueError("Expected 1-D crow/col and values shaped (nnz, block_rows, block_cols)") + if crow.dtype not in (torch.int32, torch.int64) or col.dtype != crow.dtype: + raise TypeError("crow and col must have the same int32 or int64 dtype") + if crow.device != values.device or col.device != values.device: + raise ValueError("All BSR components must reside on the same device") + if len(size) != 2 or any(not isinstance(d, int) or d < 0 for d in size): + raise ValueError("size must contain two nonnegative integer dimensions") + br, bc = values.shape[-2:] + if br == 0 or bc == 0 or size[0] % br or size[1] % bc: + raise ValueError("Matrix dimensions must be divisible by positive block dimensions") + if crow.numel() != size[0] // br + 1 or col.numel() != values.shape[0]: + raise ValueError("BSR component shapes do not match size") + if values.dtype not in (torch.float32, torch.float64): + raise TypeError("Tuple BSR operations support float32 and float64 values") + if values.device.type == "mps" and values.dtype != torch.float32: + raise TypeError("MPS tuple BSR operations require float32 values") + return crow, col, values + + +@lru_cache(maxsize=1) +def _metal_library(): + if not hasattr(torch.mps, "load_metallib"): + raise RuntimeError("The MPS backend requires PyTorch 2.13 or newer") + resource = files("bae.sparse").joinpath("bsr_mps.metallib") + if not resource.is_file(): + raise RuntimeError( + "The BAE Metal library is missing. Install the Xcode Metal Toolchain, " + "then rebuild BAE with `python -m pip install --no-build-isolation -e .`." + ) + # Bytes also work for packages accessed through an importlib resource loader. + return torch.mps.load_metallib(resource.read_bytes()) + + +_SPECIALIZED_BLOCK_DIMS = (1, 2, 3, 4, 6, 7, 9, 10, 12, 16) +_SPECIALIZED_TILE_SIZES = (32, 64, 128, 256) + + +def _tile_dispatch(nnz, br, bc, scalar_rows, device_type, tile_size): + """Warp 1.19's exact long-row heuristic, with Metal as a GPU target.""" + if not isinstance(tile_size, int): + raise TypeError("tile_size must be an integer") + if tile_size > 0: + return True, tile_size + if tile_size < 0: + return False, tile_size + tile_size = 64 + return ( + device_type in ("cuda", "mps") + and nnz * br * bc > 2 * tile_size * scalar_rows, + tile_size, + ) + + +def _scale_output(y, beta): + # Warp's transpose path zeroes before accumulation, skips beta==1, and + # launches a separate scale kernel for any other beta. + if beta == 0.0: + y.zero_() + elif beta != 1.0: + if y.device.type == "mps" and y.numel(): + kernel = _metal_library().bsr_scale + kernel(beta, y, threads=y.numel()) + else: + y.mul_(beta) + + +def _check_vector(vector, length, values, name): + if vector.ndim not in (1, 2): + raise ValueError(f"{name} must be a vector, single-column tensor, or 2-D block-vector array") + if vector.numel() != length: + raise ValueError(f"Expected {name} with {length} scalar elements, got {vector.numel()}") + if vector.device != values.device or vector.dtype != values.dtype: + raise ValueError(f"{name} and BSR values must have the same device and dtype") + + +def bsr_mv(A, x, y=None, alpha=1.0, beta=0.0, transpose=False, + work_buffer=None, tile_size=0, *, size): + """Compute ``y := alpha * A @ x + beta * y`` following Warp 1.19. + + ``size`` is the full scalar shape, including unused column blocks. ``A`` + must describe a valid BSR matrix. Transpose uses ``A.T`` and atomic sums, + whose floating-point summation order is nondeterministic on MPS. + + A supplied contiguous ``y`` is mutated and returned. Otherwise an output + is allocated and beta is ignored. Vectors, single-column tensors, and 2-D + block-vector arrays are accepted. Strided ``x`` is copied as a PyTorch + convenience; output/work-buffer arrays must be contiguous. Aliasing x/y + uses temporary storage (or the supplied work_buffer). + + Positive tile_size forces lane-strided tiled reduction, negative disables + it, and zero uses Warp's default 64-lane GPU heuristic. Transpose ignores + tile_size. alpha==0 does not read matrix/vector data; beta==0 does not read + old output data. The source port is based on: + https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L5051-L5172 + """ + crow, col, values = _validate(A, size) + input_length, output_length = size if transpose else size[::-1] + _check_vector(x, input_length, values, "x") + br, bc = values.shape[-2:] + output_block = bc if transpose else br + if y is None: + shape = (output_length,) + if x.ndim == 2: + shape = (output_length, 1) if x.shape[1] == 1 else (output_length // output_block, output_block) + y = values.new_empty(shape) + beta = 0.0 + _check_vector(y, output_length, values, "y") + if not y.is_contiguous(): + raise ValueError("y must be contiguous") + # Warp casts scalars to A.scalar_type before making zero/one decisions. + scalar = (lambda value: c_float(float(value)).value) if values.dtype == torch.float32 else float + alpha, beta = scalar(alpha), scalar(beta) + + if not transpose: + use_tiles, tile_size = _tile_dispatch(values.shape[0], br, bc, size[0], values.device.type, tile_size) + else: + use_tiles = False + + # Copy only when the input will be consumed. Detect shared storage rather + # than just equal starting pointers so overlapping PyTorch views work too. + if alpha != 0.0 and x.numel() and torch._C._overlaps(x, y): + if work_buffer is None: + work_buffer = torch.empty_like(x, memory_format=torch.contiguous_format) + if work_buffer.numel() < x.numel(): + raise ValueError(f"Work buffer size is insufficient; needs at least {x.numel()} elements") + if work_buffer.device != values.device or work_buffer.dtype != values.dtype: + raise ValueError("Work buffer must have the same device and dtype as y") + if not work_buffer.is_contiguous(): + raise ValueError("Work buffer must be contiguous") + if torch._C._overlaps(work_buffer, x) or torch._C._overlaps(work_buffer, y): + raise ValueError("Work buffer must not alias x or y") + saved = work_buffer.reshape(-1)[:x.numel()] + saved.copy_(x.reshape(-1)) + x = saved + + if output_length == 0: + return y + if alpha == 0.0 or values.shape[0] == 0: + _scale_output(y, beta) + if not transpose and alpha != 0.0 and not math.isfinite(alpha): + # Warp's forward row kernel multiplies even an empty row's zero + # sum by alpha. Transpose has no contributing blocks in this case. + y.add_(alpha * 0.0) + return y + + nrows = size[0] // br + vector = x.reshape(-1).contiguous() + output = y.view(-1) + if values.device.type == "mps": + lib = _metal_library() + suffix = "i32" if crow.dtype == torch.int32 else "i64" + args = (crow.contiguous(), col.contiguous(), values.contiguous(), vector, + output, nrows, br, bc, alpha, beta) + if transpose: + _scale_output(output, beta) + specialization = f"_r{br}" if br in _SPECIALIZED_BLOCK_DIMS else "" + kernel = getattr(lib, "bsr_mv_transpose_" + suffix + specialization) + # Warp dim=(nnz, block_cols) has the LAST dimension fastest. + kernel(*args, threads=values.shape[0] * bc, + group_size=min(256, kernel.max_threads_per_threadgroup)) + elif use_tiles: + # Cached BA camera transposes can make both dimensions constant; + # retain the same Warp lane sequence and collective reduction. + if (br, bc) == (9, 2) and tile_size == 64: + specialization = "_r9_c2_t64" + else: + specialization = f"_t{tile_size}" if tile_size in _SPECIALIZED_TILE_SIZES else "" + kernel = getattr(lib, "bsr_mv_tiled_" + suffix + specialization) + if tile_size > min(1024, kernel.max_threads_per_threadgroup): + raise ValueError("tile_size exceeds the Metal kernel's threadgroup limit") + kernel(*args, tile_size, threads=output_length * tile_size, group_size=tile_size) + else: + # BA forward blocks and cached point transposes have fixed shapes. + # Specializing dimensions removes runtime row-decoding division, + # while retaining Warp's scalar row loop and accumulation order. + if br == 2 and bc in (3, 9): + specialization = f"_r2_c{bc}" + elif (br, bc) == (3, 2): + specialization = "_r3_c2" + else: + specialization = f"_c{bc}" if bc in _SPECIALIZED_BLOCK_DIMS else "" + kernel = getattr(lib, "bsr_mv_" + suffix + specialization) + kernel(*args, threads=output_length, + group_size=min(256, kernel.max_threads_per_threadgroup)) + else: + # Dense-tensor fallback has the same affine/output semantics without + # constructing native sparse tensors (CPU/CUDA tuple support). + _scale_output(output, beta) + rows = torch.repeat_interleave( + torch.arange(nrows, device=values.device), + (crow[1:] - crow[:-1]).long(), output_size=values.shape[0], + ) + if transpose: + gathered = vector.reshape(nrows, br)[rows] + products = torch.bmm(values.transpose(1, 2), gathered.unsqueeze(-1)).squeeze(-1) + output.reshape(-1, bc).index_add_(0, col.long(), products, alpha=alpha) + else: + gathered = vector.reshape(-1, bc)[col.long()] + products = torch.bmm(values, gathered.unsqueeze(-1)).squeeze(-1) + sums = values.new_zeros((nrows, br)) + sums.index_add_(0, rows, products) + # Warp scales the completed row sum, including zero empty rows. + output.add_(sums.reshape(-1), alpha=alpha) + return y + + +def bsr_transposed(A, *, size): + """Build a transposed BSR tuple, preserving the full matrix dimensions. + + As with Warp's bsr_transposed + bsr_mv, assembling this once allows repeated + transpose products to use row reduction instead of contended atomic sums. + The returned values own their storage; rebuild after changing A. + """ + crow, col, values = _validate(A, size) + nnz = values.shape[0] + rows = torch.searchsorted( + crow[1:], torch.arange(nnz, device=crow.device, dtype=crow.dtype), right=True, + ) + order = torch.argsort(col, stable=True) + sorted_col = col[order] + boundaries = torch.arange(size[1] // values.shape[-1] + 1, + device=col.device, dtype=col.dtype) + transposed_crow = torch.searchsorted(sorted_col, boundaries).to(crow.dtype) + transposed_col = rows[order].to(col.dtype) + transposed_values = values[order].transpose(-1, -2).contiguous() + return transposed_crow, transposed_col, transposed_values + + +def bsr_diagonal(A, *, size): + """Return diag(A.T @ A); duplicate block coordinates must be coalesced.""" + _, col, values = _validate(A, size) + bc = values.shape[-1] + diagonal = values.new_zeros((size[1] // bc, bc)) + diagonal.index_add_(0, col.long(), values.square().sum(dim=-2)) + return diagonal.reshape(-1) diff --git a/bae/sparse/warp_wrappers.py b/bae/sparse/warp_wrappers.py index dd3f4bb..b4225fc 100644 --- a/bae/sparse/warp_wrappers.py +++ b/bae/sparse/warp_wrappers.py @@ -1,10 +1,14 @@ # https://nvidia.github.io/warp/modules/sparse.html -import warp as wp -from warp import sparse as wps -from warp.optim import linear as wpol import torch -wp.init() + +try: + import warp as wp + from warp import sparse as wps + from warp.optim import linear as wpol + wp.init() +except ImportError: + pass def torchbsr2wp(tbsr): diff --git a/bae/utils/config.py b/bae/utils/config.py new file mode 100644 index 0000000..2a111d5 --- /dev/null +++ b/bae/utils/config.py @@ -0,0 +1,19 @@ +"""Runtime environment flags.""" + +import os + + +def pypose_ambient_grad_enabled() -> bool: + value = os.environ.get("BAE_USE_PYPOSE_AMBIENT_GRAD", "") + return value.lower() in {"1", "true", "yes", "on"} + + +def pypose_torch_compile_enabled() -> bool: + value = os.environ.get("BAE_USE_PYPOSE_TORCH_COMPILE", "") + return value.lower() in {"1", "true", "yes", "on"} + + +def jacobian_tuple_enabled() -> bool: + """Whether Jacobians use tuple-backed BSR tensor storage.""" + value = os.environ.get("BAE_JACOBIAN_TUPLE", "") + return value.lower() in {"1", "true", "yes", "on"} diff --git a/bae/utils/pypose_ambient_grad.py b/bae/utils/pypose_ambient_grad.py index ce25ab8..f565733 100644 --- a/bae/utils/pypose_ambient_grad.py +++ b/bae/utils/pypose_ambient_grad.py @@ -1,14 +1,8 @@ -import os - import torch -_ENV_FLAG = "BAE_USE_PYPOSE_AMBIENT_GRAD" -_PATCH_INSTALLED = False - +from .config import pypose_ambient_grad_enabled -def pypose_ambient_grad_enabled() -> bool: - value = os.environ.get(_ENV_FLAG, "") - return value.lower() in {"1", "true", "yes", "on"} +_PATCH_INSTALLED = False def _pm(input: torch.Tensor) -> torch.Tensor: diff --git a/bae/utils/pypose_compile.py b/bae/utils/pypose_compile.py index 0702980..9cf8c7d 100644 --- a/bae/utils/pypose_compile.py +++ b/bae/utils/pypose_compile.py @@ -1,22 +1,16 @@ from __future__ import annotations -import os import warnings from importlib import import_module import torch from torch.utils._pytree import tree_flatten, tree_map +from .config import pypose_torch_compile_enabled -_ENV_FLAG = "BAE_USE_PYPOSE_TORCH_COMPILE" _PATCH_INSTALLED = False -def pypose_torch_compile_enabled() -> bool: - value = os.environ.get(_ENV_FLAG, "") - return value.lower() in {"1", "true", "yes", "on"} - - def install_pypose_torch_compile_monkeypatch() -> bool: """Make PyPose's ``LieTensor`` traceable by TorchDynamo. diff --git a/bae/utils/pysolvers.py b/bae/utils/pysolvers.py index 0a61e3e..74d87a4 100644 --- a/bae/utils/pysolvers.py +++ b/bae/utils/pysolvers.py @@ -37,6 +37,46 @@ def forward(self, A, b, x=None, M=None) -> torch.Tensor: res = res.squeeze(-1) return res + def _forward_mps(self, A, b, x, M): + # TODO: Upstream these scalar reductions to PyPose CG, then remove this + # duplicate loop and delegate to super().forward on MPS as well. + # Preserve PyPose CG's recurrence, stopping checks, output-buffer use, + # and in-place warm-start updates. For a real single-column RHS, its + # two 1xN @ Nx1 products are scalar reductions. The equivalent + # multiply-and-sum avoids the slow MPS matrix-multiply dispatch. + if x is None: + x = torch.zeros_like(b) + elif x.shape != b.shape: + raise ValueError("x must have the same shape as b") + + bnrm2 = torch.linalg.norm(b, dim=0) + if (bnrm2 == 0).all(): + return b + atol = self.tol * bnrm2 + maxiter = b.shape[-2] * 10 if self.maxiter is None else self.maxiter + r = b - A @ x if x.any() else b.clone() + q, z = torch.empty_like(b), torch.empty_like(b) + rho_prev, p = None, None + + for iteration in range(maxiter): + if (torch.linalg.norm(r, dim=0) < atol).all(): + return x + + torch.matmul(M, r, out=z) + rho_cur = (r * z).sum(dim=0, keepdim=True) + if iteration: + p.mul_(rho_cur / rho_prev).add_(z) + else: + p = z.clone() + + torch.matmul(A, p, out=q) + alpha = rho_cur / (p * q).sum(dim=0, keepdim=True) + x += alpha * p + r -= alpha * q + rho_prev = rho_cur + + return x + class SciPySpSolver(torch.nn.Module): def __init__(self, ): super().__init__() diff --git a/pyproject.toml b/pyproject.toml index 3769547..66c841c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,10 @@ [build-system] -requires = ["setuptools", "wheel", "torch", "warp-lang>=1.13.0"] +# Build environment only; installed runtime dependencies are in setup.py. +requires = [ + "setuptools>=70.1", + "wheel", + "packaging", + "torch>=2.13; sys_platform == 'darwin' and platform_machine == 'arm64'", + "torch; sys_platform != 'darwin' or platform_machine != 'arm64'", +] build-backend = "setuptools.build_meta" diff --git a/requirements.txt b/requirements.txt index f84f63b..a17506f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,6 @@ -scipy -matplotlib +# Development and test tools; runtime dependencies are declared in setup.py. pytest -warp-lang +torchvision +setuptools>=70.1 +wheel +packaging diff --git a/setup.py b/setup.py index 785b662..871f35b 100644 --- a/setup.py +++ b/setup.py @@ -1,14 +1,112 @@ import os +import platform import site +import subprocess +import sys import sysconfig from importlib.metadata import PackageNotFoundError, version as get_installed_version +from pathlib import Path from packaging.specifiers import SpecifierSet from packaging.version import Version -from setuptools import setup, find_packages -from torch.utils.cpp_extension import CUDAExtension, BuildExtension +from setuptools import Command, setup, find_packages +from setuptools.command.bdist_wheel import bdist_wheel +from setuptools.command.build import build +from setuptools.errors import CompileError +import torch +from torch.utils.cpp_extension import CUDA_HOME, CUDAExtension, BuildExtension VERSION = "0.2.6" SUPPORTED_CUDSS_SPECIFIER = SpecifierSet("<0.9") +METAL_SOURCE = Path("bae/sparse/bsr_mps.metal") +METAL_LIBRARY = METAL_SOURCE.with_suffix(".metallib") + + +def build_metal_enabled(): + return sys.platform == "darwin" and platform.machine() == "arm64" + + +def build_cuda_enabled(): + # A GPU need not be visible to build a CUDA wheel (for example, in CI). + return not build_metal_enabled() and CUDA_HOME is not None and torch.version.cuda is not None + + +def metal_deployment_target(): + target = Version(os.environ.get("MACOSX_DEPLOYMENT_TARGET", "14.0")) + target = max(target, Version("14.0")) + return f"{target.major}.{target.minor}" + + +class BuildMetal(Command): + """Build the Metal library for both regular and PEP 660 editable installs.""" + + user_options = [] + editable_mode = False + + def initialize_options(self): + self.build_lib = None + self.build_temp = None + + def finalize_options(self): + self.set_undefined_options( + "build", ("build_lib", "build_lib"), ("build_temp", "build_temp") + ) + + def get_source_files(self): + return [str(METAL_SOURCE)] + + def get_outputs(self): + return [str(Path(self.build_lib) / METAL_LIBRARY)] if build_metal_enabled() else [] + + def get_output_mapping(self): + if self.editable_mode and build_metal_enabled(): + return {self.get_outputs()[0]: str(METAL_LIBRARY)} + return {} + + def run(self): + if not build_metal_enabled(): + return + if Version(torch.__version__.split("+")[0]) < Version("2.13") or not hasattr(torch.mps, "load_metallib"): + raise CompileError("Building BAE for MPS requires PyTorch >= 2.13 with torch.mps.load_metallib.") + + output = METAL_LIBRARY if self.editable_mode else Path(self.get_outputs()[0]) + intermediate = Path(self.build_temp) / "bsr_mps.air" + if self.dry_run: + return + output.parent.mkdir(parents=True, exist_ok=True) + intermediate.parent.mkdir(parents=True, exist_ok=True) + commands = [ + [ + "xcrun", "-sdk", "macosx", "metal", "-std=metal3.0", + f"-mmacosx-version-min={metal_deployment_target()}", + "-c", str(METAL_SOURCE), "-o", str(intermediate), + ], + ["xcrun", "-sdk", "macosx", "metallib", str(intermediate), "-o", str(output)], + ] + try: + for command in commands: + subprocess.run(command, check=True) + except (OSError, subprocess.CalledProcessError) as error: + raise CompileError( + "Could not compile BAE's Metal kernels. Install Xcode and its Metal Toolchain " + "(`xcodebuild -downloadComponent MetalToolchain`), then reinstall BAE." + ) from error + + +class BuildWithMetal(build): + sub_commands = build.sub_commands + [("build_metal", None)] + + +class PlatformWheel(bdist_wheel): + def finalize_options(self): + super().finalize_options() + if build_metal_enabled(): + self.root_is_pure = False + + def get_tag(self): + if build_metal_enabled(): + target = metal_deployment_target().replace(".", "_") + return "py3", "none", f"macosx_{target}_arm64" + return super().get_tag() def readme(): """Read the README.md file for long description""" @@ -99,7 +197,10 @@ def resolve_cudss_link_inputs(cudss_root): return libraries, extra_link_args, nvcc_args -if __name__ == '__main__': +def cuda_extensions(): + if not build_cuda_enabled(): + return [] + if USE_CUDSS: validate_cudss_packages(SUPPORTED_CUDSS_SPECIFIER) @@ -160,18 +261,26 @@ def resolve_cudss_link_inputs(cudss_root): library_dirs=library_dirs, ) ) + return ext_modules + +if __name__ == '__main__': setup( name = 'bae', version = VERSION, description = 'PyTorch implementation of BA', long_description = readme(), long_description_content_type = "text/markdown", + license_files=["LICENSE", "third_party/warp/LICENSE.md", "third_party/warp/ORIGIN.txt"], python_requires = ">=3.8", install_requires=[ - 'torch', - 'torchvision', - 'warp-lang', + 'torch>=2.13; sys_platform == "darwin" and platform_machine == "arm64"', + 'torch; sys_platform != "darwin" or platform_machine != "arm64"', + 'numpy', + 'scipy', + 'matplotlib', + 'pillow', + 'warp-lang>=1.13.0; sys_platform != "darwin"', ], packages=find_packages(exclude=['./ba_example.py', './setup.py', @@ -183,6 +292,12 @@ def resolve_cudss_link_inputs(cudss_root): './datapipes', './examples', './tests',]), - ext_modules=ext_modules, - cmdclass={'build_ext': BuildExtension} + ext_modules=cuda_extensions(), + package_data={'bae.sparse': ['*.metal']}, + cmdclass={ + 'build': BuildWithMetal, + 'build_metal': BuildMetal, + 'build_ext': BuildExtension, + 'bdist_wheel': PlatformWheel, + }, ) From 6fc2add71f9c9ebfba03bcf28b6f82e6db9d12a3 Mon Sep 17 00:00:00 2001 From: zitongzhan Date: Wed, 25 Nov 2026 00:31:18 -0500 Subject: [PATCH 2/6] add dtype parameter to read_bal_data and update related functions --- README.md | 5 +++-- ba_example.py | 45 +++++++++++++++++++++++++++++++++------- bae/utils/pysolvers.py | 24 ++++++++++++++------- datapipes/bal_io.py | 11 +++++----- datapipes/bal_loader.py | 6 +++--- tests/sparse/test_bsr.py | 1 + 6 files changed, 66 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 381d40a..f2808fd 100644 --- a/README.md +++ b/README.md @@ -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) @@ -109,7 +110,7 @@ - [ ] 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. @@ -117,7 +118,7 @@ ### 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) diff --git a/ba_example.py b/ba_example.py index 28ff359..884818e 100644 --- a/ba_example.py +++ b/ba_example.py @@ -1,4 +1,5 @@ from time import perf_counter +import argparse import pypose as pp import torch @@ -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) } @@ -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, @@ -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) diff --git a/bae/utils/pysolvers.py b/bae/utils/pysolvers.py index 74d87a4..29b92cb 100644 --- a/bae/utils/pysolvers.py +++ b/bae/utils/pysolvers.py @@ -2,7 +2,8 @@ import torch from torch import Tensor from pypose.optim.solver import CG -from bae.sparse.py_ops import spdiags_ +from .linear_operator import DiagonalMatVec +from ..sparse import py_ops as _py_ops # Registers native sparse diagonal dispatch. try: from bae.sparse.solve import CuDirectSparseSolver as CuDSS @@ -20,19 +21,26 @@ def __init__(self, *args, **kwargs): class PCG(CG): + """Diagonally preconditioned CG with scalar reductions for MPS solves.""" + def __init__(self, maxiter=None, tol=1e-5): super().__init__(maxiter, tol) def forward(self, A, b, x=None, M=None) -> torch.Tensor: was_vector = b.dim() == 1 if was_vector: b = b[..., None] - l_diag = A.diagonal() - l_diag[l_diag.abs() < 1e-6] = 1e-6 - M = spdiags_((1 / l_diag), None, shape=A.shape, layout=None) - if A.layout == torch.sparse_bsr: - M = M.to_sparse_bsr(blocksize=A.values().shape[-2:]).to(A.device) - - res = super().forward(A, b, x, M) + if x is not None and x.dim() == 1: + x = x[..., None] + if M is None: + l_diag = A.diagonal().clone() + l_diag[l_diag.abs() < 1e-6] = 1e-6 + M = DiagonalMatVec(l_diag.reciprocal()) + + if (b.device.type == 'mps' and b.dtype == torch.float32 + and A.ndim == 2 and b.ndim == 2 and b.shape[-1] == 1): + res = self._forward_mps(A, b, x, M) + else: + res = super().forward(A, b, x, M) if was_vector: res = res.squeeze(-1) return res diff --git a/datapipes/bal_io.py b/datapipes/bal_io.py index 7d99928..0bac8fe 100644 --- a/datapipes/bal_io.py +++ b/datapipes/bal_io.py @@ -17,9 +17,10 @@ def _rotvec_to_quat_xyzw(rotvec: torch.Tensor) -> torch.Tensor: return torch.cat([xyz, cos_half], dim=-1) -def read_bal_data(file_name: str, use_quat: bool = True) -> dict: +def read_bal_data(file_name: str, use_quat: bool = True, *, dtype: torch.dtype = DTYPE) -> dict: """ Read a Bundle Adjustment in the Large dataset problem text file. + Floating-point tensors use ``dtype`` (default: torch.float64); indices use torch.int64. Format: @@ -37,7 +38,7 @@ def read_bal_data(file_name: str, use_quat: bool = True) -> dict: camera_indices = torch.empty(n_observations, dtype=torch.int64) point_indices = torch.empty(n_observations, dtype=torch.int64) - points_2d = torch.empty((n_observations, 2), dtype=DTYPE) + points_2d = torch.empty((n_observations, 2), dtype=dtype) for i in range(n_observations): camera_index, point_index, x, y = file.readline().split() @@ -46,12 +47,12 @@ def read_bal_data(file_name: str, use_quat: bool = True) -> dict: points_2d[i, 0] = float(x) points_2d[i, 1] = float(y) - camera_params = torch.empty(n_cameras * 9, dtype=DTYPE) + camera_params = torch.empty(n_cameras * 9, dtype=dtype) for i in range(n_cameras * 9): camera_params[i] = float(file.readline()) camera_params = camera_params.reshape((n_cameras, 9)) - points_3d = torch.empty(n_points * 3, dtype=DTYPE) + points_3d = torch.empty(n_points * 3, dtype=dtype) for i in range(n_points * 3): points_3d[i] = float(file.readline()) points_3d = points_3d.reshape((n_points, 3)) @@ -64,7 +65,7 @@ def read_bal_data(file_name: str, use_quat: bool = True) -> dict: return { "problem_name": os.path.splitext(os.path.basename(file_name))[0], - "camera_params": camera_params.to(DTYPE), + "camera_params": camera_params.to(dtype), "points_3d": points_3d, "points_2d": points_2d, "camera_index_of_observations": camera_indices, diff --git a/datapipes/bal_loader.py b/datapipes/bal_loader.py index 90d9531..f5b692b 100644 --- a/datapipes/bal_loader.py +++ b/datapipes/bal_loader.py @@ -16,7 +16,7 @@ from pathlib import Path from urllib.parse import urljoin -from .bal_io import read_bal_data +from .bal_io import DTYPE, read_bal_data __all__ = ['get_problem', 'read_bal_data', 'DATA_URL', 'ALL_DATASETS'] @@ -83,9 +83,9 @@ def _ensure_problem_available(dataset: str, problem_name: str, cache_dir: Path) os.replace(tmp_path, txt_path) return txt_path -def get_problem(problem_name, dataset, cache_dir='bal_data', use_quat=True): +def get_problem(problem_name, dataset, cache_dir='bal_data', use_quat=True, *, dtype=DTYPE): cache_path = Path(cache_dir) print(f"Preparing data for {dataset}...") _validate_dataset(dataset) problem_path = _ensure_problem_available(dataset, problem_name, cache_path) - return read_bal_data(str(problem_path), use_quat=use_quat) + return read_bal_data(str(problem_path), use_quat=use_quat, dtype=dtype) diff --git a/tests/sparse/test_bsr.py b/tests/sparse/test_bsr.py index be59b00..a76a96b 100644 --- a/tests/sparse/test_bsr.py +++ b/tests/sparse/test_bsr.py @@ -42,6 +42,7 @@ def sp_diag_clamp_inp(x): return x class TestBSR: + @pytest.mark.skipif(not torch.cuda.is_available(), reason='CUDA required for native sparse operators') @pytest.mark.parametrize('device', ['cuda']) @pytest.mark.parametrize('block_prob', [0.0, 0.5, 1.0]) @pytest.mark.parametrize('zero_prob', [0., 0.7, 1.0]) From 396fe1865346791750948a00f70bebb7a2e58ea4 Mon Sep 17 00:00:00 2001 From: zitongzhan Date: Wed, 25 Nov 2026 00:32:42 -0500 Subject: [PATCH 3/6] deprecate the tuple mode env flag --- bae/autograd/graph.py | 7 +------ bae/optim/optimizer.py | 21 +++++++++++---------- bae/utils/config.py | 19 ------------------- bae/utils/pypose_ambient_grad.py | 10 ++++++++-- bae/utils/pypose_compile.py | 8 +++++++- 5 files changed, 27 insertions(+), 38 deletions(-) delete mode 100644 bae/utils/config.py diff --git a/bae/autograd/graph.py b/bae/autograd/graph.py index b65e45f..714b6d6 100644 --- a/bae/autograd/graph.py +++ b/bae/autograd/graph.py @@ -6,7 +6,6 @@ import torch from torch.func import jacrev -from ..utils.config import jacobian_tuple_enabled from ..utils.parameter import trim_parameter_jacobian_values from ..sparse.tensor import BSRTensor from .function import _INDEXED_TRACE_TAG @@ -425,7 +424,7 @@ def jacobian_components(output, params): return tuple(result) -def materialize_jacobian_components(components, *, as_tuple: Optional[bool] = None): +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 @@ -590,10 +589,6 @@ def backward(output_, is_root=False): def jacobian(output, params): - # TODO: should we deprecate this in favor of jacobian_components + materialize_jacobian_components? - if jacobian_tuple_enabled(): - components = jacobian_components(output, params) - return materialize_jacobian_components(components, as_tuple=True) assert output.optrace[0] in ('map', 'index', 'cat'), "Unsupported last operation in compute graph" _clear_jactrace(output, params) try: diff --git a/bae/optim/optimizer.py b/bae/optim/optimizer.py index fb8588f..2795374 100644 --- a/bae/optim/optimizer.py +++ b/bae/optim/optimizer.py @@ -3,10 +3,9 @@ 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 ..utils.config import jacobian_tuple_enabled from ..utils.linear_operator import NormalMatVec from ..utils.parameter import parameter_update_shape @@ -22,14 +21,11 @@ class LM(ppLM): def __init__(self, *args, matrix_free_normal: bool = False, **kwargs): self.matrix_free_normal = matrix_free_normal - self.tuple_mode = jacobian_tuple_enabled() super(LM, self).__init__(*args, **kwargs) - has_mps = any(param.device.type == 'mps' - for pg in self.param_groups for param in pg['params']) - if not self.matrix_free_normal and (has_mps or self.tuple_mode): - raise ValueError("MPS and tuple Jacobians require matrix_free_normal=True.") - if has_mps and not self.tuple_mode: - raise RuntimeError("MPS optimization requires BAE_JACOBIAN_TUPLE=1.") + 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() @@ -40,7 +36,12 @@ def step(self, input, target=None, weight=None): 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): diff --git a/bae/utils/config.py b/bae/utils/config.py deleted file mode 100644 index 2a111d5..0000000 --- a/bae/utils/config.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Runtime environment flags.""" - -import os - - -def pypose_ambient_grad_enabled() -> bool: - value = os.environ.get("BAE_USE_PYPOSE_AMBIENT_GRAD", "") - return value.lower() in {"1", "true", "yes", "on"} - - -def pypose_torch_compile_enabled() -> bool: - value = os.environ.get("BAE_USE_PYPOSE_TORCH_COMPILE", "") - return value.lower() in {"1", "true", "yes", "on"} - - -def jacobian_tuple_enabled() -> bool: - """Whether Jacobians use tuple-backed BSR tensor storage.""" - value = os.environ.get("BAE_JACOBIAN_TUPLE", "") - return value.lower() in {"1", "true", "yes", "on"} diff --git a/bae/utils/pypose_ambient_grad.py b/bae/utils/pypose_ambient_grad.py index f565733..ce25ab8 100644 --- a/bae/utils/pypose_ambient_grad.py +++ b/bae/utils/pypose_ambient_grad.py @@ -1,10 +1,16 @@ -import torch +import os -from .config import pypose_ambient_grad_enabled +import torch +_ENV_FLAG = "BAE_USE_PYPOSE_AMBIENT_GRAD" _PATCH_INSTALLED = False +def pypose_ambient_grad_enabled() -> bool: + value = os.environ.get(_ENV_FLAG, "") + return value.lower() in {"1", "true", "yes", "on"} + + def _pm(input: torch.Tensor) -> torch.Tensor: return torch.sign(torch.sign(input) * 2 + 1) diff --git a/bae/utils/pypose_compile.py b/bae/utils/pypose_compile.py index 9cf8c7d..0702980 100644 --- a/bae/utils/pypose_compile.py +++ b/bae/utils/pypose_compile.py @@ -1,16 +1,22 @@ from __future__ import annotations +import os import warnings from importlib import import_module import torch from torch.utils._pytree import tree_flatten, tree_map -from .config import pypose_torch_compile_enabled +_ENV_FLAG = "BAE_USE_PYPOSE_TORCH_COMPILE" _PATCH_INSTALLED = False +def pypose_torch_compile_enabled() -> bool: + value = os.environ.get(_ENV_FLAG, "") + return value.lower() in {"1", "true", "yes", "on"} + + def install_pypose_torch_compile_monkeypatch() -> bool: """Make PyPose's ``LieTensor`` traceable by TorchDynamo. From b1383264a5e48ef5645a51870cee5e7d9fc5a7f9 Mon Sep 17 00:00:00 2001 From: zitongzhan Date: Wed, 25 Nov 2026 00:43:41 -0500 Subject: [PATCH 4/6] the deps are not needed because pip install does it. --- .github/workflows/test-graph-jacobian.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test-graph-jacobian.yml b/.github/workflows/test-graph-jacobian.yml index 5fd81e0..53fff77 100644 --- a/.github/workflows/test-graph-jacobian.yml +++ b/.github/workflows/test-graph-jacobian.yml @@ -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 @@ -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/test_normal_diagonal_consistency.py tests/test_tuple_normal_operator.py tests/test_mps_pcg.py tests/sparse/test_tuple_ops.py tests/sparse/test_sparse_tensor.py tests/test_build.py From 90b752e97bb57ba8a8f4234185f2a943ad360eb5 Mon Sep 17 00:00:00 2001 From: zitongzhan Date: Wed, 25 Nov 2026 01:07:11 -0500 Subject: [PATCH 5/6] migrate licenses --- bae/sparse/bsr_mps.metal | 11 +- bae/sparse/tensor.py | 270 +++++++++++++++++++++++++++++++++++ bae/sparse/tuple_ops.py | 2 + bae/utils/linear_operator.py | 139 ++++++++++-------- setup.py | 2 +- third_party/warp/LICENSE.md | 203 ++++++++++++++++++++++++++ 6 files changed, 566 insertions(+), 61 deletions(-) create mode 100644 bae/sparse/tensor.py create mode 100644 third_party/warp/LICENSE.md diff --git a/bae/sparse/bsr_mps.metal b/bae/sparse/bsr_mps.metal index d078bf3..5fdf118 100644 --- a/bae/sparse/bsr_mps.metal +++ b/bae/sparse/bsr_mps.metal @@ -1,9 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // -// Metal adaptation of NVIDIA Warp release-1.19 sparse.py's make_bsr_mv_kernel, -// make_bsr_mv_tiled_kernel, make_bsr_mv_transpose_kernel and scale kernel: -// https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L4890-L5172 +// Metal adaptation of NVIDIA Warp release-1.19 sparse matrix-vector kernels. +// Changes: Metal thread dispatch, SIMD reductions and float32 atomic accumulation. +// License text: third_party/warp/LICENSE.md. // // BAE tuples use compact BSR storage, so Warp's optional row_counts is absent: // row_end = crow[row + 1], row_count = crow[row + 1] - crow[row]. Blocks are @@ -12,6 +12,7 @@ #include using namespace metal; +// https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L4884-L4923 template kernel void bsr_mv( const device Index* crow [[buffer(0)]], @@ -58,6 +59,7 @@ kernel void bsr_mv( y[yi] = v; } +// https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L4925-L4974 template kernel void bsr_mv_tiled( const device Index* crow [[buffer(0)]], @@ -121,6 +123,7 @@ kernel void bsr_mv_tiled( } } +// https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L4976-L5006 template kernel void bsr_mv_transpose( const device Index* crow [[buffer(0)]], @@ -142,6 +145,7 @@ kernel void bsr_mv_transpose( // Exact compact-storage bsr_row_index: lower_bound(crow, block+1) - 1. // This includes leading and consecutive empty rows. + // https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L2090-L2130 long lo = 0, hi = nrows + 1; while (lo < hi) { const long mid = lo + (hi - lo) / 2; @@ -168,6 +172,7 @@ kernel void bsr_mv_transpose( y + long(col[block]) * bc + subcol, alpha * col_sum, memory_order_relaxed); } +// https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L3375-L3382 kernel void bsr_scale( constant float& beta [[buffer(0)]], device float* y [[buffer(1)]], diff --git a/bae/sparse/tensor.py b/bae/sparse/tensor.py new file mode 100644 index 0000000..e6eddc5 --- /dev/null +++ b/bae/sparse/tensor.py @@ -0,0 +1,270 @@ +"""Tensor interfaces for component-backed BSR matrices and their concatenation.""" + +import torch + +from . import tuple_ops + + +class _SparseTensor(torch.Tensor): + # Dense storage belongs to the components, not the wrapper. Returning plain + # tensors from matmul is essential: Tensor's default torch_function would + # otherwise wrap the result without initializing our component attributes. + __torch_function__ = torch._C._disabled_torch_function_impl + + @staticmethod + def _new(cls, size, reference): + return torch.Tensor._make_wrapper_subclass( + cls, tuple(size), dtype=reference.dtype, device=reference.device, + requires_grad=False, + ) + + def __repr__(self): + return f"{type(self).__name__}(size={tuple(self.shape)}, dtype={self.dtype}, device='{self.device}')" + + @classmethod + def __torch_dispatch__(cls, func, types, args=(), kwargs=None): + kwargs = {} if kwargs is None else kwargs + aten = torch.ops.aten + if func in (aten.mv.default, aten.mv.out, aten.mm.default, aten.mm.out): + matrix, x = args + if isinstance(matrix, _SparseTensor) and not isinstance(x, _SparseTensor): + return matrix.matvec(x, out=kwargs.get("out")) + elif func is aten.add.Tensor: + left, right = args + if isinstance(left, BSRTensor) and isinstance(right, BSRTensor): + return left._add(right, kwargs.get("alpha", 1)) + elif func is aten.cat.default: + return SparseCat(args[0], dim=args[1] if len(args) > 1 else 0) + elif func in (aten.t.default, aten.mT.default, aten.transpose.int, aten.permute.default): + matrix = args[0] + if func is aten.transpose.int: + if any(dim not in (-2, -1, 0, 1) for dim in args[1:]): + raise IndexError("Sparse matrix transpose dimensions must be 0 or 1") + if args[1] % 2 == args[2] % 2: + return matrix.detach() + if func is aten.permute.default and tuple(args[1]) not in ((1, 0), (-1, -2)): + if tuple(args[1]) in ((0, 1), (-2, -1)): + return matrix.detach() + raise NotImplementedError("Sparse matrix permutation must swap its two dimensions") + return matrix._transpose() + elif func in (aten.detach.default, aten.clone.default, aten._to_copy.default): + return args[0]._map_components(func, kwargs) + raise NotImplementedError(f"{func} is not supported for {cls.__name__}") + + def matvec(self, x, out=None): + if x.ndim not in (1, 2) or x.shape[0] != self.shape[1]: + raise ValueError("x must be a vector or matrix with compatible leading dimension") + if x.device != self.device or x.dtype != self.dtype: + raise ValueError("x must have the matrix's device and dtype") + shape = (self.shape[0], *x.shape[1:]) + if out is None: + out = x.new_empty(shape) + elif out.shape != shape or out.device != self.device or out.dtype != self.dtype: + raise ValueError("out must have the result's shape, device, and dtype") + elif not out.is_contiguous(): + raise ValueError("out must be contiguous") + if torch._C._overlaps(x, out): + x = x.clone() + if x.ndim == 2 and x.shape[1] != 1: + if x.shape[1]: + out.copy_(torch.stack([self.matvec(column) for column in x.unbind(1)], dim=1)) + else: + self._mv(x, out, beta=0) + return out + + +class BSRTensor(_SparseTensor): + """BSR matrix backed by dense tensors, including on MPS. + + ``size`` is mandatory so empty rows and unused trailing columns survive. + The wrapper is intended for fixed solver linearizations, not autograd. + Components are exposed through the native sparse Tensor accessors. Stored + transposes are cached and refreshed after ordinary component mutations. + Transposed component arrays own their storage; update the source matrix's + components to change the matrix rather than writing to its transpose. + """ + + @staticmethod + def __new__(cls, crow_indices, col_indices, values, *, size, is_coalesced=False): + components = (crow_indices, col_indices, values) + tuple_ops._validate(components, size) + result = cls._new(cls, size, values) + result._components = components + result._source = None + result._transposed_components = None + result._source_versions = None + result._canonical_versions = result._index_versions() if is_coalesced else None + return result + + @property + def components(self): + if self._source is not None: + source = self._source.components + versions = tuple(t._version for t in source) + if self._source_versions != versions: + cached = self._source._transposed_components + if cached is None or cached[0] != versions: + cached = (versions, tuple_ops.bsr_transposed(source, size=self._source.shape)) + self._source._transposed_components = cached + self._components = cached[1] + self._source_versions = versions + self._canonical_versions = ( + self._index_versions() if self._source.is_coalesced() else None + ) + return self._components + + def crow_indices(self): + return self.components[0] + + def col_indices(self): + return self.components[1] + + def values(self): + return self.components[2] + + def _index_versions(self): + return tuple(t._version for t in self._components[:2]) + + def is_coalesced(self): + self.components + return self._canonical_versions == self._index_versions() + + def coalesce(self): + return self if self.is_coalesced() else self._combine([self]) + + @staticmethod + def _combine(matrices, alpha=1): + # PyTorch implementation of Warp's duplicate block accumulation semantics: + # https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L1226-L1273 + # https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L1417-L1713 + first = matrices[0] + parts = [matrix.components for matrix in matrices] + columns = torch.cat([part[1] for part in parts]) + values = torch.cat([part[2] if i == 0 else part[2] * alpha + for i, part in enumerate(parts)]) + if not columns.numel(): + return BSRTensor(parts[0][0].to(columns.dtype), columns, values, + size=first.shape, is_coalesced=True) + rows = torch.cat([ + torch.searchsorted(crow[1:], torch.arange(value.shape[0], device=value.device, + dtype=crow.dtype), right=True) + for crow, _, value in parts + ]) + ncols = first.shape[1] // values.shape[-1] + keys = rows.long() * ncols + columns.long() + order = torch.argsort(keys, stable=True) + keys, values = keys[order], values[order] + starts = torch.cat([torch.ones(1, dtype=torch.bool, device=keys.device), keys[1:] != keys[:-1]]) + unique_keys = keys[starts] + groups = starts.long().cumsum(0) - 1 + combined = values.new_zeros((unique_keys.numel(), *values.shape[1:])) + combined.index_add_(0, groups, values) + boundaries = torch.arange(first.shape[0] // values.shape[-2] + 1, + device=columns.device, dtype=torch.int64) + crow = torch.searchsorted(unique_keys // ncols, boundaries).to(columns.dtype) + col = (unique_keys % ncols).to(columns.dtype) + return BSRTensor(crow, col, combined, size=first.shape, is_coalesced=True) + + def _add(self, other, alpha): + if self.shape != other.shape or self.values().shape[1:] != other.values().shape[1:]: + raise ValueError("BSR addition requires matching matrix and block shapes") + if self.device != other.device or self.dtype != other.dtype: + raise ValueError("BSR addition requires matching devices and dtypes") + return self._combine([self, other], alpha) + + def _transpose(self): + if self._source is not None: + return self._source.detach() + result = self._new(type(self), self.shape[::-1], self.values()) + result._source = self + result._components = None + result._transposed_components = None + result._source_versions = None + result._canonical_versions = None + return result + + def _mv(self, x, out, beta): + components = self.components + # Preserve the measured MPS dispatch for cached camera transposes. + scalar = (self._source is not None and self.device.type == "mps" + and components[2].shape[-2:] == (9, 2) + and components[0].numel() - 1 >= 1024) + tuple_ops.bsr_mv(components, x, y=out, beta=beta, size=self.shape, + tile_size=-1 if scalar else 0) + + def normal_diagonal(self): + return tuple_ops.bsr_diagonal(self.coalesce().components, size=self.shape) + + def _map_components(self, func, kwargs): + if func is torch.ops.aten.detach.default and self._source is not None: + return self._source.detach().mT + if func is torch.ops.aten.detach.default: + # Dispatch runs below view tracking. Reenter it for dense detach so + # aliases share version counters and invalidate transpose caches. + with torch.overrides.enable_reentrant_dispatch(): + parts = [func(tensor) for tensor in self.components] + return BSRTensor(*parts, size=self.shape, is_coalesced=self.is_coalesced()) + parts = [] + for index, tensor in enumerate(self.components): + options = dict(kwargs) + if func is torch.ops.aten._to_copy.default and index != 2: + options.pop("dtype", None) + parts.append(func(tensor, **options)) + return BSRTensor(*parts, size=self.shape, is_coalesced=self.is_coalesced()) + + def to_dense(self): + crow, col, values = self.components + br, bc = values.shape[-2:] + rows = torch.searchsorted(crow[1:], torch.arange(col.numel(), device=self.device, + dtype=crow.dtype), right=True) + row = rows[:, None, None] * br + torch.arange(br, device=self.device)[None, :, None] + column = col[:, None, None] * bc + torch.arange(bc, device=self.device)[None, None, :] + result = values.new_zeros(self.numel()) + result.index_add_(0, (row * self.shape[1] + column).reshape(-1).long(), values.reshape(-1)) + return result.reshape(self.shape) + + +class SparseCat(_SparseTensor): + """A tensor concatenation retaining each BSR matrix's own block size.""" + + @staticmethod + def __new__(cls, blocks, dim=1): + blocks = tuple(blocks) + if not blocks or any(not isinstance(block, _SparseTensor) for block in blocks): + raise TypeError("Sparse concatenation requires BSR tensors") + if dim not in (-2, -1, 0, 1): + raise IndexError("Sparse concatenation dimension must be 0 or 1") + dim %= 2 + first = blocks[0] + if any(block.shape[1 - dim] != first.shape[1 - dim] for block in blocks): + raise ValueError("Sparse concatenation requires matching non-concatenated dimensions") + if any(block.device != first.device or block.dtype != first.dtype for block in blocks): + raise ValueError("Sparse concatenation requires matching devices and dtypes") + shape = list(first.shape) + shape[dim] = sum(block.shape[dim] for block in blocks) + result = cls._new(cls, shape, first) + result.blocks, result.cat_dim = blocks, dim + return result + + def _transpose(self): + return SparseCat([block.mT for block in self.blocks], 1 - self.cat_dim) + + def _mv(self, x, out, beta): + widths = [block.shape[self.cat_dim] for block in self.blocks] + if self.cat_dim == 1: + for block, part in zip(self.blocks, x.split(widths, dim=0)): + block._mv(part, out, beta) + beta = 1 + else: + for block, part in zip(self.blocks, out.split(widths, dim=0)): + block._mv(x, part, beta) + + def normal_diagonal(self): + diagonals = [block.normal_diagonal() for block in self.blocks] + return torch.cat(diagonals) if self.cat_dim == 1 else sum(diagonals) + + def _map_components(self, func, kwargs): + return SparseCat([func(block, **kwargs) for block in self.blocks], self.cat_dim) + + def to_dense(self): + return torch.cat([block.to_dense() for block in self.blocks], dim=self.cat_dim) diff --git a/bae/sparse/tuple_ops.py b/bae/sparse/tuple_ops.py index e88bdbe..cc4e7f3 100644 --- a/bae/sparse/tuple_ops.py +++ b/bae/sparse/tuple_ops.py @@ -227,6 +227,8 @@ def bsr_transposed(A, *, size): As with Warp's bsr_transposed + bsr_mv, assembling this once allows repeated transpose products to use row reduction instead of contended atomic sums. The returned values own their storage; rebuild after changing A. + PyTorch implementation of the semantics documented in: + https://github.com/NVIDIA/warp/blob/release-1.19/warp/_src/sparse.py#L2889-L3148 """ crow, col, values = _validate(A, size) nnz = values.shape[0] diff --git a/bae/utils/linear_operator.py b/bae/utils/linear_operator.py index 070badf..3a7c608 100644 --- a/bae/utils/linear_operator.py +++ b/bae/utils/linear_operator.py @@ -1,12 +1,50 @@ from __future__ import annotations -from typing import Optional, Union, Any, Tuple +from typing import Optional, Union, Tuple import torch from torch import Tensor -class NormalMatVec: +class _MatVecOperator: + ndim = 2 + + def __call__(self, x): + return self.matvec(x) + + def __matmul__(self, x): + return self.matvec(x) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + kwargs = {} if kwargs is None else kwargs + if func is torch.matmul and len(args) >= 2 and isinstance(args[0], cls): + out = kwargs.get("out") + return args[0].matvec(args[1], out=out[0] if isinstance(out, tuple) else out) + return NotImplemented + + +class DiagonalMatVec(_MatVecOperator): + """Apply a diagonal matrix without constructing a sparse tensor.""" + + def __init__(self, diagonal): + if diagonal.ndim != 1: + raise ValueError("diagonal must be one-dimensional") + self.values = diagonal + self.device, self.dtype = diagonal.device, diagonal.dtype + self.shape = (diagonal.numel(), diagonal.numel()) + + def matvec(self, x, out=None): + if x.ndim not in (1, 2) or x.shape[0] != self.shape[1]: + raise ValueError("x must be a vector or matrix with compatible leading dimension") + diagonal = self.values if x.ndim == 1 else self.values[:, None] + return torch.mul(diagonal, x, out=out) if out is not None else diagonal * x + + def diagonal(self): + return self.values + + +class NormalMatVec(_MatVecOperator): r"""Matrix-free normal-equation linear operator. Given a Jacobian J (dense, CSR/COO, or BSR), this operator represents: @@ -14,6 +52,11 @@ class NormalMatVec: A x = J^T (J x) + damping * diag(J^T J) * x where diag(J^T J) is computed as the column-wise sum of squares of J. + Supplying ``diag`` replaces the normal matrix's diagonal before damping, + matching LM's explicit clamp-and-damp behavior. + ``raw_diag`` can reuse a previously computed diagonal. The replacement and + correction must use the same reduction result: separate parallel sums can + differ by more than a small damping term in float32. """ def __init__( @@ -21,8 +64,10 @@ def __init__( J: Tensor, damping: Union[float, Tensor] = 0.0, diag: Optional[Tensor] = None, + *, + raw_diag: Optional[Tensor] = None, ): - if not torch.is_tensor(J): + if not isinstance(J, Tensor): raise TypeError("J must be a torch.Tensor") if J.ndim != 2: raise ValueError("J must be 2-D") @@ -32,14 +77,20 @@ def __init__( self.device = J.device self.dtype = J.dtype - self.layout = J.layout if J.layout != torch.sparse_coo else torch.sparse_csr self.shape: Tuple[int, int] = (J.shape[1], J.shape[1]) self.ndim: int = 2 - self._diag: Tensor = diag if diag is not None else self._compute_diag(J) + self._raw_diag = self._compute_diag(J) if raw_diag is None else raw_diag + if self._raw_diag.ndim != 1 or self._raw_diag.numel() != J.shape[1]: + raise ValueError("raw_diag must be 1-D with length equal to J.shape[1]") + if self._raw_diag.device != self.device or self._raw_diag.dtype != self.dtype: + raise ValueError("raw_diag must have the same device and dtype as J") + self._diag: Tensor = diag if diag is not None else self._raw_diag if self._diag.ndim != 1 or self._diag.numel() != J.shape[1]: raise ValueError("diag must be 1-D with length equal to J.shape[1]") + if self._diag.device != self.device or self._diag.dtype != self.dtype: + raise ValueError("diag must have the same device and dtype as J") self.set_damping(damping) @@ -50,59 +101,40 @@ def set_damping(self, damping: Union[float, Tensor]) -> None: self.damping = damping.to(device=self.device, dtype=self.dtype) else: self.damping = float(damping) + self._effective_diag = self._diag * (1.0 + self.damping) + # Keep small positive damping even when 1 + damping rounds to 1 in + # float32. Subtract only the intended diagonal replacement. + self._correction = (self._diag - self._raw_diag) + self.damping * self._diag def diagonal(self) -> Tensor: - damp = self._damping_value() - if damp is None: - return self._diag - return self._diag * (1.0 + damp) - - def matvec(self, x: Tensor) -> Tensor: - if x.ndim == 1: - x2d = x.unsqueeze(-1) - elif x.ndim == 2: - x2d = x - else: - raise ValueError("x must be 1-D or 2-D") + return self._effective_diag + + def matvec(self, x: Tensor, out: Optional[Tensor] = None) -> Tensor: + if x.ndim not in (1, 2) or x.shape[0] != self.shape[1]: + raise ValueError("x must be a vector or matrix with compatible leading dimension") + if out is not None: + if out.shape != x.shape or out.device != self.device or out.dtype != self.dtype: + raise ValueError("out must have the result's shape, device, and dtype") + if not out.is_contiguous(): + raise ValueError("out must be contiguous") + if torch._C._overlaps(x, out): + x = x.clone() + x2d = x.unsqueeze(-1) if x.ndim == 1 else x if x2d.device != self.device or x2d.dtype != self.dtype: x2d = x2d.to(device=self.device, dtype=self.dtype) + # Both native and tuple-backed Jacobians use ordinary tensor dispatch. y = self.J @ x2d - Jt = self._get_Jt() - z = Jt @ y - - damp = self._damping_value() - if damp is not None: - z = z + damp * self._diag.unsqueeze(-1) * x2d + output = None if out is None else out.reshape(x2d.shape) + z = torch.matmul(self._get_Jt(), y, out=output) + z.addcmul_(self._correction.unsqueeze(-1), x2d) + if out is not None: + return out return z.squeeze(-1) if x.ndim == 1 else z - def __call__(self, x: Tensor) -> Tensor: - return self.matvec(x) - - def __matmul__(self, x: Tensor) -> Tensor: - return self.matvec(x) - - @classmethod - def __torch_function__( # type: ignore[override] - cls, func: Any, types: Any, args: Tuple[Any, ...] = (), kwargs: Optional[dict] = None - ): - if kwargs is None: - kwargs = {} - if func is torch.matmul and len(args) >= 2: - A, B = args[0], args[1] - if isinstance(A, cls): - out = kwargs.get("out", None) - result = A.matvec(B) - if out is not None: - out_tensor = out[0] if isinstance(out, tuple) else out - out_tensor.copy_(result) - return out_tensor - return result - return NotImplemented - - def _get_Jt(self) -> Tensor: + def _get_Jt(self): if self._Jt is None: Jt = self.J.mT if Jt.layout == torch.sparse_csc: @@ -113,17 +145,10 @@ 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 hasattr(J, 'normal_diagonal'): + return J.normal_diagonal() if J.layout == torch.strided: return J.square().sum(dim=0) diff --git a/setup.py b/setup.py index 871f35b..c9e054f 100644 --- a/setup.py +++ b/setup.py @@ -271,7 +271,7 @@ def cuda_extensions(): description = 'PyTorch implementation of BA', long_description = readme(), long_description_content_type = "text/markdown", - license_files=["LICENSE", "third_party/warp/LICENSE.md", "third_party/warp/ORIGIN.txt"], + license_files=["LICENSE", "third_party/warp/LICENSE.md"], python_requires = ">=3.8", install_requires=[ 'torch>=2.13; sys_platform == "darwin" and platform_machine == "arm64"', diff --git a/third_party/warp/LICENSE.md b/third_party/warp/LICENSE.md new file mode 100644 index 0000000..9663cb9 --- /dev/null +++ b/third_party/warp/LICENSE.md @@ -0,0 +1,203 @@ +Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. From 96345a112f5af85b90007982f50b4c78e4378151 Mon Sep 17 00:00:00 2001 From: zitongzhan Date: Wed, 25 Nov 2026 10:47:27 -0500 Subject: [PATCH 6/6] add tuple tests --- .github/workflows/test-graph-jacobian.yml | 2 +- bae/sparse/__init__.py | 21 +- tests/sparse/tuple/test_mps_pcg.py | 136 ++++++ .../tuple/test_normal_diagonal_consistency.py | 65 +++ .../tuple/test_tuple_normal_operator.py | 379 +++++++++++++++ tests/sparse/tuple/test_tuple_ops.py | 434 ++++++++++++++++++ tests/sparse/tuple/test_tuple_tensor.py | 177 +++++++ tests/test_normal_operator.py | 42 ++ 8 files changed, 1246 insertions(+), 10 deletions(-) create mode 100644 tests/sparse/tuple/test_mps_pcg.py create mode 100644 tests/sparse/tuple/test_normal_diagonal_consistency.py create mode 100644 tests/sparse/tuple/test_tuple_normal_operator.py create mode 100644 tests/sparse/tuple/test_tuple_ops.py create mode 100644 tests/sparse/tuple/test_tuple_tensor.py diff --git a/.github/workflows/test-graph-jacobian.yml b/.github/workflows/test-graph-jacobian.yml index 53fff77..a5932fd 100644 --- a/.github/workflows/test-graph-jacobian.yml +++ b/.github/workflows/test-graph-jacobian.yml @@ -43,4 +43,4 @@ jobs: PYTHONPATH: /tmp/pydeps:${{ github.workspace }} run: | python -c "import torch; print('torch', torch.__version__)" - python -m pytest -q tests/autograd tests/test_normal_operator.py tests/test_normal_diagonal_consistency.py tests/test_tuple_normal_operator.py tests/test_mps_pcg.py tests/sparse/test_tuple_ops.py tests/sparse/test_sparse_tensor.py tests/test_build.py + python -m pytest -q tests/autograd tests/test_normal_operator.py tests/sparse/tuple diff --git a/bae/sparse/__init__.py b/bae/sparse/__init__.py index bd08f26..6febb2b 100644 --- a/bae/sparse/__init__.py +++ b/bae/sparse/__init__.py @@ -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}') diff --git a/tests/sparse/tuple/test_mps_pcg.py b/tests/sparse/tuple/test_mps_pcg.py new file mode 100644 index 0000000..5a36e35 --- /dev/null +++ b/tests/sparse/tuple/test_mps_pcg.py @@ -0,0 +1,136 @@ +"""Regression checks for the single-RHS MPS CG reduction path.""" + +import pytest +import torch +from pypose.optim.solver import CG +from torch.utils._python_dispatch import TorchDispatchMode + +from bae.utils.linear_operator import DiagonalMatVec, _MatVecOperator +from bae.utils.pysolvers import PCG + + +MPS = pytest.mark.skipif(not torch.backends.mps.is_available(), reason="MPS unavailable") + + +def _system(device="cpu"): + factor = torch.tensor([[2., 0., 1., 0.], [1., 3., 0., 0.], + [0., 1., 2., 1.], [0., 0., 1., 2.]]) + matrix = factor.mT @ factor + torch.eye(4) + rhs = torch.tensor([[1.], [-2.], [3.], [0.5]]) + return matrix.to(device), rhs.to(device) + + +class _CountingMatrix(_MatVecOperator): + def __init__(self, matrix): + self.matrix = matrix + self.shape, self.device, self.dtype = matrix.shape, matrix.device, matrix.dtype + self.calls = [] + + def matvec(self, x, out=None): + self.calls.append(None if out is None else out.data_ptr()) + return torch.matmul(self.matrix, x, out=out) + + +@pytest.mark.parametrize("maxiter", [0, 1, 2, None]) +def test_reduction_recurrence_matches_pypose_and_mutates_warm_start(maxiter): + matrix, rhs = _system() + initial = torch.full_like(rhs, 0.125) + reference = CG(maxiter=maxiter, tol=1e-6)( + matrix, rhs, x=initial.clone(), M=torch.diag(matrix.diagonal().reciprocal())) + op = _CountingMatrix(matrix) + preconditioner = _CountingMatrix(torch.diag(matrix.diagonal().reciprocal())) + result = PCG(maxiter=maxiter, tol=1e-6)._forward_mps(op, rhs, initial, preconditioner) + assert result is initial + torch.testing.assert_close(result, reference, rtol=2e-5, atol=2e-6) + # A nonzero initial guess consumes one residual evaluation before CG. + if maxiter is not None: + assert len(op.calls) == maxiter + 1 + assert len(preconditioner.calls) == maxiter + else: + torch.testing.assert_close(result.double(), torch.linalg.solve(matrix.double(), rhs.double()), + rtol=2e-5, atol=2e-6) + assert 0 < len(preconditioner.calls) < rhs.numel() * 10 + # The recurrence supplies and reuses output buffers for A and custom M. + assert all(pointer is not None for pointer in op.calls[1:] + preconditioner.calls) + assert len(set(op.calls[1:])) <= 1 + assert len(set(preconditioner.calls)) <= 1 + + +def test_zero_rhs_and_exact_warm_start_do_not_iterate(): + matrix = torch.diag(torch.tensor([1., 2., 4., 8.])) + op, preconditioner = _CountingMatrix(matrix), _CountingMatrix(torch.eye(4)) + solver = PCG() + zero, initial = torch.zeros(4, 1), torch.ones(4, 1) + assert solver._forward_mps(op, zero, initial, preconditioner) is zero + assert torch.equal(initial, torch.ones_like(initial)) + assert op.calls == preconditioner.calls == [] + rhs = matrix @ initial + assert solver._forward_mps(op, rhs, initial, preconditioner) is initial + assert len(op.calls) == 1 + assert preconditioner.calls == [] + + +class _NoMatrixInnerProducts(TorchDispatchMode): + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + if func in (torch.ops.aten.mm.default, torch.ops.aten.mm.out, + torch.ops.aten.bmm.default, torch.ops.aten.bmm.out): + left, right = args[:2] + assert not (left.shape[-2] == 1 and right.shape[-1] == 1), \ + "CG scalar products must use reductions, not 1xN @ Nx1" + return func(*args, **(kwargs or {})) + + +@pytest.mark.parametrize("device", ["cpu", pytest.param( + "cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA unavailable"))]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.float64]) +def test_other_backends_still_delegate_to_pypose(device, dtype, monkeypatch): + matrix, rhs = _system(device) + matrix, rhs = matrix.to(dtype), rhs.to(dtype).squeeze(-1) + calls = [] + + def delegated(self, A, b, x, M): + calls.append((A, b, M)) + return b.clone() + + monkeypatch.setattr(CG, "forward", delegated) + result = PCG()(matrix, rhs) + assert len(calls) == 1 and calls[0][0] is matrix + assert calls[0][1].shape == (4, 1) + assert isinstance(calls[0][2], DiagonalMatVec) + torch.testing.assert_close(result, rhs) + + +@MPS +@pytest.mark.parametrize("form", ["half", "multiple_rhs", "batched"]) +def test_other_mps_forms_still_delegate_to_pypose(form, monkeypatch): + matrix, rhs = _system("mps") + if form == "half": + matrix, rhs = matrix.half(), rhs.half() + elif form == "batched": + matrix, rhs = matrix.expand(2, 4, 4), rhs.expand(2, 4, 1) + else: + rhs = rhs.expand(4, 2) + calls = [] + + def delegated(self, A, b, x, M): + calls.append(b.shape) + return b.clone() + + monkeypatch.setattr(CG, "forward", delegated) + result = PCG()(matrix, rhs, M=torch.eye(4, device="mps")) + assert calls == [rhs.shape] + torch.testing.assert_close(result, rhs) + + +@MPS +@pytest.mark.parametrize("vector", [False, True]) +def test_mps_dense_solve_normalizes_rhs_and_uses_reductions(vector): + matrix, rhs = _system("mps") + if vector: + rhs = rhs.squeeze(-1) + initial = torch.full_like(rhs, 0.125) + expected = torch.linalg.solve(matrix.cpu().double(), rhs.cpu().double()) + with _NoMatrixInnerProducts(): + result = PCG(tol=1e-6)(matrix, rhs, x=initial) + assert result.shape == rhs.shape and result.data_ptr() == initial.data_ptr() + torch.testing.assert_close(result.cpu().double(), expected, rtol=2e-5, atol=2e-6) diff --git a/tests/sparse/tuple/test_normal_diagonal_consistency.py b/tests/sparse/tuple/test_normal_diagonal_consistency.py new file mode 100644 index 0000000..04ce1bf --- /dev/null +++ b/tests/sparse/tuple/test_normal_diagonal_consistency.py @@ -0,0 +1,65 @@ +import pypose as pp +import pytest +import torch +import torch.nn as nn + +from bae.optim import LM +from bae.utils.linear_operator import NormalMatVec + + +@pytest.mark.parametrize('device', ['cpu', pytest.param('mps', marks=pytest.mark.skipif( + not torch.backends.mps.is_available(), reason='MPS is unavailable'))]) +def test_lm_reuses_one_diagonal_reduction_for_small_damping(device, monkeypatch): + """Reduction-order noise must not turn positive damping into a subtraction.""" + + class Residual(nn.Module): + def __init__(self): + super().__init__() + self.variable = pp.Parameter(torch.zeros(2, 1, device=device), sjac=True) + + def forward(self, target, index): + return self.variable[index] * 10000.0 - target + + reductions = 0 + normal_diagonal = NormalMatVec._compute_diag + + def count_reductions(jacobian): + nonlocal reductions + reductions += 1 + return normal_diagonal(jacobian) + + monkeypatch.setattr(NormalMatVec, "_compute_diag", staticmethod(count_reductions)) + + class InspectSolver(nn.Module): + def forward(self, operator, rhs): + expected = torch.full_like(rhs.flatten(), 1e8) * (1 + 1e-6) + torch.testing.assert_close(operator.diagonal(), expected, rtol=0, atol=0) + return torch.zeros_like(rhs) + + model = Residual() + optimizer = LM(model, solver=InspectSolver(), matrix_free_normal=True, + strategy=pp.optim.strategy.Constant(damping=1e-6)) + loss = optimizer.step({"target": torch.ones(2, 1, device=device), + "index": torch.arange(2, device=device)}) + assert reductions == 1 + assert torch.isfinite(loss) + + +def test_sub_epsilon_float32_damping_remains_positive(): + jacobian = torch.tensor([[1e5, 1e5]], dtype=torch.float32) + operator = NormalMatVec(jacobian, damping=1e-8) + # In this null direction J.T @ J contributes zero, so the result directly + # exposes the positive damping that a rounded (1 + damping) would lose. + vector = torch.tensor([1., -1.]) + torch.testing.assert_close(operator @ vector, torch.tensor([100., -100.])) + + +@pytest.mark.parametrize("raw", [ + torch.ones(2, 1), + torch.ones(3), + torch.ones(2, dtype=torch.float64), + torch.ones(2, device="meta"), +]) +def test_supplied_raw_diagonal_is_validated(raw): + with pytest.raises(ValueError, match="raw_diag"): + NormalMatVec(torch.eye(2), raw_diag=raw) diff --git a/tests/sparse/tuple/test_tuple_normal_operator.py b/tests/sparse/tuple/test_tuple_normal_operator.py new file mode 100644 index 0000000..929bc71 --- /dev/null +++ b/tests/sparse/tuple/test_tuple_normal_operator.py @@ -0,0 +1,379 @@ +import pytest +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor +from threading import Barrier +from types import ModuleType +from unittest.mock import Mock +import torch +import torch.nn as nn +import pypose as pp + +from bae.optim import LM +from bae.sparse import BSRTensor +from bae.utils.linear_operator import NormalMatVec +from bae.utils.pysolvers import PCG + + +DEVICES = ['cpu', pytest.param('mps', marks=pytest.mark.skipif( + not torch.backends.mps.is_available(), reason='MPS is unavailable'))] + + +def _cat_blocks(blocks, sizes): + return torch.cat([ + BSRTensor(*block, size=size, is_coalesced=True) + for block, size in zip(blocks, sizes) + ], dim=1) + + +def _same_components(actual, expected): + return all(a is b for a, b in zip(actual, expected)) + + +def test_matrix_free_imports_without_optional_backends(): + script = ''' +import importlib.abc +import sys + +attempts = [] +class BlockCuDSS(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname == "bae.sparse.solve": + attempts.append(fullname) + raise ImportError("CuDSS import intercepted by test") + +sys.modules["warp"] = None # Simulate an installation without Warp. +sys.meta_path.insert(0, BlockCuDSS()) +from bae.optim import LM +from bae.utils.pysolvers import PCG, CuDSS +PCG() +assert attempts == ["bae.sparse.solve"], attempts +assert "bae.sparse.spgemm" not in sys.modules +assert "bae.sparse.conversion" not in sys.modules +if sys.platform == "darwin": + assert "triton" not in sys.modules +try: + CuDSS() +except ImportError as error: + assert "Use `PCG(...)` instead" in str(error) + assert "intercepted by test" in str(error.__cause__) +else: + raise AssertionError("CuDSS should fail when its extension is unavailable") +assert attempts == ["bae.sparse.solve"], attempts +''' + result = subprocess.run([sys.executable, '-c', script], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + +def test_lm_constructor_preserves_explicit_matrix_free_setting(monkeypatch): + spgemm = ModuleType('bae.sparse.spgemm') + spgemm.CuSparse = Mock() + monkeypatch.setitem(sys.modules, 'bae.sparse.spgemm', spgemm) + model = nn.Linear(1, 1) + optimizer = LM(model, solver=PCG()) + assert optimizer.matrix_free_normal is False + assert optimizer.tuple_mode is False + assert optimizer.mm is spgemm.CuSparse.return_value + spgemm.CuSparse.assert_called_once_with() + + # Matrix-free construction must work when the CUDA extension cannot import. + monkeypatch.setitem(sys.modules, 'bae.sparse.spgemm', None) + optimizer = LM(model, solver=PCG(), matrix_free_normal=True) + assert optimizer.matrix_free_normal is True + assert optimizer.tuple_mode is False + spgemm.CuSparse.assert_called_once_with() + + +@pytest.mark.skipif(not torch.backends.mps.is_available(), reason='MPS is unavailable') +@pytest.mark.parametrize('requires_grad', [True, False]) +def test_lm_constructor_checks_all_mps_parameters(requires_grad): + model = nn.Module() + model.first = nn.Parameter(torch.ones(1)) + model.second = nn.Parameter(torch.ones(1, device='mps'), requires_grad=requires_grad) + with pytest.raises(ValueError, match='matrix_free_normal=True'): + LM(model, solver=PCG()) + optimizer = LM(model, solver=PCG(), matrix_free_normal=True) + assert optimizer.matrix_free_normal is True + assert optimizer.tuple_mode is True + + +def _block_components(block_width, device): + # One empty block row, repeated column references across rows, and an + # unobserved trailing block column. Different widths cannot be concatenated + # into a single BSR matrix without changing its blocking. + crow = torch.tensor([0, 2, 2, 3], dtype=torch.int32) + col = torch.tensor([0, 1, 0], dtype=torch.int32) + values = torch.arange(1, 1 + 3 * 2 * block_width, dtype=torch.float32) + values = values.reshape(3, 2, block_width) / 10 + dense = torch.zeros(6, 3 * block_width) + for row in range(3): + for entry in range(crow[row], crow[row + 1]): + column = col[entry] * block_width + dense[2 * row:2 * row + 2, column:column + block_width] += values[entry] + return tuple(t.to(device) for t in (crow, col, values)), dense + + +@pytest.mark.parametrize('device', DEVICES) +def test_normal_diagonal_replacement_and_repeated_damping(device): + block, dense = _block_components(2, device) + jacobian = _cat_blocks([block], [(6, 6)]) + raw = dense.square().sum(0) + replacement = raw.clamp(min=0.25, max=2.0) + op = NormalMatVec(jacobian, diag=replacement.to(device)) + x = torch.arange(6, dtype=torch.float32) + scale = 1.0 + for damping in (0.0, 0.1, 0.7): + scale *= 1.0 + damping + op.set_damping(scale - 1.0) + expected = dense.mT @ dense + expected.diagonal().copy_(scale * replacement) + out = torch.empty(6, device=device) + assert torch.matmul(op, x.to(device), out=out) is out + torch.testing.assert_close(out.cpu(), expected @ x, rtol=2e-5, atol=2e-5) + torch.testing.assert_close(op.diagonal().cpu(), expected.diagonal()) + + +@pytest.mark.parametrize('device', DEVICES) +def test_pcg_tuple_normal_without_sparse_constructors(device, monkeypatch): + def forbidden(*args, **kwargs): + raise AssertionError('tuple solver must not construct native sparse tensors') + + for name in ('sparse_coo_tensor', 'sparse_csr_tensor', 'sparse_csc_tensor', + 'sparse_bsr_tensor', 'sparse_bsc_tensor'): + monkeypatch.setattr(torch, name, forbidden) + block, dense = _block_components(2, device) + jacobian = _cat_blocks([block], [(6, 6)]) + diagonal = dense.square().sum(0).clamp(min=0.1) + op = NormalMatVec(jacobian, damping=0.5, diag=diagonal.to(device)) + expected_matrix = dense.mT @ dense + expected_matrix.diagonal().copy_(diagonal * 1.5) + rhs = torch.arange(1, 7, dtype=torch.float32) + solver = PCG(tol=1e-5, maxiter=100) + for vector in (True, False): + b = rhs if vector else rhs[:, None] + initial = torch.full_like(b, 0.1, device=device) + actual = solver(op, b.to(device), x=initial) + expected = torch.linalg.solve(expected_matrix, b) + torch.testing.assert_close(actual.cpu(), expected, rtol=2e-4, atol=2e-4) + assert actual.shape == b.shape + zero = torch.zeros(6, device=device) + assert torch.equal(solver(op, zero), zero) + torch.testing.assert_close(op.diagonal().cpu(), diagonal * 1.5) + + +@pytest.mark.parametrize('device', DEVICES) +def test_tuple_operator_reuses_outputs_and_prepares_transposes_once(device, monkeypatch): + from bae.sparse import tuple_ops + + a, adense = _block_components(3, device) + b, bdense = _block_components(2, device) + dense = torch.cat([adense, bdense], dim=1) + op = _cat_blocks([a, b], [(6, 9), (6, 6)]) + normal = NormalMatVec(op, damping=0.25) + original = tuple_ops.bsr_transposed + prepared = [] + + def track_transpose(block, **kwargs): + prepared.append(block) + return original(block, **kwargs) + + monkeypatch.setattr(tuple_ops, 'bsr_transposed', track_transpose) + x = torch.arange(15, dtype=torch.float32, device=device)[:, None] / 10 + residual = torch.arange(6, dtype=torch.float32, device=device)[:, None] / 5 + forward_out = torch.empty(6, 1, device=device) + transpose_out = torch.empty(15, 1, device=device) + normal_out = torch.empty_like(x) + pointers = [out.data_ptr() for out in (forward_out, transpose_out, normal_out)] + with torch.no_grad(): + for scale in (1., 2., 0.5): + current_x = x * scale + assert torch.matmul(op, current_x, out=forward_out) is forward_out + assert torch.matmul(op.mT, residual, out=transpose_out) is transpose_out + assert torch.matmul(normal, current_x, out=normal_out) is normal_out + assert [out.data_ptr() for out in (forward_out, transpose_out, normal_out)] == pointers + expected_normal = dense.mT @ (dense @ current_x.cpu()) + expected_normal += 0.25 * dense.square().sum(0)[:, None] * current_x.cpu() + torch.testing.assert_close(forward_out.cpu(), dense @ current_x.cpu(), rtol=2e-5, atol=2e-5) + torch.testing.assert_close(transpose_out.cpu(), dense.mT @ residual.cpu(), rtol=2e-5, atol=2e-5) + torch.testing.assert_close(normal_out.cpu(), expected_normal, rtol=2e-5, atol=2e-5) + assert len(prepared) == 2 + assert _same_components(prepared[0], a) and _same_components(prepared[1], b) + + +@pytest.mark.skipif(not torch.backends.mps.is_available(), reason='MPS unavailable') +@pytest.mark.parametrize('camera_count,block_shape,expected_tile', [ + (1023, (2, 9), 0), + (1024, (2, 9), -1), + (1024, (3, 9), 0), + (1024, (2, 8), 0), +]) +def test_cached_camera_transpose_dispatch(camera_count, block_shape, expected_tile, monkeypatch): + from bae.sparse import tuple_ops + + br, bc = block_shape + values = torch.arange(1., 1 + br * bc).reshape(1, br, bc) + matrix = BSRTensor(torch.tensor([0, 1], device='mps'), + torch.tensor([0], device='mps'), values.to('mps'), + size=(br, camera_count * bc), is_coalesced=True) + tiles = [] + original = tuple_ops.bsr_mv + + def record(*args, **kwargs): + tiles.append(kwargs['tile_size']) + return original(*args, **kwargs) + + monkeypatch.setattr(tuple_ops, 'bsr_mv', record) + result = matrix.mT @ torch.ones(br, device='mps') + expected = torch.zeros(camera_count, bc) + expected[0] = values[0].sum(0) + torch.testing.assert_close(result.cpu(), expected.flatten()) + assert tiles == [expected_tile] + + +def test_normal_matvec_concurrent_calls_keep_intermediates_independent(monkeypatch): + block = ( + torch.arange(5, dtype=torch.int32), + torch.arange(4, dtype=torch.int32), + torch.ones(4, 1, 1), + ) + jacobian = _cat_blocks([block], [(4, 4)]) + normal = NormalMatVec(jacobian) + # Warm all caches before coordinating simultaneous calls. With a shared + # intermediate, both calls would read the last-written Jx after the barrier. + with torch.no_grad(): + normal @ torch.zeros(4) + completed_forward = Barrier(2) + matvec = jacobian.matvec + + def coordinated_forward(x, out=None): + result = matvec(x, out=out) + completed_forward.wait(timeout=10) + return result + + monkeypatch.setattr(jacobian, 'matvec', coordinated_forward) + + def evaluate(x): + with torch.no_grad(): + return normal @ x + + inputs = (torch.arange(1., 5.), torch.arange(10., 14.)) + with ThreadPoolExecutor(max_workers=2) as executor: + futures = [executor.submit(evaluate, x) for x in inputs] + outputs = [future.result(timeout=15) for future in futures] + for output, expected in zip(outputs, inputs): + torch.testing.assert_close(output, expected) + + +@pytest.mark.parametrize('device', DEVICES) +def test_normal_output_can_alias_input_with_nonzero_damping(device): + block, dense = _block_components(2, device) + normal = NormalMatVec(_cat_blocks([block], [(6, 6)]), damping=0.5) + x = torch.arange(6, dtype=torch.float32, device=device) + expected = dense.mT @ (dense @ x.cpu()) + 0.5 * dense.square().sum(0) * x.cpu() + with torch.no_grad(): + assert torch.matmul(normal, x, out=x) is x + torch.testing.assert_close(x.cpu(), expected, rtol=2e-5, atol=2e-5) + + +@pytest.mark.parametrize('device', DEVICES) +@pytest.mark.parametrize('unused_shape', [(2, 1), (), (0,)], ids=['matrix', 'scalar', 'empty_vector']) +def test_lm_rejects_disconnected_parameters_before_solving(device, unused_shape): + class Residual(nn.Module): + def __init__(self): + super().__init__() + self.unused = pp.Parameter(torch.full(unused_shape, 3., device=device), sjac=True) + self.variable = pp.Parameter(torch.zeros(2, 1, device=device), sjac=True) + + def forward(self, target, index): + return self.variable[index] * 2 - target + + model = Residual() + solver = Mock() + optimizer = LM(model, solver=solver, matrix_free_normal=True) + data = {'target': torch.tensor([[2.], [4.]], device=device), + 'index': torch.tensor([0, 1], device=device)} + with pytest.raises(ValueError, match='All optimized parameters must contribute to the residual'): + optimizer.step(data) + solver.assert_not_called() + torch.testing.assert_close(model.variable.detach(), torch.zeros(2, 1, device=device)) + + +@pytest.mark.parametrize('device', DEVICES) +def test_synthetic_ba_lm_reduces_reprojection_error(device): + from ba_example import Residual, project + + torch.manual_seed(5) + cameras = torch.zeros(3, 10) + cameras[:, 6] = 1 + cameras[:, 7] = 300 + cameras[:, 0] = torch.tensor([-0.2, 0., 0.2]) + points = torch.randn(8, 3) * 0.3 + points[:, 2] -= 3 + cidx = torch.arange(3).repeat_interleave(8) + pidx = torch.arange(8).repeat(3) + observes = project(points[pidx], cameras[cidx]).detach() + cameras[:, :3] += torch.randn(3, 3) * 0.01 + points += torch.randn_like(points) * 0.01 + model = Residual(cameras.to(device), points.to(device)) + data = {'observes': observes.to(device), 'cidx': cidx.to(device), 'pidx': pidx.to(device)} + optimizer = LM(model, solver=PCG(tol=1e-5, maxiter=150), reject=10, matrix_free_normal=True, + strategy=pp.optim.strategy.TrustRegion(radius=100)) + initial = optimizer.model.loss(data, None).item() + for _ in range(3): + loss = optimizer.step(data) + assert torch.isfinite(loss) + assert loss.item() < initial * 0.1 + + +@pytest.mark.parametrize('device', DEVICES) +def test_lm_rejected_step_keeps_cumulative_damping(device, monkeypatch): + from bae.optim import optimizer as optimizer_module + from pypose.autograd.function import psjac + + trace_name = 'jacobian_components' if device == 'mps' else 'jacobian' + other_name = 'jacobian' if device == 'mps' else 'jacobian_components' + trace = Mock(wraps=getattr(optimizer_module, trace_name)) + monkeypatch.setattr(optimizer_module, trace_name, trace) + monkeypatch.setattr(optimizer_module, other_name, Mock(side_effect=AssertionError('Wrong Jacobian path'))) + if device == 'mps': + for name in ('sparse_coo_tensor', 'sparse_csr_tensor', 'sparse_csc_tensor', + 'sparse_bsr_tensor', 'sparse_bsc_tensor'): + monkeypatch.setattr(torch, name, Mock(side_effect=AssertionError('Native sparse constructor'))) + + @psjac + def square(value): + return value.square() + + class Residual(nn.Module): + def __init__(self): + super().__init__() + self.variable = pp.Parameter(torch.ones(1, 1, device=device), sjac=True) + + def forward(self, target, index): + return square(self.variable[index]) - target + + model = Residual() + diagonals, parameter_states = [], [] + + class TrialSolver(nn.Module): + def forward(self, operator, rhs): + parameter_states.append(torch.Tensor(model.variable).clone()) + diagonals.append(operator.diagonal().clone()) + # The first step predicts improvement but increases nonlinear loss. + # Both increments are exactly reversible in float32. + return torch.full_like(rhs, (0.75, 0.25)[len(diagonals) - 1]) + + optimizer = LM(model, solver=TrialSolver(), reject=2, matrix_free_normal=True, + strategy=pp.optim.strategy.TrustRegion(radius=10)) + loss = optimizer.step({'target': torch.tensor([[2.]], device=device), + 'index': torch.tensor([0], device=device)}) + + trace.assert_called_once() + assert optimizer.reject_count == 1 + assert len(diagonals) == 2 + for state in parameter_states: + torch.testing.assert_close(state.cpu(), torch.ones(1, 1)) + torch.testing.assert_close(model.variable.detach().cpu(), torch.tensor([[1.25]])) + torch.testing.assert_close(loss.cpu(), torch.tensor(0.19140625)) + torch.testing.assert_close(diagonals[0].cpu(), torch.tensor([4 * 1.1])) + torch.testing.assert_close(diagonals[1].cpu(), torch.tensor([4 * 1.1 * 1.2])) diff --git a/tests/sparse/tuple/test_tuple_ops.py b/tests/sparse/tuple/test_tuple_ops.py new file mode 100644 index 0000000..c1dc9b9 --- /dev/null +++ b/tests/sparse/tuple/test_tuple_ops.py @@ -0,0 +1,434 @@ +import pytest +import torch + +from bae.sparse.tuple_ops import _tile_dispatch, bsr_diagonal, bsr_mv, bsr_transposed + + +@pytest.fixture(params=["cpu", "mps", "cuda"]) +def device(request): + name = request.param + if name == "mps" and not torch.backends.mps.is_available(): + pytest.skip("MPS unavailable") + if name == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA unavailable") + return name + + +def matrix(block, index_dtype, device, empty=False): + br, bc = block + crow = torch.tensor([0, 2, 2, 3, 3], dtype=index_dtype) + col = torch.tensor([0, 2, 2], dtype=index_dtype) + generator = torch.Generator().manual_seed(9) + values = torch.randn(3, br, bc, generator=generator) + if empty: + crow.zero_() + col, values = col[:0], values[:0] + dense = torch.zeros(4 * br, 5 * bc) + for row in range(4): + for k in range(int(crow[row]), int(crow[row + 1])): + column = int(col[k]) + dense[row * br:(row + 1) * br, column * bc:(column + 1) * bc] += values[k] + return tuple(t.to(device) for t in (crow, col, values)), dense + + +@pytest.mark.parametrize("block,index_dtype,empty", [ + ((1, 1), torch.int64, False), + ((2, 9), torch.int32, False), + ((2, 3), torch.int64, False), + ((5, 11), torch.int32, False), + ((3, 2), torch.int64, True), +]) +def test_tuple_products_match_dense(device, block, index_dtype, empty, monkeypatch): + A, dense = matrix(block, index_dtype, device, empty) + size = tuple(dense.shape) + originals = tuple(t.clone() for t in A) + + def no_sparse(*args, **kwargs): + raise AssertionError("Tuple operations must not construct native sparse tensors") + + for constructor in ("sparse_bsr_tensor", "sparse_csr_tensor", "sparse_coo_tensor"): + monkeypatch.setattr(torch, constructor, no_sparse) + generator = torch.Generator().manual_seed(11) + x = torch.randn(size[1], generator=generator) + r = torch.randn(size[0], generator=generator) + # Strided inputs ensure dispatch normalizes storage correctly. + x_storage = torch.stack((x, x), dim=-1).to(device) + x_device = x_storage[:, 0] + forward = bsr_mv(A, x_device, size=size) + backward = bsr_mv(A, r.to(device)[:, None], size=size, transpose=True) + torch.testing.assert_close(forward.cpu(), dense @ x, rtol=1e-4, atol=1e-5) + torch.testing.assert_close(backward.cpu(), (dense.T @ r)[:, None], rtol=1e-4, atol=1e-5) + torch.testing.assert_close( + bsr_diagonal(A, size=size).cpu(), dense.square().sum(0), rtol=1e-4, atol=1e-5, + ) + torch.testing.assert_close( + (forward * r.to(device)).sum(), (x_device * backward[:, 0]).sum(), + rtol=1e-4, atol=1e-5, + ) + for actual, original in zip(A, originals): + torch.testing.assert_close(actual, original) + torch.testing.assert_close(x_storage[:, 0].cpu(), x) + + +def test_tuple_product_duplicate_coordinates(device): + # Matvec accepts duplicate blocks, though diagonal extraction requires + # canonical input (the Jacobian materializer coalesces first). + A = ( + torch.tensor([0, 2], device=device), + torch.tensor([0, 0], device=device), + torch.tensor([[[2.0, 3.0]], [[-1.0, 4.0]]], device=device), + ) + x = torch.tensor([5.0, 2.0], device=device) + torch.testing.assert_close(bsr_mv(A, x, size=(1, 2)), torch.tensor([19.0], device=device)) + torch.testing.assert_close( + bsr_mv(A, torch.tensor([2.0], device=device), size=(1, 2), transpose=True), + torch.tensor([2.0, 14.0], device=device), + ) + + +def test_tuple_validation(): + A, dense = matrix((2, 3), torch.int64, "cpu") + with pytest.raises(ValueError): + bsr_mv(A, torch.zeros(dense.shape[1], 2), size=tuple(dense.shape)) + with pytest.raises(ValueError, match="Expected x"): + bsr_mv(A, torch.zeros(1), size=tuple(dense.shape)) + with pytest.raises(ValueError, match="divisible"): + bsr_mv(A, torch.zeros(1), size=(7, 15)) + with pytest.raises(TypeError, match="same int32 or int64"): + bsr_mv((A[0].int(), A[1], A[2]), torch.zeros(15), size=(8, 15)) + + +# The affine, aliasing, and zero-coefficient contracts below follow +# NVIDIA Warp release-1.19 warp/_src/sparse.py:bsr_mv. +_TILES = [-1, 33, 64] + + +@pytest.mark.parametrize("tile_size", _TILES) +@pytest.mark.parametrize("index_dtype", [torch.int32, torch.int64]) +@pytest.mark.parametrize("transpose", [False, True]) +def test_warp_affine_product_updates_and_returns_y(device, tile_size, index_dtype, transpose): + A, dense = matrix((2, 3), index_dtype, device) + operator = dense.T if transpose else dense + x_cpu = torch.linspace(-1.5, 2., operator.shape[1]) + y_cpu = torch.linspace(3., -2., operator.shape[0]) + x = x_cpu.to(device) + y = y_cpu.to(device).clone() + if transpose: + x, y = x[:, None], y[:, None] + expected = -1.75 * (operator @ x_cpu) + 0.25 * y_cpu + originals = tuple(part.clone() for part in A) + + actual = bsr_mv(A, x, y, -1.75, 0.25, transpose, None, tile_size, size=tuple(dense.shape)) + + assert actual is y + torch.testing.assert_close(actual.reshape(-1).cpu(), expected, rtol=1e-4, atol=1e-5) + torch.testing.assert_close(x.reshape(-1).cpu(), x_cpu) + for part, original in zip(A, originals): + torch.testing.assert_close(part, original) + + +@pytest.mark.parametrize("transpose", [False, True]) +def test_warp_missing_y_ignores_beta(device, transpose): + A, dense = matrix((2, 3), torch.int32, device) + operator = dense.T if transpose else dense + x = torch.linspace(-1., 1., operator.shape[1], device=device) + actual = bsr_mv(A, x, alpha=0.5, beta=float("nan"), transpose=transpose, + size=tuple(dense.shape)) + torch.testing.assert_close(actual.cpu(), 0.5 * (operator @ x.cpu()), rtol=1e-4, atol=1e-5) + + +@pytest.mark.parametrize("tile_size", [-1, 64]) +@pytest.mark.parametrize("transpose", [False, True]) +@pytest.mark.parametrize("alpha,beta", [(0., -2.), (0., 0.), (1.5, 0.)]) +def test_warp_zero_coefficients_do_not_read_nan_operands(device, tile_size, transpose, alpha, beta): + A, dense = matrix((2, 3), torch.int64, device) + operator = dense.T if transpose else dense + x = torch.arange(operator.shape[1], dtype=torch.float32, device=device) + y = torch.arange(operator.shape[0], dtype=torch.float32, device=device) + expected = (alpha * (operator @ x.cpu())) + beta * y.cpu() + if alpha == 0: + A[2].fill_(float("nan")) + x.fill_(float("nan")) + if beta == 0: + y.fill_(float("nan")) + + actual = bsr_mv(A, x, y=y, alpha=alpha, beta=beta, transpose=transpose, + tile_size=tile_size, size=tuple(dense.shape)) + + assert actual is y + assert torch.isfinite(actual).all() + torch.testing.assert_close(actual.cpu(), expected, rtol=1e-4, atol=1e-5) + + +@pytest.mark.parametrize("transpose", [False, True]) +@pytest.mark.parametrize("zero_coefficient", ["alpha", "beta"]) +def test_warp_coefficients_are_cast_before_zero_checks(device, transpose, zero_coefficient): + A, dense = matrix((2, 3), torch.int32, device) + operator = dense.T if transpose else dense + x = torch.ones(operator.shape[1], device=device) + y = torch.ones(operator.shape[0], device=device) + alpha, beta = 1., 2. + if zero_coefficient == "alpha": + alpha = 1e-50 # Nonzero Python float, zero in A's float32 scalar type. + x.fill_(float("nan")) + A[2].fill_(float("nan")) + expected = torch.full((operator.shape[0],), 2.) + else: + beta = 1e-50 + y.fill_(float("nan")) + expected = operator @ x.cpu() + actual = bsr_mv(A, x, y=y, alpha=alpha, beta=beta, transpose=transpose, + size=tuple(dense.shape)) + torch.testing.assert_close(actual.cpu(), expected, rtol=1e-4, atol=1e-5) + + +def _square_with_rectangular_blocks(device, index_dtype=torch.int64): + crow = torch.tensor([0, 2, 3, 4], dtype=index_dtype) + columns = torch.tensor([0, 1, 1, 0], dtype=index_dtype) + values = torch.arange(24, dtype=torch.float32).reshape(4, 2, 3) / 10 - 1 + dense = torch.zeros(6, 6) + for row in range(3): + for block in range(int(crow[row]), int(crow[row + 1])): + column = int(columns[block]) + dense[row * 2:(row + 1) * 2, column * 3:(column + 1) * 3] = values[block] + return tuple(part.to(device) for part in (crow, columns, values)), dense + + +@pytest.mark.parametrize("transpose", [False, True]) +@pytest.mark.parametrize("use_work_buffer", [False, True]) +def test_warp_x_y_alias_uses_saved_input(device, transpose, use_work_buffer): + A, dense = _square_with_rectangular_blocks(device) + original = torch.linspace(-1., 1., 6) + xy = original.to(device).clone() + work_buffer = torch.full((8,), 123., device=device) if use_work_buffer else None + expected = 1.5 * ((dense.T if transpose else dense) @ original) - 0.5 * original + + actual = bsr_mv(A, xy, xy, alpha=1.5, beta=-0.5, transpose=transpose, + work_buffer=work_buffer, size=(6, 6)) + + assert actual is xy + torch.testing.assert_close(actual.cpu(), expected, rtol=1e-4, atol=1e-5) + if use_work_buffer: + torch.testing.assert_close(work_buffer[:6].cpu(), original) + torch.testing.assert_close(work_buffer[6:].cpu(), torch.full((2,), 123.)) + + +@pytest.mark.parametrize("transpose", [False, True]) +def test_warp_work_buffer_is_unused_without_alias(device, transpose): + A, dense = _square_with_rectangular_blocks(device) + x, y = torch.ones(6, device=device), torch.empty(6, device=device) + # Deliberately insufficient and of the wrong type: unused buffers are ignored. + work_buffer = torch.tensor([7], dtype=torch.int32, device=device) + actual = bsr_mv(A, x, y=y, transpose=transpose, work_buffer=work_buffer, size=(6, 6)) + torch.testing.assert_close(actual.cpu(), (dense.T if transpose else dense) @ torch.ones(6)) + torch.testing.assert_close(work_buffer.cpu(), torch.tensor([7], dtype=torch.int32)) + + +@pytest.mark.parametrize("transpose", [False, True]) +def test_warp_block_shaped_vectors(device, transpose): + A, dense = matrix((2, 3), torch.int64, device) + operator = dense.T if transpose else dense + input_shape = (4, 2) if transpose else (5, 3) + output_shape = (5, 3) if transpose else (4, 2) + x = torch.arange(operator.shape[1], dtype=torch.float32, device=device).reshape(input_shape) + expected = (operator @ x.reshape(-1).cpu()).reshape(output_shape) + + allocated = bsr_mv(A, x, transpose=transpose, size=tuple(dense.shape)) + assert allocated.shape == output_shape + torch.testing.assert_close(allocated.cpu(), expected, rtol=1e-4, atol=1e-5) + y = torch.ones(output_shape, device=device) + actual = bsr_mv(A, x, y=y, beta=2., transpose=transpose, size=tuple(dense.shape)) + assert actual is y + torch.testing.assert_close(actual.cpu(), expected + 2., rtol=1e-4, atol=1e-5) + + +@pytest.mark.parametrize("transpose", [False, True]) +def test_warp_empty_matrix_only_scales_y(device, transpose): + A, dense = matrix((2, 3), torch.int32, device, empty=True) + operator = dense.T if transpose else dense + x = torch.full((operator.shape[1],), float("nan"), device=device) + y = torch.arange(operator.shape[0], dtype=torch.float32, device=device) + expected = -0.25 * y.cpu() + actual = bsr_mv(A, x, y=y, alpha=3., beta=-0.25, transpose=transpose, + size=tuple(dense.shape)) + assert actual is y + torch.testing.assert_close(actual.cpu(), expected) + + +@pytest.mark.parametrize("tile_size", [-1, 64]) +@pytest.mark.parametrize("transpose", [False, True]) +@pytest.mark.parametrize("empty,alpha", [(False, float("nan")), (True, float("inf"))]) +def test_warp_empty_rows_with_nonfinite_alpha(device, tile_size, transpose, empty, alpha): + A, dense = matrix((2, 3), torch.int32, device, empty=empty) + operator = dense.T if transpose else dense + x = torch.ones(operator.shape[1], device=device) + y = torch.arange(operator.shape[0], dtype=torch.float32, device=device) + empty_outputs = (operator == 0).all(dim=1) + if transpose: + # Warp never scatter-adds into unreferenced columns, so alpha is not + # applied to those outputs even when it is NaN or infinity. + expected = 2 * y.cpu()[empty_outputs] + else: + # Forward scalar/tiled kernels scale the zero row sum by alpha. + expected = torch.full((int(empty_outputs.sum()),), float("nan")) + actual = bsr_mv(A, x, y=y, alpha=alpha, beta=2., transpose=transpose, + tile_size=tile_size, size=tuple(dense.shape)) + torch.testing.assert_close(actual.cpu()[empty_outputs], expected, equal_nan=True) + + +@pytest.mark.parametrize("size", [(0, 6), (4, 0), (0, 0)]) +@pytest.mark.parametrize("transpose", [False, True]) +def test_warp_zero_dimensions(device, size, transpose): + A = ( + torch.zeros(size[0] // 2 + 1, dtype=torch.int64, device=device), + torch.empty(0, dtype=torch.int64, device=device), + torch.empty(0, 2, 3, device=device), + ) + input_size, output_size = size if transpose else size[::-1] + x = torch.full((input_size,), float("nan"), device=device) + y = torch.arange(output_size, dtype=torch.float32, device=device) + expected = 2 * y.cpu() + actual = bsr_mv(A, x, y=y, beta=2., transpose=transpose, size=size) + assert actual is y + torch.testing.assert_close(actual.cpu(), expected) + + +@pytest.mark.parametrize("tile_size", _TILES) +@pytest.mark.parametrize("index_dtype", [torch.int32, torch.int64]) +def test_warp_long_rows_and_empty_rows(device, tile_size, index_dtype): + # 129 * 3 scalar entries per populated subrow exceeds Warp's auto-tile + # threshold, including the empty middle row in the average. + crow = torch.tensor([0, 129, 129, 258], dtype=index_dtype, device=device) + columns = torch.arange(129, dtype=index_dtype, device=device).repeat(2) + values = torch.linspace(-0.1, 0.2, 258 * 2 * 3, device=device).reshape(258, 2, 3) + x = torch.linspace(-0.5, 0.5, 129 * 3, device=device) + dense = torch.zeros(6, 129 * 3) + dense[:2] = values[:129].cpu().permute(1, 0, 2).reshape(2, -1) + dense[4:] = values[129:].cpu().permute(1, 0, 2).reshape(2, -1) + y = torch.arange(6, dtype=torch.float32, device=device) + expected = 0.75 * (dense @ x.cpu()) - 2 * y.cpu() + actual = bsr_mv((crow, columns, values), x, y=y, alpha=0.75, beta=-2., + tile_size=tile_size, size=tuple(dense.shape)) + torch.testing.assert_close(actual.cpu(), expected, rtol=2e-4, atol=1e-5) + + +def _check_affine_product_with_long_mixed_and_empty_rows(device, block_shape, index_dtype, tile_size): + block_rows, block_cols = block_shape + crow = torch.tensor([0, 129, 130, 130, 259, 259], dtype=index_dtype) + columns = torch.cat([torch.arange(129, dtype=index_dtype), + torch.tensor([7], dtype=index_dtype), + torch.arange(129, dtype=index_dtype)]) + generator = torch.Generator().manual_seed(19) + values = torch.randn(259, block_rows, block_cols, generator=generator) / 10 + size = (5 * block_rows, 129 * block_cols) + dense = _dense_from_tuple((crow, columns, values.double()), size) + x_cpu = torch.linspace(-0.75, 1.25, size[1]) + y_cpu = torch.linspace(2., -1., size[0]) + expected = -1.75 * (dense @ x_cpu.double()) + 0.25 * y_cpu.double() + A = tuple(part.to(device) for part in (crow, columns, values)) + x, y = x_cpu.to(device), y_cpu.to(device).clone() + + actual = bsr_mv(A, x, y=y, alpha=-1.75, beta=0.25, + tile_size=tile_size, size=size) + + assert actual is y + torch.testing.assert_close(actual.cpu().double(), expected, rtol=2e-4, atol=1e-5) + torch.testing.assert_close(x.cpu(), x_cpu) + + +@pytest.mark.skipif(not torch.backends.mps.is_available(), reason="Metal kernels require MPS") +@pytest.mark.parametrize("block_rows", [2, 3]) +@pytest.mark.parametrize("index_dtype", [torch.int32, torch.int64]) +def test_scalar_camera_blocks_with_long_mixed_and_empty_rows(block_rows, index_dtype): + # br=2 exercises the camera specialization; br=3 must retain the general + # row path. The long rows would otherwise select Warp's tiled kernel. + _check_affine_product_with_long_mixed_and_empty_rows("mps", (block_rows, 9), index_dtype, -1) + + +@pytest.mark.skipif(not torch.backends.mps.is_available(), reason="Metal kernels require MPS") +@pytest.mark.parametrize("block_shape,tile_size", [ + ((3, 2), -1), + ((9, 2), -1), + ((9, 2), 64), + ((9, 2), 32), # Other tile sizes keep their general block-dimension path. + ((8, 2), 64), # Other block heights keep the general tiled kernel. +]) +@pytest.mark.parametrize("index_dtype", [torch.int32, torch.int64]) +def test_cached_transpose_block_kernels_with_long_mixed_and_empty_rows(block_shape, tile_size, index_dtype): + # These are ordinary forward products of pretransposed BSR storage, not + # the atomic transpose kernel. Each case includes two long rows, one short + # row, an internal empty row, and an empty trailing row. + _check_affine_product_with_long_mixed_and_empty_rows("mps", block_shape, index_dtype, tile_size) + + +def test_warp_output_and_alias_work_buffer_validation(device): + A, _ = _square_with_rectangular_blocks(device) + x = torch.ones(6, device=device) + with pytest.raises(ValueError): + bsr_mv(A, x, y=torch.zeros(5, device=device), size=(6, 6)) + with pytest.raises((TypeError, ValueError)): + bsr_mv(A, x, y=torch.zeros(6, dtype=torch.int32, device=device), size=(6, 6)) + with pytest.raises(ValueError): + bsr_mv(A, x, y=torch.zeros(6, 2, device=device)[:, 0], size=(6, 6)) + with pytest.raises(ValueError): + bsr_mv(A, x, y=x, work_buffer=torch.empty(5, device=device), size=(6, 6)) + with pytest.raises((TypeError, ValueError)): + bsr_mv(A, x, y=x, work_buffer=torch.empty(6, dtype=torch.int32, device=device), size=(6, 6)) + + +def _dense_from_tuple(A, size): + crow, columns, values = (part.cpu() for part in A) + result = torch.zeros(size, dtype=values.dtype) + br, bc = values.shape[-2:] + for row in range(crow.numel() - 1): + for block in range(int(crow[row]), int(crow[row + 1])): + column = int(columns[block]) + result[row * br:(row + 1) * br, column * bc:(column + 1) * bc] += values[block] + return result + + +@pytest.mark.parametrize("index_dtype", [torch.int32, torch.int64]) +@pytest.mark.parametrize("empty", [False, True]) +def test_bsr_transposed_preserves_full_shape_and_owns_values(device, index_dtype, empty): + A, dense = matrix((2, 3), index_dtype, device, empty=empty) + size = tuple(dense.shape) + originals = tuple(part.clone() for part in A) + transposed = bsr_transposed(A, size=size) + + assert transposed[0].shape == (6,) # Includes the two trailing empty column blocks. + assert transposed[2].shape[-2:] == (3, 2) + assert transposed[0].dtype == transposed[1].dtype == index_dtype + torch.testing.assert_close(_dense_from_tuple(transposed, size[::-1]), dense.T) + restored = bsr_transposed(transposed, size=size[::-1]) + assert restored[0].shape == A[0].shape + torch.testing.assert_close(_dense_from_tuple(restored, size), dense) + + residual = torch.linspace(-1., 1., size[0], device=device) + torch.testing.assert_close( + bsr_mv(transposed, residual, size=size[::-1]).cpu(), + dense.T @ residual.cpu(), rtol=1e-4, atol=1e-5, + ) + for actual, original in zip(A, originals): + torch.testing.assert_close(actual, original) + A[2].add_(7.) + torch.testing.assert_close(_dense_from_tuple(transposed, size[::-1]), dense.T) + + +@pytest.mark.parametrize( + "nnz,br,bc,rows,device,tile,expected", + [ + (128, 2, 1, 2, "mps", 0, (False, 64)), + (129, 2, 1, 2, "mps", 0, (True, 64)), + (128, 2, 1, 2, "cuda", 0, (False, 64)), + (129, 2, 1, 2, "cuda", 0, (True, 64)), + (129, 2, 1, 2, "cpu", 0, (False, 64)), + (42, 2, 3, 2, "mps", 0, (False, 64)), + (43, 2, 3, 2, "mps", 0, (True, 64)), + (0, 2, 3, 0, "mps", 0, (False, 64)), + (0, 2, 3, 4, "cpu", 32, (True, 32)), + (1000, 2, 3, 4, "mps", -7, (False, -7)), + ], +) +def test_warp_tile_selection_threshold(nnz, br, bc, rows, device, tile, expected): + # Equality must stay scalar: Warp uses a strict greater-than threshold. + assert _tile_dispatch(nnz, br, bc, rows, device, tile) == expected diff --git a/tests/sparse/tuple/test_tuple_tensor.py b/tests/sparse/tuple/test_tuple_tensor.py new file mode 100644 index 0000000..dee5dce --- /dev/null +++ b/tests/sparse/tuple/test_tuple_tensor.py @@ -0,0 +1,177 @@ +"""Tensor dispatch for component-backed BSR matrices and mixed-width Jacobians.""" + +import pytest +import torch + +from bae.sparse import BSRTensor + + +DEVICES = ["cpu", pytest.param("mps", marks=pytest.mark.skipif( + not torch.backends.mps.is_available(), reason="MPS unavailable")), + pytest.param("cuda", marks=pytest.mark.skipif( + not torch.cuda.is_available(), reason="CUDA unavailable"))] + + +def _matrix(device, width=3, index_dtype=torch.int64, duplicates=False): + # Internal empty rows and trailing unused column blocks must survive every + # wrapper operation. Optional duplicates are deliberately non-adjacent. + crow = torch.tensor([0, 3, 3, 4] if duplicates else [0, 2, 2, 3], + dtype=index_dtype, device=device) + col = torch.tensor([1, 0, 1, 0] if duplicates else [0, 1, 0], + dtype=index_dtype, device=device) + values = torch.arange(col.numel() * 2 * width, dtype=torch.float32, + device=device).reshape(-1, 2, width) / 7 - 1 + return BSRTensor(crow, col, values, size=(6, 3 * width), + is_coalesced=not duplicates) + + +def _dense_reference(matrix): + crow, col, values = (component.detach().cpu().clone() for component in matrix.components) + result = torch.zeros(matrix.shape, dtype=values.dtype) + br, bc = values.shape[-2:] + for row in range(crow.numel() - 1): + for entry in range(int(crow[row]), int(crow[row + 1])): + column = int(col[entry]) + result[row * br:(row + 1) * br, column * bc:(column + 1) * bc] += values[entry] + return result + + +@pytest.mark.parametrize("device", DEVICES) +@pytest.mark.parametrize("index_dtype", [torch.int32, torch.int64]) +def test_tensor_metadata_and_addition_coalesce_before_squaring(device, index_dtype, monkeypatch): + def forbidden(*args, **kwargs): + raise AssertionError("component-backed matrices must not construct native sparse tensors") + + for constructor in ("sparse_bsr_tensor", "sparse_bsc_tensor", "sparse_csr_tensor", + "sparse_csc_tensor", "sparse_coo_tensor"): + monkeypatch.setattr(torch, constructor, forbidden) + left = _matrix(device, index_dtype=index_dtype, duplicates=True) + right = _matrix(device, index_dtype=index_dtype) + before = [component.clone() for component in left.components + right.components] + left_dense, right_dense = _dense_reference(left), _dense_reference(right) + assert isinstance(left, torch.Tensor) + assert left.shape == left.size() == (6, 9) + assert left.ndim == 2 and left.numel() == 54 + assert left.device.type == device and left.dtype == torch.float32 + assert left.crow_indices() is left.components[0] + assert left.col_indices() is left.components[1] + assert left.values() is left.components[2] + for result, expected in ((left + right, left_dense + right_dense), + (torch.add(left, right, alpha=-0.5), left_dense - 0.5 * right_dense)): + assert isinstance(result, BSRTensor) and result.shape == left.shape + assert result.values().shape[0] == 3 + torch.testing.assert_close(result.to_dense().cpu(), expected) + torch.testing.assert_close(result.normal_diagonal().cpu(), expected.square().sum(0)) + torch.testing.assert_close(left.normal_diagonal().cpu(), left_dense.square().sum(0)) + for component, original in zip(left.components + right.components, before): + torch.testing.assert_close(component, original) + + +@pytest.mark.parametrize("device", DEVICES) +@pytest.mark.parametrize("columns", [None, 0, 1, 3]) +def test_cat_with_different_block_widths_uses_tensor_products(device, columns): + camera, point = _matrix(device, 3), _matrix(device, 2) + unused = BSRTensor( + torch.zeros(4, dtype=torch.int64, device=device), + torch.empty(0, dtype=torch.int64, device=device), + camera.values().new_empty((0, 2, 2)), size=(6, 4), is_coalesced=True, + ) + jacobian = torch.cat([camera, unused, point], dim=-1) + expected = torch.cat([_dense_reference(camera), torch.zeros(6, 4), _dense_reference(point)], dim=1) + assert isinstance(jacobian, torch.Tensor) and jacobian.shape == (6, 19) + for actual, dense in ((jacobian, expected), (jacobian.mT, expected.mT), + (torch.cat([camera, camera], dim=0), torch.cat([_dense_reference(camera)] * 2))): + shape = (dense.shape[1],) if columns is None else (dense.shape[1], columns) + vector = torch.arange(torch.Size(shape).numel(), dtype=torch.float32).reshape(shape) / 13 + out = torch.empty((dense.shape[0], *shape[1:]), device=device) + assert torch.matmul(actual, vector.to(device), out=out) is out + torch.testing.assert_close(out.cpu(), dense @ vector, rtol=2e-5, atol=2e-5) + torch.testing.assert_close((actual @ vector.to(device)).cpu(), dense @ vector, + rtol=2e-5, atol=2e-5) + torch.testing.assert_close(actual.to_dense().cpu(), dense) + torch.testing.assert_close(actual.normal_diagonal().cpu(), dense.square().sum(0)) + torch.testing.assert_close(jacobian.T.to_dense().cpu(), expected.T) + torch.testing.assert_close(jacobian.transpose(0, 1).to_dense().cpu(), expected.T) + for _ in range(2): + torch.testing.assert_close(torch.transpose(jacobian, 0, 1).to_dense().cpu(), expected.T) + torch.testing.assert_close(torch.t(jacobian).to_dense().cpu(), expected.T) + + +@pytest.mark.parametrize("device", DEVICES) +def test_transpose_cache_tracks_value_and_index_mutation(device): + matrix = _matrix(device) + transpose = matrix.mT + residual = torch.linspace(-1, 1, 6, device=device) + for update in (lambda: None, lambda: matrix.values().mul_(2), + lambda: matrix.col_indices().zero_()): + update() + dense = _dense_reference(matrix) + torch.testing.assert_close((transpose @ residual).cpu(), dense.T @ residual.cpu(), + rtol=2e-5, atol=2e-5) + torch.testing.assert_close(matrix.normal_diagonal().cpu(), dense.square().sum(0)) + + +@pytest.mark.parametrize("device", DEVICES) +@pytest.mark.parametrize("component", ["values", "indices"]) +def test_detached_alias_mutations_invalidate_transpose_and_coalescing(device, component): + matrix = _matrix(device) + transpose = matrix.mT + residual = torch.linspace(-1, 1, 6, device=device) + # Populate the transpose before creating the detached alias. Mutations via + # that alias must invalidate both stored values and canonical-index state. + transpose @ residual + alias = matrix.detach() + if component == "values": + alias.values().add_(1) + else: + alias.col_indices().zero_() + dense = _dense_reference(matrix) + for view in (matrix, alias): + torch.testing.assert_close(view.normal_diagonal().cpu(), dense.square().sum(0)) + torch.testing.assert_close((transpose @ residual).cpu(), dense.T @ residual.cpu(), + rtol=2e-5, atol=2e-5) + + +@pytest.mark.parametrize("device", DEVICES) +def test_copy_detach_and_transfer_preserve_sparse_storage(device): + matrix = _matrix(device, index_dtype=torch.int32) + for original in (matrix, torch.cat([matrix, matrix], dim=1)): + dense = original.to_dense().cpu() + copied, detached = original.clone(), original.detach() + assert isinstance(copied, torch.Tensor) and isinstance(detached, torch.Tensor) + torch.testing.assert_close(copied.to_dense().cpu(), dense) + torch.testing.assert_close(detached.to_dense().cpu(), dense) + assert not detached.requires_grad + # Native MPS tensors require transfer before a float64 conversion. + converted = original.to(device="cpu").to(dtype=torch.float64) + assert converted.dtype == torch.float64 and converted.device.type == "cpu" + torch.testing.assert_close(converted.to_dense(), dense.double()) + detached = matrix.detach() + clone = matrix.clone() + assert all(a.data_ptr() == b.data_ptr() for a, b in zip(detached.components, matrix.components)) + assert all(a.data_ptr() != b.data_ptr() for a, b in zip(clone.components, matrix.components)) + converted = matrix.to(device="cpu").to(dtype=torch.float64) + assert converted.crow_indices().dtype == converted.col_indices().dtype == torch.int32 + assert isinstance(matrix.data, BSRTensor) + + +@pytest.mark.parametrize("device", DEVICES) +def test_matmul_output_can_alias_input(device): + matrix = _matrix(device, width=2) + dense = _dense_reference(matrix) + for actual, reference in ((matrix, dense), (matrix.mT, dense.T), + (torch.cat([matrix], dim=1), dense)): + vector = torch.linspace(-1, 1, 6, device=device) + expected = reference @ vector.cpu() + assert torch.matmul(actual, vector, out=vector) is vector + torch.testing.assert_close(vector.cpu(), expected, rtol=2e-5, atol=2e-5) + + +def test_unsupported_tensor_operations_fail_without_densifying(): + matrix = _matrix("cpu") + with pytest.raises((NotImplementedError, TypeError)): + torch.sin(matrix) + with pytest.raises((ValueError, NotImplementedError, TypeError)): + matrix + torch.ones(matrix.shape) + with pytest.raises((ValueError, RuntimeError)): + torch.cat([matrix, _matrix("cpu", width=2)], dim=0) diff --git a/tests/test_normal_operator.py b/tests/test_normal_operator.py index b101514..6771ef8 100644 --- a/tests/test_normal_operator.py +++ b/tests/test_normal_operator.py @@ -1,10 +1,51 @@ import pytest +import subprocess +import sys import torch from bae.utils.linear_operator import NormalMatVec from bae.utils.pysolvers import PCG +@pytest.mark.parametrize('layout', ['csr', 'bsr']) +@pytest.mark.parametrize('device', ['cpu', pytest.param('cuda', marks=pytest.mark.skipif( + not torch.cuda.is_available(), reason='CUDA is unavailable'))]) +def test_standalone_pcg_import_solves_native_sparse_without_prior_registrations(layout, device): + # A subprocess is essential: importing bae.optim or collecting graph tests + # installs sparse diagonal registrations and masked this import-order bug. + script = ''' +import importlib.abc +import sys +import torch + +class BlockOptionalBackends(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname == "bae.sparse.solve": + raise ModuleNotFoundError("CuDSS is optional", name=fullname) + if fullname.split(".")[0] == "warp": + raise ModuleNotFoundError("Warp is optional", name=fullname) + +sys.meta_path.insert(0, BlockOptionalBackends()) +from bae.utils.pysolvers import PCG +device = sys.argv[2] +dense = torch.tensor([[4., 1.], [1., 3.]], dtype=torch.float64, device=device) +rhs = torch.tensor([1., 2.], dtype=torch.float64, device=device) +if sys.argv[1] == "csr": + matrix = dense.to_sparse_csr() +else: + matrix = dense.to_sparse_bsr((2, 2)) + # A zero RHS still constructs the BSR diagonal preconditioner, but does + # not require the MKL BSR matvec absent from macOS CPU wheels. + if device == "cpu" and not torch.backends.mkl.is_available(): + rhs.zero_() +actual = PCG(maxiter=10, tol=1e-10)(matrix, rhs) +torch.testing.assert_close(actual, torch.linalg.solve(dense, rhs)) +torch.testing.assert_close(matrix.to_dense(), dense) +''' + result = subprocess.run([sys.executable, '-c', script, layout, device], capture_output=True, text=True) + assert result.returncode == 0, result.stderr + + def test_normal_matvec_dense_matches_explicit(): torch.manual_seed(0) m, n = 8, 5 @@ -50,6 +91,7 @@ def test_normal_matvec_sparse_csr_matches_explicit_and_cached_diag(): torch.testing.assert_close(y_op, y_ex, rtol=1e-10, atol=1e-10) +@pytest.mark.skipif(not torch.backends.mkl.is_available(), reason="Native CPU BSR matvec requires MKL") def test_normal_matvec_sparse_bsr_matches_explicit(): torch.manual_seed(3) m, n = 6, 4