You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat: preconditioner support for iterative solvers (#29) - #128
bicgstab takes preconditioner= like gmres, linear_cg and minres. BICGSTABSettings.precon still works but is deprecated (DeprecationWarning), and setting both is an error. The docstring now says BiCGSTAB is right-preconditioned, which matches the implementation.
linear_cg and minres also accept a matrix, so all four solvers take a tensor or a callable.
New torchsparsegradutils.utils.preconditioners:
Preconditioner: an abstract base class with transpose()/.T, is_symmetric and is_positive_definite.
JacobiPreconditioner(A, absolute=False): zeros on the diagonal are replaced by 1. absolute=True gives a symmetric positive definite preconditioner for MINRES on indefinite A.
MatrixPreconditioner(M_inv): wraps an explicit matrix and can transpose it (dense, COO or CSR).
New sparse_diagonal(A) helper for COO, CSR and dense matrices. It sums duplicate COO entries and is differentiable.
2. Correct preconditioning in the backward pass of sparse_generic_solve
New keyword-only preconditioner= and transpose_preconditioner= arguments, mirroring solve/transpose_solve.
Before this change, a preconditioner passed through **kwargs was reused unchanged for the transposed system Aᵀ in the backward pass. Jacobi happens to work because A and Aᵀ share a diagonal, but a nonsymmetric M slows convergence. The gradients themselves were never wrong. Now:
a Preconditioner instance supplies its transpose(), computed only when gradients are needed;
a tensor is wrapped in MatrixPreconditioner;
a Preconditioner subclass, e.g. preconditioner=JacobiPreconditioner, is built from A.detach();
a plain callable has no known transpose, so its transpose is never guessed. When gradients are required, transpose_preconditioner must also be given (the same callable if M is symmetric), otherwise a ValueError is raised. A plain callable given only as transpose_preconditioner always raises;
sparse_generic_symmetric_solve passes the same preconditioner for both systems, which is exact since Aᵀ = A.
The preconditioner is only forwarded to solve when one is set, so custom solvers without that argument keep working.
sparse_generic_symmetric_solve takes preconditioner= and warns when MINRES or CG gets a Preconditioner that isn't known to be positive definite.
Only Preconditioner subclasses act as "build from A" factories. An arbitrary callable A -> M can't be told apart from a callable X -> M⁻¹X, so allowing both would be ambiguous.
3. sparse_mm broadcasting (added after review)
For a 2D sparse A, sparse_mm now follows torch.matmul broadcasting: a vector (m,) gives (n,), and a batch (*batch, m, p) gives (*batch, n, p). Gradients with respect to A stay sparse. These inputs used to raise an error, so this only adds behaviour; the error messages for invalid shapes changed.
MatrixPreconditioner applies sparse matrices with sparse_mm and accepts batched dense matrices. It no longer detaches its matrix. All four solvers wrap a tensor preconditioner in MatrixPreconditioner, so a sparse preconditioner works with batched right-hand sides.
Tests
New tests/test_preconditioners.py (37 tests). It covers sparse_diagonal and the two new preconditioner classes for each layout and input shape. On a badly scaled system, Jacobi cuts iterations or matrix-vector products by more than half for each solver. A recording solver checks that the backward pass receives exactly Mᵀ for a nonsymmetric M, and gradients are compared with torch.linalg.solve. The test also covers each way of passing a preconditioner, the transpose being computed only when needed, and the MINRES warning.
test_bicgstab.py now uses the new keyword and adds a test for the deprecation.
Locally on macOS, the full suite has the same failures as main: the torch build there has no MKL, which sparse triangular solves need on CPU. The branch adds 38 passing tests. CUDA was not tested locally.
Follow-ups (not in this PR)
Block-Jacobi and Chebyshev/polynomial preconditioners, which are cheap in memory and work well on GPU, and IC/ILU through a backend. Right preconditioning for lsmr/sparse_generic_lstsq.
…ner (#29)
- bicgstab takes a `preconditioner` keyword like gmres, linear_cg and minres;
BICGSTABSettings.precon is deprecated. Its docstring now says it is
right-preconditioned, which matches the implementation.
- linear_cg and minres also accept a matrix as preconditioner.
- New utils.preconditioners module: a Preconditioner base class with
transpose() and symmetry/positive-definiteness flags, JacobiPreconditioner
and MatrixPreconditioner.
- New sparse_diagonal helper for COO, CSR and dense matrices.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…backward (#29)
sparse_generic_solve gains keyword-only `preconditioner` and
`transpose_preconditioner` arguments, mirroring solve/transpose_solve.
The backward pass now preconditions the transposed system with M^{-T}
instead of reusing M^{-1}:
- a Preconditioner instance supplies its transpose(), computed only when
gradients are required;
- a matrix is wrapped in MatrixPreconditioner;
- a Preconditioner subclass is built from the detached A;
- a plain callable is reused for the backward pass, as before, unless a
transpose_preconditioner is given.
sparse_generic_symmetric_solve forwards `preconditioner` and warns when
MINRES or CG is given a preconditioner not known to be positive definite.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- MatrixPreconditioner folds batch dimensions into the columns for sparse
matrices, whose matmul does not broadcast over (*batch, n, k).
- The JacobiPreconditioner example used a singular matrix, so its CG call
failed; use an SPD one and run the module's doctests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Wrap sparse tensor preconditioners for batched linear_cg RHS
torchsparsegradutils/utils/linear_cg.py:338
A sparse COO/CSR tensor preconditioner still fails for the leading batch dimensions supported by linear_cg: exposing .matmul directly cannot multiply a 2-D sparse matrix by a (*batch, n, k) residual. MatrixPreconditioner already implements the required flatten/restore path, so tensor inputs should be wrapped with it; the solver tensor test should also include a sparse preconditioner with a batched RHS.
Wrap sparse tensor preconditioners for batched minres RHS
torchsparsegradutils/utils/minres.py:356
A sparse COO/CSR tensor preconditioner still fails for the leading batch dimensions supported by minres: exposing .matmul directly cannot multiply a 2-D sparse matrix by a (*batch, n, k) residual. MatrixPreconditioner already implements the required flatten/restore path, so tensor inputs should be wrapped with it; the solver tensor test should also include a sparse preconditioner with a batched RHS.
…NRES and GMRES
A sparse COO/CSR tensor passed directly as preconditioner was applied via
.matmul, which does not broadcast over leading batch dimensions. Route
sparse tensors through MatrixPreconditioner; dense tensors keep .matmul so
batched dense preconditioners still broadcast.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The public module documentation incorrectly claims every utility solver supports preconditioning, although LSMR does not.
0 open findings
Previously missed (1)
In code that hasn't changed since last review
Scope “all solvers” claim to the four supported solvers
torchsparsegradutils/utils/preconditioners.py:6
lsmr is also part of torchsparsegradutils.utils' documented iterative solvers, but its public signature has no preconditioner argument. Thus “All solvers” advertises unsupported behavior (and conflicts with the PR's stated LSMR follow-up); scope this claim to the four supported linear-system solvers.
For a 2D sparse A, sparse_mm now follows torch.matmul broadcasting: a
vector (m,) gives (n,) and a batch (*batch, m, p) gives (*batch, n, p),
by folding the batch into the columns around SparseMatMul. Gradients with
respect to A stay sparse. Native sparse matmul rejects the batched case
("expand is unsupported for Sparse tensors"). These inputs used to raise,
so the change is additive; error messages for invalid ranks are updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- MatrixPreconditioner applies sparse matrices with sparse_mm instead of
folding batch dimensions itself, and accepts batched dense matrices
(*batch, n, n), transposed with mT. It no longer detaches, so gradients
flow (sparse) when a solver is differentiated directly.
- linear_cg, minres, gmres and bicgstab wrap tensor preconditioners in
MatrixPreconditioner; the _matrix_operator helper is removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… detach
- Fold batch dimensions with flatten(1) rather than reshape(inner, -1),
which cannot infer the size when the inner dimension is zero.
- The preconditioners module docstring now says that only preconditioners
built from A detach it; MatrixPreconditioner keeps its matrix and is
differentiable when applied directly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
JacobiPreconditioner no longer detaches A, matching MatrixPreconditioner
and the torch convention that functions do not silently cut the graph.
sparse_generic_solve still builds a Preconditioner subclass from
A.detach(), as its implicit-function gradients do not depend on M.
The preconditioners module docs now explain when preconditioner
gradients matter: never for sparse_generic_solve, but they do when
backpropagating through the iterations of a solver called directly,
e.g. to learn a preconditioner.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Callable transpose preconditioner incorrectly reused for forward solve
torchsparsegradutils/sparse_solve.py:313
When only a plain callable transpose_preconditioner is supplied, _as_preconditioner leaves it as a callable and this branch reuses that same operator for the forward system. That callable is documented as approximating A^{-T}, so it is not generally a valid approximation of A^{-1} and can make the forward solve converge poorly or fail. Only derive the forward preconditioner when the resolved transpose value is a Preconditioner (tensor/class inputs become one); otherwise leave the forward solve unpreconditioned. The corresponding docs and a callable-only regression test should be updated as well.
🧠 Review effort: Balanced
Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.
A plain callable approximating A^{-T} has no known transpose, so reusing
it for the forward solve was unjustified. Unlike a plain forward
preconditioner, which is reused for the backward pass for backward
compatibility, the new transpose_preconditioner argument has no legacy
behaviour to keep, so ask for an explicit preconditioner instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Preconditioners in sparse_generic_solve are new in this PR, so there is
no earlier behaviour to keep. A plain callable has no known transpose,
so it is no longer reused for the other system in either direction:
- `preconditioner=f` alone works when no gradient is required; when one
is, a ValueError asks for transpose_preconditioner too (the same
callable if M is symmetric) or a Preconditioner.
- `transpose_preconditioner=f` alone always raises.
sparse_generic_symmetric_solve passes the same preconditioner for both
systems, which is exact since A^T = A.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Bring in correctness and test-stability history through f03ecc9. Resolve sparse_mm conflicts while preserving preconditioning branch broadcasting and PR #123's COO uniqueness, gradient-ordering and inference contracts.
da8b9ef: request tighter solver tolerances in tensor-preconditioner tests. MINRES defaults to 1e-4 while the dense-reference assertions use 1e-5; assertions and production defaults are unchanged.
9a99c6a: add vector/batch regressions for COO uniqueness checks, stored-coordinate gradients including explicit zeros, and no-grad/inference behaviour.
Validation on CPU and RTX 5090 with PyTorch 2.14.0.dev20260713+cu130: the added broadcasting cases passed in the affected-suite run; after the tolerance adjustment, the complete preconditioner, utility and doctest run passed 236 tests, 16 skipped. Ruff, formatting, type checking and wheel/sdist builds passed on the reviewed tree; commit hooks passed for both new test commits. This is affected-suite validation, not a full repository or PyTorch 2.5 run.
An independent Claude static review covered these changes and found no material correctness defects. Remaining follow-ups include release-note coverage of the callable-preconditioner compatibility change, avoiding an unnecessary CSR transpose in preconditioner resolution, and minimum-version/edge-case validation. This is not a final merge approval.
_resolve_preconditioners transposed A eagerly for any
transpose_preconditioner, but only a Preconditioner class is built from
A.T. Since the backward solve passes the forward preconditioner back as
transpose_preconditioner, every backward pass made an unused transposed
copy of A (a CSR -> CSC -> CSR conversion for CSR). The matrix is now
provided lazily.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #29.
Summary
Two commits, which can be reviewed separately:
1. One way to pass a preconditioner, plus Jacobi
bicgstabtakespreconditioner=likegmres,linear_cgandminres.BICGSTABSettings.preconstill works but is deprecated (DeprecationWarning), and setting both is an error. The docstring now says BiCGSTAB is right-preconditioned, which matches the implementation.linear_cgandminresalso accept a matrix, so all four solvers take a tensor or a callable.torchsparsegradutils.utils.preconditioners:Preconditioner: an abstract base class withtranspose()/.T,is_symmetricandis_positive_definite.JacobiPreconditioner(A, absolute=False): zeros on the diagonal are replaced by 1.absolute=Truegives a symmetric positive definite preconditioner for MINRES on indefiniteA.MatrixPreconditioner(M_inv): wraps an explicit matrix and can transpose it (dense, COO or CSR).sparse_diagonal(A)helper for COO, CSR and dense matrices. It sums duplicate COO entries and is differentiable.2. Correct preconditioning in the backward pass of
sparse_generic_solvepreconditioner=andtranspose_preconditioner=arguments, mirroringsolve/transpose_solve.**kwargswas reused unchanged for the transposed system Aᵀ in the backward pass. Jacobi happens to work because A and Aᵀ share a diagonal, but a nonsymmetric M slows convergence. The gradients themselves were never wrong. Now:Preconditionerinstance supplies itstranspose(), computed only when gradients are needed;MatrixPreconditioner;Preconditionersubclass, e.g.preconditioner=JacobiPreconditioner, is built fromA.detach();transpose_preconditionermust also be given (the same callable if M is symmetric), otherwise aValueErroris raised. A plain callable given only astranspose_preconditioneralways raises;sparse_generic_symmetric_solvepasses the same preconditioner for both systems, which is exact since Aᵀ = A.solvewhen one is set, so custom solvers without that argument keep working.sparse_generic_symmetric_solvetakespreconditioner=and warns when MINRES or CG gets aPreconditionerthat isn't known to be positive definite.Only
Preconditionersubclasses act as "build from A" factories. An arbitrary callableA -> Mcan't be told apart from a callableX -> M⁻¹X, so allowing both would be ambiguous.3.
sparse_mmbroadcasting (added after review)A,sparse_mmnow followstorch.matmulbroadcasting: a vector(m,)gives(n,), and a batch(*batch, m, p)gives(*batch, n, p). Gradients with respect toAstay sparse. These inputs used to raise an error, so this only adds behaviour; the error messages for invalid shapes changed.MatrixPreconditionerapplies sparse matrices withsparse_mmand accepts batched dense matrices. It no longer detaches its matrix. All four solvers wrap a tensor preconditioner inMatrixPreconditioner, so a sparse preconditioner works with batched right-hand sides.Tests
tests/test_preconditioners.py(37 tests). It coverssparse_diagonaland the two new preconditioner classes for each layout and input shape. On a badly scaled system, Jacobi cuts iterations or matrix-vector products by more than half for each solver. A recording solver checks that the backward pass receives exactly Mᵀ for a nonsymmetric M, and gradients are compared withtorch.linalg.solve. The test also covers each way of passing a preconditioner, the transpose being computed only when needed, and the MINRES warning.test_bicgstab.pynow uses the new keyword and adds a test for the deprecation.main: the torch build there has no MKL, which sparse triangular solves need on CPU. The branch adds 38 passing tests. CUDA was not tested locally.Follow-ups (not in this PR)
Block-Jacobi and Chebyshev/polynomial preconditioners, which are cheap in memory and work well on GPU, and IC/ILU through a backend. Right preconditioning for
lsmr/sparse_generic_lstsq.🤖 Generated with Claude Code