Skip to content

feat: preconditioner support for iterative solvers (#29) - #128

Open
tvercaut wants to merge 41 commits into
mainfrom
feat/preconditioning
Open

tvercaut wants to merge 41 commits into
mainfrom
feat/preconditioning

Conversation

@tvercaut

@tvercaut tvercaut commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

Closes #29.

Summary

Two commits, which can be reviewed separately:

1. One way to pass a preconditioner, plus Jacobi

  • 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.

🤖 Generated with Claude Code

tvercaut and others added 2 commits October 7, 2026 23:22
…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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Sparse matrix preconditioners violate the documented batched-input contract, and the Jacobi CG example uses a singular matrix.

2 open findings
What changed in this PR

Adds unified preconditioner support to iterative sparse solvers, addressing issue #29.

Changes:

  • Adds Jacobi and explicit-matrix preconditioners plus sparse diagonal extraction.
  • Correctly transposes preconditioners during backward solves.
  • Extends solver APIs and tests for tensor/callable preconditioners.
File Description
utils/​utils.py Adds sparse diagonal extraction.
utils/​preconditioners.py Defines the preconditioner API and implementations.
utils/​minres.py Accepts matrix preconditioners.
utils/​linear_cg.py Accepts matrix preconditioners.
utils/​bicgstab.py Adds the preconditioner keyword and deprecation path.
utils/​__init__.py Exports new utilities.
tests/​test_preconditioners.py Tests preconditioners, solvers, and gradients.
tests/​test_bicgstab.py Tests the updated BiCGSTAB API.
sparse_solve.py Integrates forward and transpose preconditioners.
docs/​source/​api/​utils.rst Documents the preconditioner module.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

- 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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Sparse tensor preconditioners fail with batched right-hand sides in CG and MINRES.

0 open findings

2 resolved since last review
Previously missed (2)

In code that hasn't changed since last review

Medium severity 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.

Medium severity 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.

🧠 Review effort: Balanced

…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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Low severity 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.

🧠 Review effort: Balanced

tvercaut and others added 3 commits October 8, 2026 00:03
…lvers

lsmr has no preconditioner argument yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Zero-width broadcasted multiplication currently fails, and the preconditioner detachment documentation contradicts the implementation.

2 open findings

🧠 Review effort: Balanced


Give feedback about Copilot approvals in this survey to enter a drawing for a $150 gift card.

Comment thread torchsparsegradutils/sparse_matmul.py Resolved
… 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>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

A callable supplied only for the transpose system is incorrectly reused as the forward preconditioner.

0 open findings

2 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity 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.

tvercaut and others added 2 commits October 8, 2026 11:35
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.
@theo-barfoot

Copy link
Copy Markdown
Collaborator

Merged #123's history through f03ecc9 in 83ce507, preserving this PR's broadcasting support. Review follow-ups are split into separate commits:

  • c7d378f: coalesce internally transposed COO matrix preconditioners so trainable transposes satisfy Fix sparse matmul correctness and stabilise statistical tests #123's contract, with gradient regression coverage.
  • 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.


Authored by ChatGPT Codex.

_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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Provide pre-conditioners for iterative methods

3 participants