tensormesh.sparse¶
Sparse matrix data type and solver entry points. Built on top of
torch-sla; see 稀疏求解器 for the design and
backend matrix.
SparseMatrix¶
- class SparseMatrix(edata: Tensor, row: Tensor, col: Tensor, shape: Tuple[int, int])[源代码]¶
基类:
_FEMSparsityMixin,SparseTensorCOO sparse matrix with FEM-flavoured helpers.
Subclass of
torch_sla.SparseTensor. Inherits@(spmm),solve, autograd-aware values,.to_dense()and friends from the parent; adds the layout signature, block-COO assembly, scipy interoperability and type-preserving arithmetic.- 参数:
- layout_signature¶
(row.data_ptr(), row._version, col.data_ptr(), col._version, nnz, shape): identifies the row and column index tensors, not the sparsity pattern (no hashing, no device synchronisation). Matrices on the same index tensors have equal signatures, such as repeated assemblies of oneElementAssemblerorMixedElementAssembler, which reuse their index tensors; other assemblers, such asFacetBilinearAssembler, build fresh index tensors at every call. The signature holds no strides and says nothing about whether the tensors are still alive: two live views that start at the same address with other strides have equal signatures, and so can index tensors allocated at the addresses of freed ones, with as many entries. Caches of quantities that depend only on the pattern (the masks ofCondenser) compare it. Seetensormesh.sparse.mixin.- Type:
- layout_hash¶
Deprecated alias of
layout_signature(with a warning).
示例
import torch from tensormesh.sparse import SparseMatrix edata = torch.tensor([1.0, 2.0, 3.0]) row = torch.tensor([0, 1, 2]) col = torch.tensor([1, 2, 0]) A = SparseMatrix(edata, row, col, shape=(3, 3)) # Inherited from SparseTensor: y = A @ torch.tensor([1.0, 2.0, 3.0]) x = A.double().solve(torch.ones(3, dtype=torch.float64)) # FEM-specific block-COO assembly: 10 element matrices of size 3x3. block_data = torch.randn(10, 3, 3) elem_row = torch.arange(10) elem_col = torch.arange(10) K = SparseMatrix.from_block_coo(block_data, elem_row, elem_col, (10, 10))
- property grad: SparseMatrix | None¶
Gradient w.r.t.
values, wrapped as aSparseMatrix.Returns
Nonewhen no gradient has accumulated onvalues.
- to(*args, **kwargs) SparseMatrix[源代码]¶
Move tensor to device and/or convert dtype.
- 参数:
- 返回:
New SparseTensor on the target device/dtype.
- 返回类型:
示例
>>> A = SparseTensor(val, row, col, shape) >>> A_cuda = A.to('cuda') >>> A_float32 = A.to(dtype=torch.float32) >>> A_cuda_float32 = A.to('cuda', torch.float32)
- cuda(device=None) SparseMatrix[源代码]¶
Move tensor to CUDA device.
- 参数:
device (int, optional) -- CUDA device index. Default: current device.
- 返回:
Tensor on CUDA.
- 返回类型:
- cpu() SparseMatrix[源代码]¶
Move tensor to CPU.
- 返回:
Tensor on CPU.
- 返回类型:
- float() SparseMatrix[源代码]¶
Convert to float32.
- double() SparseMatrix[源代码]¶
Convert to float64.
- half() SparseMatrix[源代码]¶
Convert to float16.
- detach() SparseMatrix[源代码]¶
- has_same_layout(other) bool[源代码]¶
Check whether
othershares this matrix's sparsity pattern.Accepts another
SparseMatrix, an opaquelayout_signaturetuple, or — for legacy callers — the previously-deprecatedlayout_hashvalue (which now returns the same tuple). Inherits the mixin implementation.
- transpose() SparseMatrix[源代码]¶
Return
A^Tas aSparseMatrixsharing this matrix's values.
- property T: SparseMatrix¶
Shorthand for
transpose().
- to_scipy_coo() coo_matrix[源代码]¶
Detach and convert to a
scipy.sparse.coo_matrixon CPU.
- to_sparse_coo() Tensor[源代码]¶
Convert to a
torch.sparse_coo_tensor()(autograd-tracked).
- static from_scipy_coo(matrix: coo_matrix, device: str = 'cpu', dtype: dtype = torch.float) SparseMatrix[源代码]¶
Wrap a
scipy.sparse.coo_matrixas aSparseMatrix.- 参数:
matrix (coo_matrix) -- Source matrix.
device (str, default
"cpu") -- Target torch device.dtype (torch.dtype, default
torch.float) -- Target value dtype.
- 返回类型:
- static from_sparse_coo(matrix: Tensor) SparseMatrix[源代码]¶
Wrap a coalesced
torch.sparse_coo_tensor()as aSparseMatrix.- 参数:
matrix (Tensor) -- Sparse COO tensor; will be coalesced in place.
- 返回类型:
- static from_dense(tensor: Tensor) SparseMatrix[源代码]¶
Pull non-zero entries out of a dense 2D tensor into COO.
- 参数:
tensor (Tensor) -- 2D tensor; entries exactly equal to zero are dropped.
- 返回类型:
- static from_block_coo(edata: Tensor, row: Tensor, col: Tensor, shape: Tuple[int, int]) SparseMatrix[源代码]¶
Expand block-COO storage into a flat
SparseMatrix.Each block is a small dense matrix attached to a
(row, col)pair in a coarser graph. This is the layout produced by FEM element assembly when the element data is vector-valued (e.g. linear elasticity), with one[dim, dim]block per(node_i, node_j)pair.Blocks are assumed square; the function uses
edata.shape[1]as the block size and ignoresshape[2].- 参数:
edata (Tensor) -- Block data of shape
[n_elements, block_size, block_size].row (Tensor) -- Block indices of shape
[n_elements]; entries refer to the coarse graph.col (Tensor) -- Block indices of shape
[n_elements]; entries refer to the coarse graph.shape (Tuple[int, int]) --
(block_rows, block_cols)of the coarse graph.
- 返回:
Flat COO matrix of shape
(shape[0] * block_size, shape[1] * block_size).- 返回类型:
- static expand_block_indices(row: Tensor, col: Tensor, block_size: int) Tuple[Tensor, Tensor][源代码]¶
Expand coarse block
(row, col)indices into flat COO indices.Entry order matches
edata.flatten()for block data of shape[n_blocks, block_size, block_size](block-major, row-major within each block), so the result pairs with a flattened block tensor to build the same matrix asfrom_block_coo().Callers that assemble repeatedly on a fixed sparsity pattern should call this once and cache the result: passing the same index tensors to every
SparseMatrixkeepslayout_signaturestable across assemblies (it is sequence-identity, seetensormesh.sparse.mixin), so layout-keyed consumers likeCondenserhit their caches.
- static random(m: int, n: int, density: float = 0.1, device: str = 'cpu', dtype: dtype = torch.float) SparseMatrix[源代码]¶
Random
m x nsparse matrix with the requested density.- 参数:
m (int) -- Dense shape.
n (int) -- Dense shape.
density (float, default 0.1) -- Fraction of entries that are non-zero. Drawn via
scipy.sparse.random().device (str, default
"cpu")dtype (torch.dtype, default
torch.float)
- 返回类型:
- static random_layout(m: int, n: int, density: float = 0.1, device: str = 'cpu') Tuple[Tensor, Tensor, Tuple[int, int]][源代码]¶
Random
(row, col, shape)triple with no value tensor attached.Useful when several matrices need to share the same sparsity pattern; combine with
random_from_layout().
- static random_from_layout(layout: Tuple[Tensor, Tensor, Tuple[int, int]], device: str = 'cpu', dtype: dtype = torch.float) SparseMatrix[源代码]¶
Attach random uniform
[0, 1)values to an existing layout.- 参数:
layout (Tuple[Tensor, Tensor, Tuple[int, int]]) --
(row, col, shape)triple, e.g. fromrandom_layout().device (str, default
"cpu")dtype (torch.dtype, default
torch.float)
- 返回类型:
- static eye(n: int, value: float = 1., device: str = 'cpu', dtype: dtype = torch.float) SparseMatrix[源代码]¶
n x nsparse identity, optionally scaled byvalue.- 参数:
- 返回类型:
- static full(m: int, n: int, value: float = 1., device: str = 'cpu', dtype: dtype = torch.float) SparseMatrix[源代码]¶
Constant
m x nmatrix stored densely-as-sparse.Mostly a building block for
combine_matrix()block layouts;value == 0is short-circuited to an empty COO tensor.- 参数:
- 返回类型:
- static combine_vector(matrices: List[SparseMatrix], axis: int = 0) SparseMatrix[源代码]¶
Stack a list of sparse matrices along
axis.Equivalent of
torch.cat()forSparseMatrix. Densetorch.Tensorentries are auto-converted viafrom_dense().- 参数:
matrices (List[SparseMatrix or Tensor]) -- Items must agree on
shape[1 - axis].axis (int, default 0) --
0stacks vertically (along rows),1horizontally.
- 返回类型:
- static combine_matrix(matrices: List[List[SparseMatrix]]) SparseMatrix[源代码]¶
Assemble a 2D block layout of sparse matrices into one matrix.
Each entry of
matrices[i][j]may be:None— treated as a zero block of inferred size;intorfloat— expanded viafull()to a constant block of the inferred size;torch.Tensor— auto-converted viafrom_dense();SparseMatrix— used as-is.
Block sizes are inferred from the first non-scalar entry in each row / column; a row or column with only
None/scalar entries will have inferred size zero.- 参数:
matrices (List[List[SparseMatrix or Tensor or int or float or None]]) -- Rectangular nested list,
[n_rows][n_cols].- 返回:
Assembled matrix of shape
(sum(row_sizes), sum(col_sizes)).- 返回类型:
- static combine(matrices) SparseMatrix[源代码]¶
Dispatch to
combine_matrix()orcombine_vector().If the first element is a list or tuple, the input is treated as a 2D block layout (calls
combine_matrix()); otherwise it is a 1D stack along axis 0 (callscombine_vector()).
- class SparseTensor[源代码]¶
COO sparse tensor with autograd support — the base class that
SparseMatrixextends. Re-exported fromtorch-sla; see the torch-sla docs for the full API.
Solvers¶
- spmm(edata, row, col, shape, B, backend=None)[源代码]¶
Compute
A @ Bfor sparseAand dense matrix (or vector)B.When
Bis 1D this transparently delegates tospmv.- 参数:
edata (Tensor) -- 1D tensor of shape
[nnz]: non-zero values ofA.row (Tensor) -- 1D int tensor of shape
[nnz]: row indices ofA.col (Tensor) -- 1D int tensor of shape
[nnz]: column indices ofA.B (Tensor) -- Dense operand of shape
[N, K](matrix) or[N](vector).backend (str or None, default None) -- See
spmvfor the backend / device matrix.
- 返回:
[M, K]or[M]matching the rank ofB.- 返回类型:
Legacy entry points (deprecated)¶
自 0.x 版本弃用: The two functions below pre-date the torch-sla integration and
are scheduled for removal. The canonical solver path is the
methods on SparseMatrix itself (inherited
from torch_sla.SparseTensor):
Linear solves →
SparseMatrix.solve(i.e.torch_sla.SparseTensor.solve) — see 稀疏求解器.Nonlinear solves →
SparseMatrix.nonlinear_solve(Newton / Picard / Anderson with line search and autograd Jacobian).
Both will be retired once the remaining in-tree call sites have migrated. New code should not use them.
- spsolve(edata, row, col, shape, b, backend='auto', method='cg', preconditioner='jacobi', tol=1e-5, max_iter=10000, x0=None, is_spd=True, verbose=False)[源代码]¶
Solve the sparse linear system
A x = b(legacy entry point).自 0.x 版本弃用: This free function pre-dates the
torch-slaintegration and is scheduled for removal. The canonical path is to wrap the data in aSparseMatrixand call itssolvemethod (inherited fromtorch_sla.SparseTensor), which auto-detects symmetry / positive-definiteness and routes totorch_sla.spsolvedirectly. See 稀疏求解器.Low-level entry point: takes raw COO arrays instead of a
SparseMatrixobject. Withtorch-slainstalled, dispatches to a differentiable sparse-linear-algebra backend; without it, falls back to a curated mini-stack of SciPy / SuperLU / CuPy / PETSc wrappers.- 参数:
edata (Tensor) -- 1D tensor of shape
[nnz]: non-zero values ofA.row (Tensor) -- 1D int tensor of shape
[nnz]: row indices ofA.col (Tensor) -- 1D int tensor of shape
[nnz]: column indices ofA.b (Tensor) -- Right-hand side. Shape
[n]for a single RHS, or[n, n_batch]for batched RHS (auto-routed through SuperLU).backend (str, default
"auto") -- Torch-sla path:"auto"(CPU →"scipy", CUDA →"pytorch"),"scipy","pytorch","eigen","cudss","cupy". Fallback path (no torch-sla):"auto","petsc","cupy"— others are accepted but the method/preconditioner hints below are ignored.method (str, default
"cg") -- Iterative algorithm —"cg","bicgstab","minres","gmres","lgmres"— or one of the direct factorizations"lu","umfpack","cholesky","ldlt". See the installedtorch_sla.spsolvesignature for the canonical list. Honoured only on the torch-sla path. On the fallback path, each wrapper uses a fixed algorithm.preconditioner (str, default
"jacobi") --"jacobi","ilu", or"none". Same caveat asmethod— torch-sla path only.tol (float, default
1e-5) -- Convergence tolerance (iterative methods).max_iter (int, default
10000) -- Iteration budget (iterative methods).x0 (Tensor, optional) -- Initial guess. Currently consumed only by some fallback wrappers and ignored by torch-sla.
is_spd (bool, default
True) -- Hint to the torch-sla path thatAis symmetric positive definite. Picks CG as the defaultmethod; setFalsefor indefinite / non-symmetricAand combine withmethod="bicgstab"or"gmres".verbose (bool, default
False) -- Print which backend/method was picked.
- 返回:
Solution
x, same shape and dtype asb.- 返回类型:
备注
Both paths are autograd-aware: gradients of
xflow back intoedataandbvia an adjoint sparse solve. On the torch-sla path this is built in to the library; on the fallback path each wrapper supplies its owntorch.autograd.Functionbackward.示例
>>> from tensormesh.sparse import spsolve >>> x = spsolve(edata, row, col, (n, n), b) # auto >>> x = spsolve(edata, row, col, (n, n), b, method="lu") # direct >>> x = spsolve(edata, row, col, (n, n), b, backend="cudss") # GPU direct >>> x = spsolve(edata, row, col, (n, n), b, ... is_spd=False, method="bicgstab") # non-SPD
- nonlinear_solve(f: Callable[[...], Tensor], j: Callable[[...], SparseMatrix], u0: Tensor, params: Tuple[Tensor, ...], max_iter: int = 100, tol: float = 1e-6, verbose: bool = False) Tensor[源代码]¶
Solve
F(u, params) = 0foru(legacy in-tree implementation).自 0.x 版本弃用: This in-tree Newton-Raphson driver is scheduled for removal.
torch-slaships a richertorch_sla.SparseTensor.nonlinear_solve(also accessible asSparseMatrix.nonlinear_solve) with Newton / Picard / Anderson modes, Armijo line search, and an autograd-based Jacobian — so the user no longer has to supplyj. Migrate toA.nonlinear_solve(residual, u0, *params); see 稀疏求解器.Drives Newton-Raphson on the forward pass and the implicit-function theorem on the backward pass: gradients w.r.t.
paramscost roughly one extra linear solve regardless of how many Newton iterations were taken.- 参数:
f (Callable) --
F(u, *params) -> torch.Tensor. Must support autograd inparamsfor gradients to flow.j (Callable) --
J(u, *params) -> SparseMatrix: the JacobiandF/du.u0 (Tensor) -- Initial guess.
params (Tuple[Tensor, ...]) -- Optimizable parameters forwarded to
f/j.max_iter (int, default 100) -- Newton iteration budget.
tol (float, default 1e-6) -- Convergence tolerance on
||F(u)||.verbose (bool, default False) -- Print residual norm each Newton step.
- 返回:
Converged
u; gradients route back intoparamsvia the adjoint solve insideNonLinearSolveFunction.- 返回类型:
Backend availability flags¶
Module-level booleans, set at import time, indicating which optional
backends were detected. torch-sla itself is a hard dependency — its
absence raises at import time rather than flipping a flag — so it is not
listed here.
- is_petsc_available¶
bool(x) -> bool
Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
- is_cupy_available¶
bool(x) -> bool
Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.