API reference¶
Generated from the source. See Operators for the classes and Configuration for settings.
Creation¶
Linox API - Public Functional Interface.
This module provides the main functional entry points for the Linox library.
as_linop(a: Any) -> LinearOperator
¶
todense(a: LinearlyOperatorLike) -> jax.Array
¶
eye(N: int, M: int | None = None, k: int = 0, dtype: Any = None) -> LinearOperator
¶
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Args: N: Number of rows in the output. M: Number of columns in the output. If None, defaults to N. k: Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype: Data-type of the returned array.
Source code in linox/api.py
zeros(dim: Int, shape: tuple[Int, Int] | None = None) -> LinearOperator
¶
Create a zero operator.
Args: dim: Dimension or number of rows. shape: Optional shape tuple (rows, cols).
Source code in linox/api.py
ones(dim: Int, shape: tuple[Int, Int] | None = None) -> LinearOperator
¶
diag(v: jax.Array) -> LinearOperator
¶
kron(a: LinearlyOperatorLike, b: LinearlyOperatorLike) -> LinearOperator
¶
block_diag(*opers: LinearlyOperatorLike) -> LinearOperator
¶
bmat(blocks: list[list[LinearlyOperatorLike]]) -> LinearOperator
¶
Construct a block matrix from a list of lists of operators.
toeplitz(c: jax.Array, r: jax.Array | None = None) -> LinearOperator
¶
Construct a Toeplitz operator from column c and optional row r.
If r is None, assumes symmetric Toeplitz (r = c).
Source code in linox/api.py
Solving¶
Linox API - Public Functional Interface.
This module provides the main functional entry points for the Linox library.
solve(a: LinearlyOperatorLike, b: jax.Array, method: str = 'auto', *, throw: bool = True, return_info: bool = False, residual_rtol: float = 1e-05, **kwargs) -> jax.Array | tuple[jax.Array, Solution]
¶
Solve linear system Ax = b.
Args:
a: Linear operator.
b: Right-hand side vector/matrix.
method: Solver method ("exact", "lsmr", "cg", "auto"). "cg" uses
linox's own preconditioned conjugate gradients, which requires a
symmetric positive-definite operator and accepts a
preconditioner= operator.
throw: Raise :class:~linox.linalg.solution.LinearSolveError when the
solve fails (the default). Pass False to accept whatever the
solver produced. Under jax.jit the outcome is a tracer and
cannot be raised at trace time, so the failure is reported by a
runtime callback instead -- branch on info.result if you need
to handle it inside the computation.
return_info: Also return a :class:~linox.linalg.solution.Solution
carrying the outcome code and solver diagnostics.
residual_rtol: Relative residual above which a square solve is judged
to have failed. A singular direct solve typically returns finite,
enormous values rather than NaN, so the residual is the only
reliable detector.
Returns:
| Type | Description |
|---|---|
``x``, or ``(x, info)`` when ``return_info=True``.
|
|
Raises:
| Type | Description |
|---|---|
LinearSolveError
|
If the solve failed and |
Source code in linox/api.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 | |
psolve(a: LinearOperator, b: jax.Array, rtol=1e-08) -> jax.Array
¶
Solve Ax = b using pseudo-inverse. See lpsolve for implementation details.
inverse(a: LinearlyOperatorLike, method: str = 'auto', **kwargs) -> LinearOperator
¶
Compute the inverse of a linear operator.
Args: a: Linear operator. method: "exact" (lazy inverse) or "auto".
Source code in linox/api.py
pinverse(a: LinearlyOperatorLike, method: str = 'auto', **kwargs) -> LinearOperator
¶
Compute the pseudo-inverse of a linear operator.
lu_factor(a: LinearOperator, overwrite_a: bool = False) -> tuple[jax.Array, jax.Array]
¶
LU factorization of a linear operator.
Source code in linox/operators/arithmetic.py
lu_solve(a: LinearOperator, b: jax.Array) -> jax.Array
¶
Solve the linear system Ax = b given the LU factorization of A.
Source code in linox/operators/arithmetic.py
Outcome reporting for linear solves.
Before this module, :func:linox.solve returned a bare array with no way to
tell whether it meant anything. A singular system produced finite, plausible,
wildly wrong numbers -- no exception, no warning, no NaN -- which then
propagated silently into whatever the caller did next.
The types here follow the shape of lineax's Solution/RESULTS:
solves report an outcome code, and by default a failed solve raises rather
than handing back garbage.
LinearSolveError
¶
Bases: RuntimeError
Raised when a linear solve fails and throw=True (the default).
Source code in linox/linalg/solution.py
RESULTS
¶
Bases: IntEnum
Outcome of a linear solve.
Source code in linox/linalg/solution.py
message: str
property
¶
Human-readable explanation of this outcome.
Solution
dataclass
¶
The outcome of a linear solve.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
Array
|
The solution array. Meaningful only when |
result |
RESULTS | Array
|
The outcome code. May be a traced array under |
stats |
dict[str, Any]
|
Solver-specific diagnostics, e.g. |
Source code in linox/linalg/solution.py
successful: bool | jax.Array
property
¶
Whether the solve succeeded.
check_result(result: RESULTS | jax.Array, *, throw: bool, detail: str = '') -> None
¶
Raise (eager) or emit a runtime error message (traced) on failure.
Under jax.jit the outcome is a tracer, so there is nothing to raise at
trace time. In that case a runtime callback reports the failure when it
actually occurs, and the caller can still branch on Solution.result
inside the computation.
Source code in linox/linalg/solution.py
residual_result(operator: Any, solution: jax.Array, rhs: jax.Array, *, rtol: float = 1e-05) -> tuple[RESULTS | jax.Array, jax.Array]
¶
Classify a solve by its relative residual ||Ax - b|| / ||b||.
This is the only reliable detector for a direct solve against a singular operator: the output is typically finite and enormous rather than NaN, so a finiteness check alone misses it. Costs one extra matvec, which is cheap next to the factorisation it is validating.
Source code in linox/linalg/solution.py
Decompositions¶
Linox API - Public Functional Interface.
This module provides the main functional entry points for the Linox library.
eigh(a: LinearlyOperatorLike, k: Int | None = None, subset_by_index: tuple[Int, Int] | None = None, method: str = 'auto', **kwargs) -> tuple[jax.Array, LinearOperator] | jax.Array
¶
Compute eigenvalues and eigenvectors.
Args: a: Linear operator. k: Number of eigenvalues (for approx/partial). subset_by_index: Range of indices (start, end) for eigenvalues. method: "exact" or "lanczos".
Source code in linox/api.py
svd(a: LinearlyOperatorLike, **kwargs) -> tuple[jax.Array, jax.Array, jax.Array]
¶
qr(a: LinearOperator) -> tuple[jax.Array, jax.Array]
¶
QR decomposition of a linear operator. See lqr for implementation details.
cholesky(a: LinearOperator) -> jax.Array
¶
Cholesky decomposition of a linear operator. See lcholesky for implementation details.
sqrt(a: LinearlyOperatorLike, method: str = 'auto', **kwargs) -> LinearOperator
¶
Matrix square root factor.
Returns an operator S satisfying S @ S.T == a. Note this is a
factor, not necessarily the symmetric principal square root: the exact
path returns whatever structured factorisation is available for the
operator (a Cholesky factor for a dense :class:Matrix, the elementwise
root for a :class:Diagonal, and so on). Request method="lanczos"
to get the principal square root a**(1/2) via a Krylov method.
Args:
a: Linear operator.
method: One of "auto", "exact", "approx", "lanczos".
Source code in linox/api.py
Traces and determinants¶
Linox API - Public Functional Interface.
This module provides the main functional entry points for the Linox library.
trace(a: LinearlyOperatorLike, method: str = 'auto', **kwargs) -> jax.Array
¶
Compute the trace of a linear operator.
Args: a: Linear operator. method: Computation method ("auto", "exact", "hutchinson").
Source code in linox/api.py
det(a: LinearlyOperatorLike) -> jax.Array
¶
slogdet(a: LinearlyOperatorLike, method: str = 'auto', **kwargs) -> tuple[jax.Array, jax.Array]
¶
Compute sign and log of determinant.
Args: a: Linear operator. method: Computation method ("auto", "exact", "slq").
Source code in linox/api.py
logdet(a: LinearlyOperatorLike) -> jax.Array
¶
diagonal(a: LinearOperator) -> jax.Array
¶
Extract the diagonal of an operator as a :class:jax.Array.
Source code in linox/operators/arithmetic.py
Matrix functions¶
Properties¶
Linox API - Public Functional Interface.
This module provides the main functional entry points for the Linox library.
is_square(a: LinearOperator) -> bool
¶
is_symmetric(a: LinearOperator, *, rtol: float = 1e-05, atol: float = 1e-08, key: jax.Array | None = None, num_probes: int = 1) -> bool
¶
Check if a linear operator is symmetric without densifying.
Uses randomized probing: generates random vectors x and checks if Ax ≈ A^T x. This avoids densifying the full matrix.
Args: a: Linear operator to check rtol: Relative tolerance for comparison atol: Absolute tolerance for comparison key: Random key for generating test vectors (default: uses key 0) num_probes: Number of random vectors to test (default: 1)
Returns:
| Type | Description |
|---|---|
True if the operator appears symmetric within tolerance
|
|
Source code in linox/operators/arithmetic.py
is_hermitian(a: LinearOperator, *, rtol: float = 1e-05, atol: float = 1e-08, key: jax.Array | None = None, num_probes: int = 1) -> bool
¶
Check if a linear operator is Hermitian without densifying.
Uses randomized probing: generates random vectors x and checks if Ax ≈ (A^H x) where A^H is the conjugate transpose. This avoids densifying the full matrix.
For real matrices, this is equivalent to checking symmetry.
Args: a: Linear operator to check rtol: Relative tolerance for comparison atol: Absolute tolerance for comparison key: Random key for generating test vectors (default: uses key 0) num_probes: Number of random vectors to test (default: 1)
Returns:
| Type | Description |
|---|---|
True if the operator appears Hermitian within tolerance
|
|
Source code in linox/operators/arithmetic.py
symmetrize(a: LinearOperator) -> ArithmeticType
¶
congruence_transform(A: ArithmeticType, B: ArithmeticType) -> LinearOperator
¶
Return the congruence transform A @ B @ A.T.
allclose(a: LinearOperatorLike, b: LinearOperatorLike, rtol: float = 1e-05, atol: float = 1e-08) -> bool
¶
Check if two linear operators are close to each other.
Args: a: First linear operator. b: Second linear operator. rtol: Relative tolerance. atol: Absolute tolerance.
Returns:
| Type | Description |
|---|---|
Whether the two linear operators are close to each other.
|
|
Source code in linox/utils/array.py
validate(op: LinearOperator, *, mode: Literal['default', 'debug'] = 'default', rtol: float = 1e-05, atol: float = 1e-08, num_probes: int = 5, key: jax.Array | None = None) -> bool
¶
Validate a LinearOperator and its children recursively.
Performs structural validation by default. In debug mode, also performs numerical probe-based validation to check symmetry and PSD promises.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
LinearOperator
|
The operator to validate. |
required |
mode
|
('default', 'debug')
|
Validation mode. "default" performs only cheap structural checks. "debug" also performs expensive numerical probes. |
"default"
|
rtol
|
float
|
Relative tolerance for numerical checks. Default is 1e-5. |
1e-05
|
atol
|
float
|
Absolute tolerance for numerical checks. Default is 1e-8. |
1e-08
|
num_probes
|
int
|
Number of random probes for numerical validation. Default is 5. |
5
|
key
|
Array
|
JAX random key for probe generation. If None, uses a default key. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if validation passes. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails, with details about the failure and hints. |
See Also
linox.config : For setting LINOX_DEBUG=1 to enable debug validation globally.
Examples:
>>> import linox as lo
>>> A = lo.Matrix(jnp.eye(3))
>>> lo.validate(A) # Cheap structural validation
True
Source code in linox/utils/validation.py
Matrix-free algorithms¶
Preconditioned conjugate gradients for symmetric positive-definite systems.
jax.scipy.sparse.linalg.cg reports no convergence information, which left
:func:linox.solve unable to say whether a CG solve had actually succeeded --
it had to fall back to a loose residual guard. This implementation reports a
termination code in the same style as :mod:linox.linalg.approx.lsmr, and
accepts a preconditioner.
Only matrix-vector products are used, so a matrix-free operator stays matrix-free.
cg_solve(A: LinearOperatorLike, b: jax.Array, *, preconditioner: LinearOperatorLike | None = None, rtol: float = 1e-06, atol: float = 0.0, maxiter: int | None = None, x0: jax.Array | None = None, track_iterations: bool = False) -> tuple[jax.Array, dict]
¶
Solve A x = b for symmetric positive-definite A.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
LinearOperatorLike
|
Symmetric positive-definite operator. Only |
required |
b
|
Array
|
Right-hand side, shape |
required |
preconditioner
|
LinearOperatorLike | None
|
Operator approximating |
None
|
rtol
|
float
|
Convergence is declared when
|
1e-06
|
atol
|
float
|
Convergence is declared when
|
1e-06
|
maxiter
|
int | None
|
Iteration cap. Defaults to |
None
|
x0
|
Array | None
|
Initial guess. Defaults to zeros. |
None
|
track_iterations
|
bool
|
Report the exact iteration count as |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
x |
Array
|
The solution. |
info |
dict
|
|
Notes on differentiability
The iteration is a lax.while_loop, which has no reverse-mode rule, and
its counter is only observable from inside it. Those two facts pull in
opposite directions, so both modes exist and each costs one CG run:
track_iterations=False(default) routes the solution through :func:jax.lax.custom_linear_solve, which supplies the adjointwhile_looplacks -- for symmetricAthe cotangent is itself a solve againstA, which is howjax.scipy.sparse.linalg.cgmanages it too.jax.gradworks; the loop runs inside the callable, soitnis not observable.track_iterations=Trueruns the loop directly, soinfo["itn"]is exact. Reverse-mode differentiation then raises,while_loophaving no VJP; forward mode andjax.jitare unaffected.
Notes
The iteration guards p^T A p <= 0, which cannot happen for a positive
definite A and therefore signals that the operator is not positive
definite -- or is too ill-conditioned to behave as though it is. The guard
halts the recurrence rather than dividing and returning NaN; the caller
sees non-convergence and a large residual.
Source code in linox/linalg/approx/cg.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
Lanczos tridiagonalization and the Krylov methods built on it.
lanczos_eigh(A: LinearOperatorLike, v0: ArrayLike, num_iters: int, k: int | None = None, which: str = 'LM', reortho: bool = True) -> tuple[jax.Array, jax.Array]
¶
Compute a few eigenvalues/eigenvectors using Lanczos method.
Source code in linox/linalg/approx/lanczos.py
lanczos_matrix_function(A: LinearOperatorLike, v: ArrayLike, func: callable, num_iters: int, reortho: bool = True) -> jax.Array
¶
Approximate f(A)v using Lanczos tridiagonalization.
Source code in linox/linalg/approx/lanczos.py
lanczos_solve_sqrt(A: LinearOperatorLike, b: ArrayLike, tol=1e-05, min_eta=1e-14, max_iter=10, overwrite_b=False) -> jax.Array
¶
Build a low-rank inverse factor for a PSD operator using CG/Lanczos.
Returns a skinny matrix D whose columns are A-conjugate directions (normalized by sqrt of the Rayleigh quotient), such that D @ D.T ≈ A^{-1} on the generated Krylov subspace. This acts like an "inverse sqrt" factor usable in Kronecker products, preconditioners, or low-rank approximations. Note this is not the symmetric A^{-1/2}; it is a factor whose Gram approximates A^{-1}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
array-like or linear operator supporting `A @ x`
|
Positive semi-definite operator. |
required |
b
|
array
|
Start vector for the Krylov process (will be normalized). |
required |
tol
|
float
|
Relative tolerance for residual norm stopping. |
1e-05
|
min_eta
|
float
|
Minimum step Rayleigh quotient to continue (guard against breakdown). |
1e-14
|
max_iter
|
int
|
Maximum number of Lanczos/CG iterations (columns in the factor). |
10
|
overwrite_b
|
bool
|
If True, may reuse the buffer of |
False
|
Source code in linox/linalg/approx/lanczos.py
lanczos_tridiag(A: LinearOperatorLike, v0: ArrayLike, num_iters: int, reortho: bool = True) -> tuple[jax.Array, jax.Array, jax.Array]
¶
Lanczos tridiagonalization for symmetric operators.
Computes a tridiagonal reduction of a symmetric linear operator using the Lanczos algorithm. Returns the orthonormal Lanczos vectors Q and the tridiagonal matrix T such that A ≈ Q T Q^T on the Krylov subspace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
LinearOperatorLike
|
Symmetric linear operator or matrix. |
required |
v0
|
ArrayLike
|
Initial vector for the Krylov process. |
required |
num_iters
|
int
|
Number of Lanczos iterations. |
required |
reortho
|
bool
|
Whether to perform full reorthogonalization. Default is True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
Q |
(Array, shape(n, num_iters))
|
Orthonormal Lanczos vectors. |
alpha |
(Array, shape(num_iters))
|
Diagonal elements. |
beta |
(Array, shape(num_iters - 1))
|
Off-diagonal elements. |
Source code in linox/linalg/approx/lanczos.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
Arnoldi and general Krylov methods.
This module implements Arnoldi iteration for general matrices. For symmetric matrices, use lanczos.py.
arnoldi_iteration(A: LinearOperatorLike, v0: ArrayLike, num_iters: int) -> tuple[jax.Array, jax.Array]
¶
Arnoldi iteration for general (non-symmetric) operators.
Computes a Hessenberg reduction of a general linear operator using the Arnoldi iteration. Returns the orthonormal Arnoldi vectors Q and the upper Hessenberg matrix H such that A ≈ Q H Q^T on the Krylov subspace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
LinearOperatorLike
|
General linear operator or matrix. |
required |
v0
|
ArrayLike
|
Initial vector for the Krylov process. |
required |
num_iters
|
int
|
Number of Arnoldi iterations. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Q |
(Array, shape(n, num_iters))
|
Orthonormal Arnoldi vectors. |
H |
(Array, shape(num_iters + 1, num_iters))
|
Upper Hessenberg matrix. |
Source code in linox/linalg/approx/arnoldi.py
arnoldi_matrix_function(A: LinearOperatorLike, v: ArrayLike, func: callable, num_iters: int) -> jax.Array
¶
Approximate f(A)v using Arnoldi iteration.
Source code in linox/linalg/approx/arnoldi.py
Hutchinson's stochastic trace estimator.
Approximate trace and diagonal using stochastic probes (Hutchinson's method). Optimized for batched execution via matrix-matrix multiplication (A @ Z).
hutchinson_diagonal(A: LinearOperatorLike, key: jax.Array, num_samples: int = 100, distribution: str = 'rademacher') -> tuple[jax.Array, jax.Array]
¶
Estimate diagonal of a linear operator using Hutchinson's method.
Computes: diag(A) ≈ (1/M) * sum(v_i ⊙ (A v_i))
Args: A: LinearOperator or array (n, n) key: PRNG key num_samples: Number of probes distribution: 'rademacher' (default) or 'normal'
Returns:
| Type | Description |
|---|---|
(estimate, std_error) each of shape (n,)
|
|
Source code in linox/linalg/approx/hutchinson.py
hutchinson_trace(A: LinearOperatorLike, key: jax.Array, num_samples: int = 100, distribution: str = 'rademacher') -> tuple[jax.Array, jax.Array]
¶
Estimate trace of a linear operator using Hutchinson's method.
Computes Monte Carlo estimate: trace(A) ≈ (1/M) * sum(v_i^T A v_i) Uses batched execution (A @ Z) for efficiency.
Args: A: LinearOperator or array (n, n) key: PRNG key num_samples: Number of random probes distribution: 'rademacher' (default) or 'normal'
Returns:
| Type | Description |
|---|---|
(estimate, std_error)
|
|
Source code in linox/linalg/approx/hutchinson.py
hutchinson_trace_and_diagonal(A: LinearOperatorLike, key: jax.Array, num_samples: int = 100, distribution: str = 'rademacher') -> dict[str, tuple[jax.Array, jax.Array]]
¶
Jointly estimate trace and diagonal using shared probes.
Source code in linox/linalg/approx/hutchinson.py
Stochastic Lanczos Quadrature (SLQ).
Approximates trace(f(A)) using stochastic probes and Lanczos tridiagonalization.
slq(A: LinearOperatorLike, func_scalar: callable, key: jax.Array, num_samples: int = 10, m: int = 20, distribution: str = 'rademacher') -> tuple[jax.Array, jax.Array]
¶
Estimate trace(f(A)) using SLQ.
trace(f(A)) ≈ (1/M) * sum_i v_i^T f(A) v_i v_i^T f(A) v_i ≈ ||v_i||^2 * e_1^T f(T_m) e_1
Source code in linox/linalg/approx/slq.py
slq_logdet(A: LinearOperatorLike, key: jax.Array, num_samples: int = 10, m: int = 20) -> tuple[jax.Array, jax.Array]
¶
Estimate log-determinant using SLQ.
logdet(A) = trace(log(A))
Source code in linox/linalg/approx/slq.py
LSMR iterative solver for least-squares problems.
This module implements the LSMR (Least Squares Minimal Residual) algorithm for solving large-scale least-squares and linear systems in a matrix-free manner.
The implementation closely follows the matfree library (https://github.com/pnkraemer/matfree) by Nicholas Krämer et al., which itself follows the original LSMR algorithm by Fong and Saunders.
Key features: - Matrix-free: Only requires matrix-vector products - Handles over-determined, under-determined, and rank-deficient systems - JAX-compatible with automatic differentiation support - Iterative with configurable stopping criteria
References
.. [1] D. C.-L. Fong and M. A. Saunders, "LSMR: An iterative algorithm for sparse least-squares problems," SIAM Journal on Scientific Computing, vol. 33, no. 5, pp. 2950-2971, 2011.
.. [2] matfree: Matrix-free linear algebra in JAX https://github.com/pnkraemer/matfree
.. [3] A. Roy, N. Krämer, V. De Bortoli, and A. Doucet, "Gradients of Stochastic Trace Estimators via Differentiable Matrix-Free Linear Solvers," arXiv preprint, 2025.
lsmr_solve(A: LinearOperatorLike, b: ArrayLike, atol: float = 1e-06, btol: float = 1e-06, ctol: float = 1e-08, maxiter: int | None = None, damp: float = 0.0, x0: ArrayLike | None = None) -> tuple[jax.Array, dict]
¶
Solve least-squares problem min ||Ax - b||_2 using LSMR algorithm.
LSMR is an iterative method for solving: - Linear systems Ax = b (when A is square and full rank) - Least-squares min ||Ax - b||_2 (when A is over-determined) - Minimum-norm solutions (when A is under-determined or rank-deficient)
The algorithm only requires matrix-vector products with A and A^T, making it suitable for large sparse or structured matrices.
This implementation follows matfree's approach, which matches SciPy's LSMR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
LinearOperatorLike
|
Linear operator or matrix of shape (m, n). Should support both
|
required |
b
|
ArrayLike
|
Right-hand side vector of shape (m,). |
required |
atol
|
float
|
Absolute tolerance for convergence. Default is 1e-6. |
1e-06
|
btol
|
float
|
Relative tolerance for convergence. Default is 1e-6. |
1e-06
|
ctol
|
float
|
Condition number tolerance. Default is 1e-8. |
1e-08
|
maxiter
|
int
|
Maximum number of iterations. If None, uses min(m, n). Default is None. |
None
|
damp
|
float
|
Damping parameter for regularization. Solves the problem min ||[A; damp*I] x - [b; 0]||_2 instead. Default is 0.0 (no damping). |
0.0
|
x0
|
ArrayLike
|
Initial guess for the solution. If None, starts with zero vector. Default is None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
x |
(Array, shape(n))
|
Solution vector. |
info |
dict
|
Dictionary containing: - 'istop': Stopping condition (0-9) - 'itn': Number of iterations performed - 'normr': Final residual norm ||r|| - 'normar': Final ||A^T r|| - 'normA': Estimate of ||A|| - 'condA': Estimate of cond(A) - 'normx': Norm of solution ||x|| |
Examples:
>>> import jax.numpy as jnp
>>> from linox import Matrix
>>> A = Matrix(jnp.eye(50))
>>> b = jnp.ones(50)
>>> x, info = lsmr_solve(A, b)
>>> assert jnp.allclose(x, b)
Notes
This implementation closely follows matfree's LSMR, which is based on Fong and Saunders (2011) and matches SciPy's implementation.
References
.. [1] D. C.-L. Fong and M. A. Saunders, "LSMR: An iterative algorithm for sparse least-squares problems," SIAM J. Sci. Compute., 2011. .. [2] https://github.com/pnkraemer/matfree
Source code in linox/linalg/approx/lsmr.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 | |
Matrix-free SVD via Lanczos bidiagonalization.
This module implements matrix-free singular value decomposition (SVD) using Lanczos bidiagonalization for large-scale problems where only a few singular values and vectors are needed.
The implementation is inspired by the matfree library (https://github.com/pnkraemer/matfree) by Nicholas Krämer et al.
Key algorithms: - Lanczos bidiagonalization: Reduces matrix to bidiagonal form - Partial SVD: Computes k largest singular values/vectors
References
.. [1] N. Krämer, M. Schober, and P. Hennig, "Gradients of functions of large matrices," arXiv preprint arXiv:2405.17277, 2024. https://arxiv.org/abs/2405.17277
.. [2] matfree: Matrix-free linear algebra in JAX https://github.com/pnkraemer/matfree
.. [3] G. H. Golub and C. F. Van Loan, "Matrix Computations," 4th ed., Johns Hopkins, 2013.
svd_partial(A: LinearOperatorLike, k: int, num_iters: int | None = None, u0: ArrayLike | None = None, reortho: bool = True) -> tuple[jax.Array, jax.Array, jax.Array]
¶
Compute partial SVD using Lanczos bidiagonalization.
Computes the k largest singular values and corresponding singular vectors of a large matrix without forming the full matrix explicitly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
LinearOperatorLike
|
Linear operator or matrix of shape (m, n). |
required |
k
|
int
|
Number of singular values/vectors to compute. |
required |
num_iters
|
int
|
Number of Lanczos iterations. Should be larger than k for good approximation. If None, uses min(2*k, min(m, n)). Default is None. |
None
|
u0
|
ArrayLike
|
Initial vector of shape (m,) for bidiagonalization. If None, uses vector of ones. Default is None. |
None
|
reortho
|
bool
|
Whether to use full reorthogonalization in bidiagonalization. This significantly improves numerical stability. Default is True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
U |
(Array, shape(m, k))
|
Left singular vectors (columns). |
S |
(Array, shape(k))
|
Singular values in descending order. |
Vt |
(Array, shape(k, n))
|
Right singular vectors (rows). |
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> from linox import Matrix
>>> # Large matrix
>>> key = jax.random.PRNGKey(0)
>>> A_dense = jax.random.normal(key, (1000, 500))
>>> A = Matrix(A_dense)
>>> # Compute top 10 singular values/vectors
>>> U, S, Vt = svd_partial(A, k=10)
>>> print(f"Top 10 singular values: {S}")
>>> # Verify: A ≈ U @ diag(S) @ Vt
>>> A_approx = U @ jnp.diag(S) @ Vt
>>> error = jnp.linalg.norm(A_dense - A_approx)
Notes
This is a matrix-free alternative to jnp.linalg.svd for computing a few singular values/vectors of large sparse or structured matrices.
The algorithm: 1. Performs Lanczos bidiagonalization: A ≈ U_bi B V_bi^T 2. Computes SVD of small bidiagonal matrix B 3. Projects back to get singular vectors of A
References
Inspired by matfree library [1, 2].
Source code in linox/linalg/spectral.py
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
lanczos_bidiag(A: LinearOperatorLike, u0: ArrayLike, num_iters: int, reortho: bool = True) -> tuple[jax.Array, jax.Array, jax.Array, jax.Array]
¶
Lanczos bidiagonalization for SVD computation.
Reduces a matrix A to bidiagonal form: A ≈ U B V^T, where U and V are orthonormal and B is bidiagonal.
This is the foundation for computing partial SVD of large matrices where only a few singular values/vectors are needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
A
|
LinearOperatorLike
|
Linear operator or matrix of shape (m, n). Should support both
|
required |
u0
|
ArrayLike
|
Initial vector of shape (m,) for the bidiagonalization process. Will be normalized internally. |
required |
num_iters
|
int
|
Number of bidiagonalization iterations (size of bidiagonal matrix). Should be much smaller than min(m, n). |
required |
reortho
|
bool
|
Whether to use full reorthogonalization. This significantly improves numerical stability at the cost of O(num_iters^2) operations. Default is True (recommended). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
U |
(Array, shape(m, num_iters))
|
Left orthonormal basis vectors (columns). |
V |
(Array, shape(n, num_iters))
|
Right orthonormal basis vectors (columns). |
alpha |
(Array, shape(num_iters))
|
Diagonal elements of bidiagonal matrix B. |
beta |
(Array, shape(num_iters - 1))
|
Super-diagonal elements of bidiagonal matrix B. |
Notes
The bidiagonal matrix B has the form: B = [[alpha[0], beta[0], 0, ...], [0, alpha[1], beta[1], ...], [0, 0, alpha[2], ...], [...]]
This is related to Golub-Kahan bidiagonalization and is used in algorithms like LSMR and partial SVD computation.
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> from linox import Matrix
>>> key = jax.random.PRNGKey(0)
>>> A = Matrix(jax.random.normal(key, (100, 50)))
>>> u0 = jnp.ones(100)
>>> U, V, alpha, beta = lanczos_bidiag(A, u0, num_iters=10)
>>> # U and V contain orthonormal vectors
>>> # B = diag(alpha) + diag(beta, 1) is bidiagonal
References
Inspired by matfree.decomp.bidiag [1, 2] and the Golub-Kahan process [3].
Source code in linox/linalg/spectral.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |