EP-0251: Sparse Linear Algebra Kernel, Decomposition Correctness & Hot-Path Performance¶
| Field | Value |
|---|---|
| EP | 0251 |
| Title | Sparse Linear Algebra Kernel, Decomposition Correctness & Hot-Path Performance |
| Author | Eran Rivlis eran@rivlis.info, Antigravity |
| Sponsor | Core Maintainers |
| Delegate | ⚡ Shannon (Efficiency) & 🛡️ Golem (Safety) |
| Status | Final |
| Type | Standards Track |
| Created | 2026-11-26 |
| Updated | 2026-11-28 |
| Replaces | — |
| Superseded-By | — |
Abstract¶
This proposal fixes critical correctness and algorithmic-complexity bugs in algebrax.matrix, algebrax.converters, algebrax.topology, and algebrax.analysis, promotes a single Field[V]-polymorphic sparse elimination kernel (sparse_rref, rank, nullspace) with RectSparseMatrix[R, C, V] and Fraction typing support, and cleanly removes the redundant matrix.core.inverse implementation in favor of \(O(N^3)\) matrix.inv. It fixes broken LU key alignment across lu_decompose and _solve_*, universal key=str integer-key corruption (\(n \ge 11\)), accidental \(O(N^4)\) inv(), \(O(N^2)\) mat_vec set allocation, exponential SimplicialComplex rebuilds, float boundary signs breaking exact finite-field homology, and sparse zero-omission bugs in graph calculus.
Motivation¶
The Second Grand Council Audit exposed critical silent-wrong-result and asymptotic blowup bugs across the numerical and sparse linear algebra backbone:
- Silent Decomposition & Key-Ordering Failures (
matrix/decompose.py,converters.py): _lu_decompose_floatand_extract_field_lulabelL's columns withcols[:min_dim]andU's rows withrows[:min_dim], breakingP @ A == L @ Uwheneverrows != cols(and_solve_float/_solve_fieldindexLcolumns viacols[j]).det()andsolve()extractrowsandcolsindependently viaget_matrix_keys, causing sparse singular square-cardinality matrices with omitted zero rows/columns such as{0: {1: 1.0}, 1: {2: 1.0}}to returndet == 1.0instead of0.0.converters.get_matrix_keys,solve_triangular,cholesky,cg_solve,analysis/calculus.py,display.py, and__main__.pysort keys withkey=str, placing'10'before'2'for integer indices \(n \ge 11\) and silently corrupting solutions (\(Lx \ne b\)).choleskyalso iteratesmatrix.keys()(rows only, ignoring column-only keys) and never validates symmetry.inv()claims \(O(N^3)\) via precomputed LU, yet callssolve(matrix, e_r)inside the column loop—recomputinglu_decompose\(N\) times (\(O(N^4)\)). Meanwhilematrixco-exports two conflicting inverses (matrix.core.inversevs.matrix.decompose.inv), andgrid_to_sparse/prune_sparsefail to prune complex floating-point noise (1e-17j).- Fragmented Elimination Kernels & Missing Rectangular Typing:
- Three separate elimination routines exist: dense-grid LU in
matrix/decompose.py, float-only_matrix_rankintopology/_core.py(ignoring callertolinCellularSheafand locking homology out of \(\mathbb{Q}\)/\(\mathbb{F}_p\) torsion), and sparseField[V]pivot elimination buried privately invariety/affine.py. SimplicialComplexstores boundary signs asfloat(1.0/-1.0), which crashesModularField.inv(pow()requiresint) and downgrades exactFractionhomology tofloat.typing.pylacksFractioninNandRectSparseMatrix[R, C, V]for rectangular boundary/incidence maps.- Hot-Path Asymptotic Blowups:
matrix.core.mat_vecdelegates per row toinner(), which re-normalizessr, re-binds methods, and allocatesset(row.keys()) & set(vector.keys())on every row—turning sparse matrix-vector multiply into \(O(\text{rows}(M) \cdot \text{nnz}(v))\) (\(O(N^2)\)) insidecg_solve,fiedler_vector,laplacian_smoothing, andsheaf_diffusion.SimplicialComplex.add_simplexrebuilds all boundary matrices at every recursive sub-face insertion (up to \(2^{k+1}-1\) rebuilds per \(k\)-simplex) and accepts degenerate repeated-vertex simplices like(0, 0), breaking \(\partial^2 = 0\).topology/persistence.pyscans all \(\binom{N}{2}\) pairs in_extract_vr_edges(defeating sparsity) and uses unguarded recursive Hopcroft–Karp DFS (RecursionErrorrisk for \(\ge 1000\) features).- Graph Calculus & Spectral Correctness Bugs (
analysis/): gradientandlaplacianskip omitted sparse zero keys, returning{}on unit impulse{0: 1.0}and contradictingmat_vec(laplacian_matrix(graph), field).fiedler_vectorperforms an \(O(N \cdot E)\) list scan (neighbor in nodes) withqueue.pop(0), directed-only BFS, and unsymmetrized degree computation (calculus.py:740).is_ramanujan_graphstrips all eigenvalues with \(|\lambda| = d\), falsely certifying disconnected \(d\)-regular graphs (e.g., \(K_4 \sqcup K_4\)) as Ramanujan expanders.
Rationale¶
- ⚡ Claude Shannon (Efficiency): Eliminating \(O(N^4)\)
inv(), \(O(N^2)\)mat_vec, \(O(2^k)\) simplex rebuilds, and \(O(N^2)\) VR scans restores true sparse output-sensitive complexity without adding a single external dependency. - 🛡️ The Golem (Safety & Containment): Explicit iterative Hopcroft–Karp DFS eliminates
RecursionErrorcliffs; partial pivoting for float/complex sparse elimination prevents catastrophic cancellation; natural key ordering, Cholesky symmetry checks, and degenerate-simplex rejection prevent silent data corruption. - ⚖️ Emmy Noether (Symmetry): One shared
Field[V]-polymorphic elimination kernel (sparse_rref,rank,nullspace), one canonicalinv(cleanly removingmatrix.core.inverse), and operand-order-preservinginner()respect non-commutative semirings and exact finite fields alike.
Specification¶
1. Core Typing Extensions & Canonical Key Ordering (typing.py, converters.py, matrix/decompose.py)¶
src/algebrax/typing.py:- Add
FractiontoN = TypeVar('N', int, float, complex, Decimal, Fraction). - Add
RectSparseMatrix = Mapping[R, Mapping[C, V]]for rectangular boundary, incidence, and restriction maps (preserving 2-parameterSparseMatrix[K, V]for square matrices). src/algebrax/converters.py:- Add public
canonical_sort_keys(keys: Iterable[K]) -> list[K]that sorts homogeneous comparable keys (int,tuple[int, ...],str) natively viasorted(keys)and falls back tokey=stronly onTypeErrorfor mixed-type keys. - Update
get_matrix_keys,matrix/decompose.py(cholesky,solve_triangular),matrix/core.py(cg_solve),analysis/calculus.py,display.py, and__main__.pyto usecanonical_sort_keys. - Fix
grid_to_sparseandprune_sparseto prune complex floating-point noise (abs(val) <= tolforisinstance(val, (int, float, complex))). src/algebrax/matrix/decompose.py&core.py:- In
_lu_decompose_floatand_extract_field_lu, bind bothL's column keys andU's row keys to a shared inner pivot domain (rows[:min_dim]) soP @ A == L @ Uholds identically for rectangular and disjoint-label matrices. Update_solve_floatand_solve_fieldto indexLcolumns byrows[j]. - For square-operator APIs (
det,solve,inv): checklen(rows) != len(cols)first (raisingValueError("Matrix must be square"), preserving rectangular rejection), then checkset(rows) != set(cols)for disjoint-domain square-cardinality endomorphisms with omitted zero rows/columns, returningdet = 0/ raisingSingularMatrixErrorimmediately. - In
cholesky: collect the full key domaincanonical_sort_keys(set(rows) | set(cols))(notmatrix.keys()alone) and validate symmetry (abs(A[i][j] - A[j][i]) <= tol) over all present entries. - In
inv: computelu_decompose(matrix, field=field, tol=tol)once outside the column loop and reuse the factoredP, L, Uvia forward/backward substitution (\(O(N^3)\) total). - Clean Cut: Remove redundant
matrix.core.inversecompletely (matrix.invinmatrix/decompose.pyis the single canonical inverse); updaterep/group.py,rep/lie.py,matrix/__init__.py, docs, and tests to callinv.
2. Shared Sparse Field[V] Elimination Kernel (src/algebrax/matrix/eliminate.py)¶
Promote and generalize variety/affine.py:_sparse_jacobian_pivot_rows into a first-class sparse elimination module exported from algebrax.matrix:
def sparse_rref(
matrix: RectSparseMatrix[R, C, V],
*,
field: Field[V] | None = None,
tol: float = 1e-12,
) -> tuple[RectSparseMatrix[int, C, V], list[C]]:
"""Compute exact sparse Reduced Row Echelon Form and pivot column list over any Field[V]."""
def rank(
matrix: RectSparseMatrix[R, C, V],
*,
field: Field[V] | None = None,
tol: float = 1e-12,
) -> int:
"""Compute exact matrix rank via forward-only sparse Field-polymorphic Gaussian elimination."""
def nullspace(
matrix: RectSparseMatrix[R, C, V],
*,
cols: Iterable[C] | None = None,
field: Field[V] | None = None,
tol: float = 1e-12,
) -> list[SparseVector[C, V]]:
"""Compute an exact basis of ker(A) via sparse RREF over any Field[V] (honoring omitted zero columns via cols)."""
- Key Pre-Mapping & Two Pivot Regimes:
- Map row and column keys via
canonical_sort_keysto dense integer indices0..m-1,0..n-1once up front (safe on mixed-type keys, fast integer hashing in inner loops). - Exact regime (
field is not Noneand not float/complex): sparse pivot selection usingfield.is_zeroandfield.inv. - Floating-point regime (
field is Noneor float/complexStandardField): sparse partial pivoting (selecting maximumabs(val) > tolin the active pivot column) for numerical stability matchingrep/lie.pyandrep/invariant.py. rank(...)executes forward elimination only (skipping RREF back-substitution fill-in).- Replace
variety/affine.py:_sparse_jacobian_pivot_rows,topology/_core.py:_matrix_rank,rep/invariant.py:_rref_row_basis, andrep/lie.py:_rref_nullspacewith calls toalgebrax.matrix.eliminate. - Thread
tol(and optionalfield: Field[V] | None) throughCellularSheaf.global_sections_dimension,first_cohomology_dimension, andSimplicialComplex.betti_numbers. ConvertSimplicialComplexboundary signs to exact(field.one, field.neg(field.one))whenfieldis supplied (and store integer1/-1signs onSimplicialComplexboundary matrices) soModularField(p)andFractionhomology work with zerofloatcoercion.
3. Core Hot-Path & Topology Performance Fixes¶
src/algebrax/matrix/core.py:- Rewrite
inner(v1, v2, semiring)to iterate directly over the smaller mapping while preserving(v1[k], v2[k])operand order (critical for non-commutative semirings likeStringSemiring,CliffordAlgebra,PathAlgebra) with \(O(\min(\text{nnz}(v_1), \text{nnz}(v_2)))\) lookups and zero set allocations. - Inline the inner-product loop directly inside
mat_vecwith a dedicatedif semiring is None:native Python fast path (avoiding per-rowSemiring.normalizeand method re-binding). - Avoid the extra trailing
dot(base, base, sr)inpower(matrix, n)whenexp == 0. - Use
collections.dequein_find_matrix_components. src/algebrax/topology/homology.py&persistence.py:- Reject degenerate simplices with repeated vertices (
len(set(simplex)) != len(simplex)) withValueErrorin bothSimplicialComplex.add_simplexandFilteredSimplicialComplex.add_simplex. - Split
_insert_simplex_no_rebuild(s_tuple)fromadd_simplex, makeSimplicialComplex.boundary_matricesa lazy@propertybacked by a_dirty: boolflag (preserving direct attribute reads with \(O(1)\) amortizedadd_simplexand rebuilding once on first read), and store exact integer1/-1incidence signs. - Rewrite
_extract_vr_edgesintopology/persistence.pyto iterate only over present entries indistance_matrix(\(O(\text{nnz})\)), canonicalizing(min(u, v), max(u, v)), skippingu == v, and takingmax(d_uv, d_vu)before filtering<= max_edge_length. - Replace recursive Hopcroft–Karp
dfs(u)in_has_perfect_bipartite_matchingwith an explicit iterative DFS stack.
4. Graph Calculus & Spectral Correctness (src/algebrax/analysis/)¶
src/algebrax/analysis/calculus.py:- Fix
gradient(with zero-pruning) andlaplacian(matchinglaplacian_matrixsymmetrization/self-loop parity) to respect sparse zero omission over all edges incident to the support offield, guaranteeinglaplacian(f, G) == mat_vec(laplacian_matrix(G), f). - In
fiedler_vector, replacequeue.pop(0)+neighbor in nodeswithcollections.deque, asetof nodes, an undirected adjacency map built once, and symmetrizeddegrees(fixing line740fornormalized=Trueon upper-triangular graphs). src/algebrax/analysis/spectral.py:- Fix
is_ramanujan_graphto remove at most one trivial \(+d\) eigenvalue (and at most one \(-d\) eigenvalue if bipartite), so disconnected \(d\)-regular graphs with repeated \(\lambda = d\) returnis_ramanujan = False.
Acceptance Criteria¶
P @ A == L @ Uholds for rectangular and disjoint-key matrices;solve(A, b)passes for disjoint-key systems;det({0: {1: 1.0}, 1: {2: 1.0}}) == 0.0; rectangular{0: {0: 1.0, 1: 2.0}}still raisesValueError("square")indet/solve/inv.solve_triangularandcholeskyproduce exact solutions for \(n \ge 12\) integer-indexed matrices;choleskyrejects asymmetric matrices and column-only keys withValueError.inv()invokeslu_decomposeexactly once (verified via spy/monkeypatch count== 1);matrix.core.inverseis cleanly removed and all complex-matrix callers (rep/group.py,rep/lie.py) pass usinginv().sparse_rref,rank, andnullspacematch exact reference solutions overStandardField(float),StandardField(complex),StandardField(Fraction), andModularField(p)on rectangular matrices with omitted zero columns;SimplicialComplex.betti_numbers(field=ModularField(2))detects \(\mathbb{RP}^2\) \(\mathbb{Z}/2\mathbb{Z}\) torsion (\(\beta_1(\mathbb{RP}^2; \mathbb{F}_2) = 1\) vs. \(\beta_1(\mathbb{RP}^2; \mathbb{Q}) = 0\)).inner(v1, v2, sr)preserves non-commutative order onStringSemiringandCliffordAlgebrawhenlen(v1) != len(v2).- Inserting a 5-simplex into
SimplicialComplextriggers_rebuild_boundary_matrices()at most once upon readingboundary_matrices; degenerate(0, 0)raisesValueErrorin bothSimplicialComplexandFilteredSimplicialComplex. - Iterative Hopcroft–Karp handles bipartite matchings of size \(N \ge 1500\) without
RecursionError. laplacian({0: 1.0}, G) == mat_vec(laplacian_matrix(G), {0: 1.0})on unweighted, weighted, and upper-triangular graphs;is_ramanujan_graphreturnsFalseon disconnected \(K_4 \sqcup K_4\).- New public exports (
canonical_sort_keys,sparse_rref,rank,nullspace,RectSparseMatrix) comply withEP-0002(AMDS) and passtests/algebrax/test_docstrings.py.
Backwards Compatibility¶
- Additive:
matrix.rank,matrix.nullspace,matrix.sparse_rref,converters.canonical_sort_keys,typing.RectSparseMatrix,Fractionintyping.N, and optionalfieldparameter on topological Betti/cohomology rank helpers. - Intentional clean cuts & behavior fixes:
matrix.core.inverseis cleanly removed; usematrix.inv(single canonical \(O(N^3)\) inverse).choleskyraisesValueErroron asymmetric matrices.SimplicialComplex.add_simplexandFilteredSimplicialComplex.add_simplexraiseValueErroron degenerate repeated-vertex simplices.gradient/laplacianinclude boundary edges between nonzero and omitted-zero vertices.is_ramanujan_graphreturnsFalsefor disconnected \(d\)-regular graphs.
How to Teach This / Documentation Plan¶
- Ensure
algebrax.matrix.eliminateandconverters.canonical_sort_keysconform toEP-0002(AMDS) andtests/algebrax/test_docstrings.py. - Update
docs/guide/matrix/core.md(replacinginverseGauss-Jordan notes withinv),docs/guide/matrix/decompositions.md, anddocs/guide/algebra/exact_matrix_solvers.mdforrank,nullspace,sparse_rref, and exact \(\mathbb{Q}\)/\(\mathbb{F}_p\) homology. - Update
docs/guide/topology/homology.md,docs/guide/topology/sheaf.md,docs/guide/matrix/benchmarks.md, anddocs/guide/analysis/discrete_calculus.md.
Reference Implementation¶
Target files verified in the Second Grand Council Audit & Review:
- src/algebrax/typing.py, src/algebrax/converters.py
- src/algebrax/matrix/{core.py,decompose.py,eliminate.py,__init__.py}
- src/algebrax/topology/{_core.py,homology.py,persistence.py,sheaf.py}
- src/algebrax/analysis/{calculus.py,spectral.py}
- src/algebrax/variety/affine.py, src/algebrax/rep/{group.py,lie.py,invariant.py}
Rejected Ideas¶
- Keeping
matrix.core.inverseas a Deprecated Wrapper Aroundmatrix.inv: - Rejected: Co-exporting two identical matrix inverses violates Shannon's minimalism and Feynman's Freshman Test. Cleanly unifying on
matrix.invleaves one canonical entry point. - Always Converting Keys to
intInternally indecompose.py: - Rejected: Breaks AlgebraX's key-polymorphic design (
str, simplex tuples,StalkCoord).canonical_sort_keyspreserves arbitrary hashable keys while fixing numeric order for \(n \ge 11\). - Swapping
(v1, v2)Directly ininner(): - Rejected: Breaks non-commutative semirings (
StringSemiring,CliffordAlgebra,PathAlgebra). Iterate over the smaller mapping while always evaluatingsr.mul(v1[k], v2[k]). - Using Unpivoted Exact Elimination for Float/Complex Matrices in
eliminate.py: - Rejected: Causes catastrophic cancellation on ill-conditioned real/complex inputs; two pivot regimes (exact sparse vs. float/complex sparse partial pivoting) keep both regimes exact and stable.
Open Questions¶
None. Both matrix.core.inverse removal and lazy _dirty SimplicialComplex.boundary_matrices are decided.
Change Log¶
- 2026-11-26:
- Initial Draft authored from the Second Grand Council Codebase Audit (Shannon, Golem, Popper, Explorer, Feynman).
- 2026-11-27:
- Incorporated Grand Council Pre-Implementation Review revisions: centralized
canonical_sort_keysinconverters.py, movedRectSparseMatrix/typing.N(Fraction) fromEP-0252, added_solve_float/_solve_fieldL-index fix and rectangularValueError-first guard, added two-regime pivoting +colsparam + forward-onlyrankineliminate.py, fixedSimplicialComplexinteger signs + lazy_dirty@property+FilteredSimplicialComplexparity, fixed non-commutativeinner()order andmat_vecfast path, fixedfiedler_vectorsymmetrized degrees and complex pruning, cleanly removedmatrix.core.inverse, added Acceptance Criteria and AMDS/guide checklist, and promoted status toAccepted. - 2026-11-28:
- Implemented full specification across
typing.py,converters.py,matrix/{core,decompose,eliminate}.py,topology/{_core,homology,persistence,sheaf}.py,analysis/{calculus,spectral}.py,variety/affine.py, andrep/{group,lie,invariant}.py; addedtests/algebrax/test_linalg_kernel_and_hotpaths.py, updated user guides, verified all 1,040 tests + Ruff + Pyrefly, and promoted status toFinal.