trnsolver 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trnsolver/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """
2
+ trnsolver — Linear solvers and eigendecomposition for AWS Trainium via NKI.
3
+
4
+ Eigenvalue problems, factorizations, and iterative solvers for scientific
5
+ computing on Trainium. Complements trnblas (BLAS) and trnfft (FFT).
6
+ Part of the trnsci scientific computing suite.
7
+ """
8
+
9
+ __version__ = "0.3.0"
10
+
11
+ # Eigenvalue decomposition
12
+ from .eigen import eigh, eigh_generalized
13
+
14
+ # Factorizations
15
+ from .factor import cholesky, lu, qr, solve, solve_spd, inv_spd, inv_sqrt_spd, inv_sqrt_spd_ns
16
+
17
+ # Iterative solvers
18
+ from .iterative import cg, gmres, jacobi_preconditioner
19
+
20
+ # Backend control
21
+ from .nki import HAS_NKI, set_backend, get_backend
22
+
23
+ __all__ = [
24
+ # Eigen
25
+ "eigh", "eigh_generalized",
26
+ # Factorization
27
+ "cholesky", "lu", "qr", "solve", "solve_spd", "inv_spd", "inv_sqrt_spd",
28
+ "inv_sqrt_spd_ns",
29
+ # Iterative
30
+ "cg", "gmres", "jacobi_preconditioner",
31
+ # Backend
32
+ "HAS_NKI", "set_backend", "get_backend",
33
+ ]
trnsolver/eigen.py ADDED
@@ -0,0 +1,170 @@
1
+ """
2
+ Eigenvalue decomposition for Trainium.
3
+
4
+ Symmetric eigenvalue problem: A @ V = V @ diag(eigenvalues)
5
+
6
+ Methods:
7
+ - Jacobi iteration (NKI-accelerable: rotation = 2×2 matmul per sweep)
8
+ - torch.linalg.eigh fallback for non-NKI backends
9
+
10
+ The Jacobi method is the natural fit for Trainium because each rotation
11
+ is a small matmul that maps to the Tensor Engine, and the sweep over
12
+ off-diagonal elements maps to the Vector Engine for max-finding.
13
+
14
+ Primary use case: SCF eigenvalue problem FC = SCε in quantum chemistry.
15
+ The generalized eigenproblem is first reduced to standard form via
16
+ Cholesky: S = L L^T, then solve (L^{-1} F L^{-T}) C' = C' ε.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ import torch
23
+ from typing import Optional, Tuple
24
+
25
+ from .nki import _use_nki
26
+
27
+
28
+ def eigh(
29
+ A: torch.Tensor,
30
+ max_sweeps: int = 100,
31
+ tol: float = 1e-10,
32
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
33
+ """Symmetric eigenvalue decomposition: A = V @ diag(w) @ V^T
34
+
35
+ Args:
36
+ A: Symmetric matrix (n, n)
37
+ max_sweeps: Maximum Jacobi sweeps
38
+ tol: Convergence threshold (sum of squared off-diagonal elements)
39
+
40
+ Returns:
41
+ eigenvalues: (n,) sorted ascending
42
+ eigenvectors: (n, n) columns are eigenvectors
43
+ """
44
+ if _use_nki():
45
+ return _jacobi_eigh(A, max_sweeps, tol)
46
+ return _torch_eigh(A)
47
+
48
+
49
+ def eigh_generalized(
50
+ A: torch.Tensor,
51
+ B: torch.Tensor,
52
+ max_sweeps: int = 100,
53
+ tol: float = 1e-10,
54
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
55
+ """Generalized symmetric eigenvalue problem: A @ x = λ B @ x
56
+
57
+ Reduces to standard form via Cholesky of B:
58
+ B = L @ L^T
59
+ (L^{-1} A L^{-T}) y = λ y
60
+ x = L^{-T} y
61
+
62
+ This is the SCF path: solve FC = SCε where F is the Fock matrix
63
+ and S is the overlap matrix.
64
+ """
65
+ L = torch.linalg.cholesky(B)
66
+ # L^{-1} A L^{-T}
67
+ L_inv_A = torch.linalg.solve_triangular(L, A, upper=False)
68
+ A_prime = torch.linalg.solve_triangular(L, L_inv_A.T, upper=False).T
69
+
70
+ # Symmetrize (numerical stability)
71
+ A_prime = 0.5 * (A_prime + A_prime.T)
72
+
73
+ eigenvalues, V_prime = eigh(A_prime, max_sweeps, tol)
74
+
75
+ # Back-transform: V = L^{-T} @ V_prime
76
+ eigenvectors = torch.linalg.solve_triangular(L.T, V_prime, upper=True)
77
+
78
+ return eigenvalues, eigenvectors
79
+
80
+
81
+ def _torch_eigh(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
82
+ """Fallback to torch.linalg.eigh."""
83
+ return torch.linalg.eigh(A)
84
+
85
+
86
+ def _jacobi_eigh(
87
+ A: torch.Tensor,
88
+ max_sweeps: int = 100,
89
+ tol: float = 1e-10,
90
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
91
+ """Classical Jacobi eigenvalue algorithm.
92
+
93
+ Each sweep applies n(n-1)/2 Givens rotations to zero off-diagonal elements.
94
+ Each rotation is a 2×2 orthogonal transform — maps to Tensor Engine on NKI.
95
+
96
+ Convergence: quadratic for well-separated eigenvalues.
97
+ """
98
+ n = A.shape[0]
99
+ assert A.shape == (n, n), f"Expected square matrix, got {A.shape}"
100
+
101
+ # Work on a copy
102
+ D = A.clone()
103
+ V = torch.eye(n, dtype=A.dtype, device=A.device)
104
+
105
+ for sweep in range(max_sweeps):
106
+ # Check convergence: sum of squared off-diagonal elements
107
+ off_diag = D.clone()
108
+ off_diag.fill_diagonal_(0.0)
109
+ off_norm = (off_diag ** 2).sum().item()
110
+ if off_norm < tol:
111
+ break
112
+
113
+ # Sweep over all off-diagonal pairs
114
+ for p in range(n):
115
+ for q in range(p + 1, n):
116
+ if abs(D[p, q].item()) < tol * 0.01:
117
+ continue
118
+
119
+ # Compute rotation angle
120
+ if abs(D[p, p].item() - D[q, q].item()) < 1e-15:
121
+ theta = math.pi / 4.0
122
+ else:
123
+ tau = (D[q, q].item() - D[p, p].item()) / (2.0 * D[p, q].item())
124
+ if tau >= 0:
125
+ t = 1.0 / (tau + math.sqrt(1.0 + tau * tau))
126
+ else:
127
+ t = -1.0 / (-tau + math.sqrt(1.0 + tau * tau))
128
+ c = 1.0 / math.sqrt(1.0 + t * t)
129
+ s = t * c
130
+ theta = math.atan2(s, c)
131
+
132
+ c = math.cos(theta)
133
+ s = math.sin(theta)
134
+
135
+ # Apply rotation to D: D' = G^T @ D @ G
136
+ # Only rows/cols p and q change
137
+ for r in range(n):
138
+ if r == p or r == q:
139
+ continue
140
+ d_rp = D[r, p].item()
141
+ d_rq = D[r, q].item()
142
+ D[r, p] = c * d_rp - s * d_rq
143
+ D[p, r] = D[r, p]
144
+ D[r, q] = s * d_rp + c * d_rq
145
+ D[q, r] = D[r, q]
146
+
147
+ d_pp = D[p, p].item()
148
+ d_qq = D[q, q].item()
149
+ d_pq = D[p, q].item()
150
+ D[p, p] = c * c * d_pp - 2 * s * c * d_pq + s * s * d_qq
151
+ D[q, q] = s * s * d_pp + 2 * s * c * d_pq + c * c * d_qq
152
+ D[p, q] = 0.0
153
+ D[q, p] = 0.0
154
+
155
+ # Accumulate eigenvectors: V' = V @ G
156
+ for r in range(n):
157
+ v_rp = V[r, p].item()
158
+ v_rq = V[r, q].item()
159
+ V[r, p] = c * v_rp - s * v_rq
160
+ V[r, q] = s * v_rp + c * v_rq
161
+
162
+ # Extract eigenvalues from diagonal
163
+ eigenvalues = torch.diag(D)
164
+
165
+ # Sort ascending
166
+ idx = torch.argsort(eigenvalues)
167
+ eigenvalues = eigenvalues[idx]
168
+ V = V[:, idx]
169
+
170
+ return eigenvalues, V
trnsolver/factor.py ADDED
@@ -0,0 +1,157 @@
1
+ """
2
+ Matrix factorizations for Trainium.
3
+
4
+ Cholesky, LU, QR — the building blocks for linear solvers.
5
+
6
+ For DF-MP2:
7
+ - Cholesky of the Coulomb metric J = L L^T
8
+ - Triangular solve L X = B for density fitting coefficients
9
+ - These feed into trnblas.trsm for the actual solve
10
+
11
+ For SCF:
12
+ - Cholesky of overlap matrix S for generalized eigenvalue reduction
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import torch
18
+ from typing import Tuple, Optional
19
+
20
+
21
+ def cholesky(A: torch.Tensor, upper: bool = False) -> torch.Tensor:
22
+ """Cholesky factorization: A = L @ L^T (or A = U^T @ U if upper=True).
23
+
24
+ A must be symmetric positive definite.
25
+ """
26
+ L = torch.linalg.cholesky(A)
27
+ if upper:
28
+ return L.T
29
+ return L
30
+
31
+
32
+ def lu(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
33
+ """LU factorization with partial pivoting: P @ A = L @ U
34
+
35
+ Returns:
36
+ P: Permutation matrix (n, n)
37
+ L: Lower triangular with unit diagonal (n, n)
38
+ U: Upper triangular (n, n)
39
+ """
40
+ LU, pivots = torch.linalg.lu_factor(A)
41
+ P, L, U = torch.lu_unpack(LU, pivots)
42
+ return P, L, U
43
+
44
+
45
+ def qr(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
46
+ """QR factorization: A = Q @ R
47
+
48
+ Returns:
49
+ Q: Orthogonal matrix (m, min(m,n))
50
+ R: Upper triangular (min(m,n), n)
51
+ """
52
+ return torch.linalg.qr(A)
53
+
54
+
55
+ def solve(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
56
+ """Solve A @ X = B for X.
57
+
58
+ Uses LU factorization internally.
59
+ """
60
+ return torch.linalg.solve(A, B)
61
+
62
+
63
+ def solve_spd(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
64
+ """Solve A @ X = B where A is symmetric positive definite.
65
+
66
+ Uses Cholesky factorization (faster than LU for SPD).
67
+ """
68
+ L = cholesky(A)
69
+ squeeze = B.dim() == 1
70
+ if squeeze:
71
+ B = B.unsqueeze(1)
72
+ Y = torch.linalg.solve_triangular(L, B, upper=False)
73
+ X = torch.linalg.solve_triangular(L.T, Y, upper=True)
74
+ if squeeze:
75
+ X = X.squeeze(1)
76
+ return X
77
+
78
+
79
+ def inv_spd(A: torch.Tensor) -> torch.Tensor:
80
+ """Inverse of symmetric positive definite matrix via Cholesky.
81
+
82
+ Used for J^{-1} in density fitting (though J^{-1/2} via solve is preferred).
83
+ """
84
+ n = A.shape[0]
85
+ return solve_spd(A, torch.eye(n, dtype=A.dtype, device=A.device))
86
+
87
+
88
+ def inv_sqrt_spd(A: torch.Tensor) -> torch.Tensor:
89
+ """A^{-1/2} for symmetric positive definite A.
90
+
91
+ Computed via eigendecomposition: A = V diag(λ) V^T → A^{-1/2} = V diag(1/√λ) V^T
92
+
93
+ Used in density fitting for the metric contraction J^{-1/2}.
94
+ """
95
+ eigenvalues, V = torch.linalg.eigh(A)
96
+ # Clamp small eigenvalues for numerical stability
97
+ eigenvalues = torch.clamp(eigenvalues, min=1e-12)
98
+ inv_sqrt_eig = 1.0 / torch.sqrt(eigenvalues)
99
+ return V @ torch.diag(inv_sqrt_eig) @ V.T
100
+
101
+
102
+ def inv_sqrt_spd_ns(
103
+ A: torch.Tensor,
104
+ *,
105
+ max_iters: int = 20,
106
+ tol: float = 1e-7,
107
+ ) -> Tuple[torch.Tensor, int, float]:
108
+ """A^{-1/2} for SPD A via the coupled Newton-Schulz iteration.
109
+
110
+ Iterates:
111
+ Y_{k+1} = Y_k T
112
+ Z_{k+1} = T Z_k
113
+ with T = 0.5 (3I - Z_k Y_k), starting from Y_0 = A / s, Z_0 = I where
114
+ s = ||A||_F is a scaling factor that keeps the spectrum of Y_0 inside
115
+ (0, 1) for convergence. At convergence Y_k → (A/s)^{1/2} and
116
+ Z_k → (A/s)^{-1/2}, so A^{-1/2} = Z_k / sqrt(s). Convergence is tracked
117
+ via ||Y_k Z_k - I||_F (which must go to 0).
118
+
119
+ All operations are GEMMs — the workload shape that maps well to the
120
+ Trainium Tensor Engine via trnblas. Prefer this over :func:`inv_sqrt_spd`
121
+ when the NKI backend is active and A is well-conditioned. Falls back
122
+ to the eigendecomposition path (:func:`inv_sqrt_spd`) is recommended
123
+ for A with eigenvalue spread beyond ~1e6.
124
+
125
+ Args:
126
+ A: Symmetric positive definite matrix (n, n).
127
+ max_iters: Maximum iterations.
128
+ tol: Relative Frobenius-norm tolerance on ||Y - I||.
129
+
130
+ Returns:
131
+ X: Approximation of A^{-1/2}.
132
+ iters: Number of iterations executed.
133
+ residual: Final ||Y - I||_F relative to ||I||_F.
134
+
135
+ Note:
136
+ TODO: power-iteration-based spectral-norm scaling is tighter than
137
+ Frobenius for matrices with one dominant eigenvalue. Frobenius is
138
+ good enough for typical DF-MP2 metric matrices.
139
+ """
140
+ n = A.shape[0]
141
+ s = torch.linalg.norm(A, ord="fro")
142
+ I = torch.eye(n, dtype=A.dtype, device=A.device)
143
+
144
+ Y = A / s
145
+ Z = I.clone()
146
+
147
+ norm_I = torch.linalg.norm(I, ord="fro")
148
+ residual = float("inf")
149
+ for k in range(max_iters):
150
+ T = 0.5 * (3.0 * I - Z @ Y)
151
+ Y = Y @ T
152
+ Z = T @ Z
153
+ residual = (torch.linalg.norm(Y @ Z - I, ord="fro") / norm_I).item()
154
+ if residual < tol:
155
+ return Z / torch.sqrt(s), k + 1, residual
156
+
157
+ return Z / torch.sqrt(s), max_iters, residual
trnsolver/iterative.py ADDED
@@ -0,0 +1,179 @@
1
+ """
2
+ Iterative linear solvers for Trainium.
3
+
4
+ Conjugate Gradient (CG) for SPD systems, GMRES for general systems.
5
+ These are relevant for large-scale SCF with linear-scaling methods
6
+ and for CPSCF (coupled-perturbed SCF) response equations.
7
+
8
+ All inner products and matvecs map to trnblas Level 1/2 ops.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import torch
14
+ from typing import Optional, Callable, Tuple
15
+
16
+
17
+ def jacobi_preconditioner(A: torch.Tensor) -> Callable[[torch.Tensor], torch.Tensor]:
18
+ """Build a Jacobi (diagonal) preconditioner M(r) = r / diag(A).
19
+
20
+ Cheap and effective when A is diagonally dominant. Approximates A^{-1}
21
+ by inverting only the diagonal.
22
+ """
23
+ d = torch.diagonal(A).clone()
24
+ if torch.any(d.abs() < 1e-15):
25
+ raise ValueError("Jacobi preconditioner: diagonal has near-zero entries")
26
+ inv_d = 1.0 / d
27
+ return lambda r: r * inv_d
28
+
29
+
30
+ def cg(
31
+ A: torch.Tensor | Callable,
32
+ b: torch.Tensor,
33
+ x0: Optional[torch.Tensor] = None,
34
+ tol: float = 1e-6,
35
+ maxiter: int = 1000,
36
+ M: Optional[torch.Tensor | Callable] = None,
37
+ ) -> Tuple[torch.Tensor, int, float]:
38
+ """Conjugate Gradient solver for A @ x = b (A must be SPD).
39
+
40
+ Args:
41
+ A: SPD matrix (n, n) or callable matvec A(x) → A@x
42
+ b: Right-hand side (n,)
43
+ x0: Initial guess (default: zeros)
44
+ tol: Convergence tolerance on relative residual
45
+ maxiter: Maximum iterations
46
+ M: Preconditioner as callable M(r) → approx A^{-1} @ r, or tensor
47
+ (interpreted as the already-inverted preconditioner applied as M@r).
48
+ Use `jacobi_preconditioner(A)` for the common diagonal case.
49
+
50
+ Returns:
51
+ x: Solution vector
52
+ iters: Number of iterations
53
+ residual: Final relative residual norm
54
+ """
55
+ n = b.shape[0]
56
+ matvec = A if callable(A) else lambda x: torch.mv(A, x)
57
+ if M is None:
58
+ precond = None
59
+ elif callable(M):
60
+ precond = M
61
+ else:
62
+ precond = lambda r: torch.mv(M, r)
63
+
64
+ x = x0.clone() if x0 is not None else torch.zeros(n, dtype=b.dtype, device=b.device)
65
+ r = b - matvec(x)
66
+ b_norm = torch.linalg.norm(b).item()
67
+ if b_norm < 1e-15:
68
+ return x, 0, 0.0
69
+
70
+ if precond is not None:
71
+ z = precond(r)
72
+ else:
73
+ z = r.clone()
74
+
75
+ p = z.clone()
76
+ rz = torch.dot(r, z).item()
77
+
78
+ for k in range(maxiter):
79
+ Ap = matvec(p)
80
+ pAp = torch.dot(p, Ap).item()
81
+ if abs(pAp) < 1e-30:
82
+ break
83
+
84
+ alpha = rz / pAp
85
+ x = x + alpha * p
86
+ r = r - alpha * Ap
87
+
88
+ r_norm = torch.linalg.norm(r).item()
89
+ if r_norm / b_norm < tol:
90
+ return x, k + 1, r_norm / b_norm
91
+
92
+ if precond is not None:
93
+ z = precond(r)
94
+ else:
95
+ z = r.clone()
96
+
97
+ rz_new = torch.dot(r, z).item()
98
+ beta = rz_new / rz
99
+ p = z + beta * p
100
+ rz = rz_new
101
+
102
+ return x, maxiter, torch.linalg.norm(r).item() / b_norm
103
+
104
+
105
+ def gmres(
106
+ A: torch.Tensor | Callable,
107
+ b: torch.Tensor,
108
+ x0: Optional[torch.Tensor] = None,
109
+ tol: float = 1e-6,
110
+ maxiter: int = 100,
111
+ restart: int = 30,
112
+ ) -> Tuple[torch.Tensor, int, float]:
113
+ """GMRES solver for A @ x = b (general, non-symmetric).
114
+
115
+ Restarted GMRES with Arnoldi process. Each iteration builds an
116
+ orthonormal Krylov basis via modified Gram-Schmidt, then solves
117
+ the least-squares Hessenberg system.
118
+
119
+ Args:
120
+ A: Matrix (n, n) or callable matvec
121
+ b: Right-hand side (n,)
122
+ x0: Initial guess
123
+ tol: Convergence tolerance
124
+ maxiter: Maximum outer iterations (restarts)
125
+ restart: Krylov subspace size before restart
126
+
127
+ Returns:
128
+ x: Solution vector
129
+ total_iters: Total matvec count
130
+ residual: Final relative residual norm
131
+ """
132
+ n = b.shape[0]
133
+ matvec = A if callable(A) else lambda x: torch.mv(A, x)
134
+
135
+ x = x0.clone() if x0 is not None else torch.zeros(n, dtype=b.dtype, device=b.device)
136
+ b_norm = torch.linalg.norm(b).item()
137
+ if b_norm < 1e-15:
138
+ return x, 0, 0.0
139
+
140
+ total_iters = 0
141
+
142
+ for outer in range(maxiter):
143
+ r = b - matvec(x)
144
+ r_norm = torch.linalg.norm(r).item()
145
+ if r_norm / b_norm < tol:
146
+ return x, total_iters, r_norm / b_norm
147
+
148
+ # Arnoldi process
149
+ m = min(restart, n)
150
+ V = torch.zeros(n, m + 1, dtype=b.dtype, device=b.device)
151
+ H = torch.zeros(m + 1, m, dtype=b.dtype, device=b.device)
152
+ V[:, 0] = r / r_norm
153
+ g = torch.zeros(m + 1, dtype=b.dtype, device=b.device)
154
+ g[0] = r_norm
155
+
156
+ for j in range(m):
157
+ total_iters += 1
158
+ w = matvec(V[:, j])
159
+
160
+ # Modified Gram-Schmidt
161
+ for i in range(j + 1):
162
+ H[i, j] = torch.dot(w, V[:, i])
163
+ w = w - H[i, j] * V[:, i]
164
+
165
+ H[j + 1, j] = torch.linalg.norm(w)
166
+ if H[j + 1, j].item() < 1e-14:
167
+ m = j + 1
168
+ break
169
+ V[:, j + 1] = w / H[j + 1, j]
170
+
171
+ # Check convergence via Givens rotations on g
172
+ # (simplified: just check residual norm)
173
+
174
+ # Solve least-squares: min ||H @ y - g||
175
+ y, _ = torch.linalg.lstsq(H[:m + 1, :m], g[:m + 1])[:2]
176
+ x = x + V[:, :m] @ y[:m]
177
+
178
+ r = b - matvec(x)
179
+ return x, total_iters, torch.linalg.norm(r).item() / b_norm
@@ -0,0 +1,5 @@
1
+ """NKI kernel dispatch for Trainium solver acceleration."""
2
+
3
+ from .dispatch import HAS_NKI, set_backend, get_backend, _use_nki
4
+
5
+ __all__ = ["HAS_NKI", "set_backend", "get_backend", "_use_nki"]
@@ -0,0 +1,91 @@
1
+ """
2
+ NKI dispatch for solver operations.
3
+
4
+ The Jacobi eigensolver is the primary NKI acceleration target:
5
+ each Givens rotation is a 2×2 matmul on the Tensor Engine,
6
+ and the off-diagonal max-finding maps to the Vector Engine.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+
13
+ try:
14
+ import neuronxcc.nki as nki
15
+ import neuronxcc.nki.language as nl
16
+ import neuronxcc.nki.isa as nisa
17
+ HAS_NKI = True
18
+ except ImportError:
19
+ HAS_NKI = False
20
+
21
+ # When set, kernel-path failures re-raise instead of falling back to PyTorch.
22
+ # Used by the validation suite to catch silent kernel breakage during iteration.
23
+ _REQUIRE_NKI = os.environ.get("TRNSOLVER_REQUIRE_NKI", "").lower() in ("1", "true", "yes")
24
+
25
+ _backend = "auto"
26
+
27
+
28
+ def set_backend(backend: str):
29
+ global _backend
30
+ assert backend in ("auto", "pytorch", "nki")
31
+ if backend == "nki" and not HAS_NKI:
32
+ raise RuntimeError("NKI backend requires neuronxcc")
33
+ _backend = backend
34
+
35
+
36
+ def get_backend() -> str:
37
+ return _backend
38
+
39
+
40
+ def _use_nki() -> bool:
41
+ if _backend == "nki":
42
+ return True
43
+ if _backend == "pytorch":
44
+ return False
45
+ return HAS_NKI
46
+
47
+
48
+ if HAS_NKI:
49
+
50
+ @nki.jit
51
+ def jacobi_rotation_kernel(
52
+ D_ref, V_ref, p: int, q: int, c: float, s: float, n: int
53
+ ):
54
+ """Apply single Jacobi rotation to D and V matrices.
55
+
56
+ D' = G^T @ D @ G (updates rows/cols p, q of D)
57
+ V' = V @ G (accumulates eigenvectors)
58
+
59
+ G is the Givens rotation matrix with cos(θ)=c, sin(θ)=s
60
+ at positions (p,q).
61
+
62
+ On Tensor Engine: the 2-row/col update is a rank-2 operation.
63
+ On Vector Engine: the element-wise updates along rows p, q.
64
+
65
+ STUB: Scaffolded for on-hardware validation.
66
+ """
67
+ # Load rows p and q of D
68
+ d_p = nl.load(D_ref[p, :])
69
+ d_q = nl.load(D_ref[q, :])
70
+
71
+ # Rotate rows
72
+ new_p = nl.add(nl.multiply(d_p, c), nl.multiply(d_q, -s))
73
+ new_q = nl.add(nl.multiply(d_p, s), nl.multiply(d_q, c))
74
+ nl.store(D_ref[p, :], new_p)
75
+ nl.store(D_ref[q, :], new_q)
76
+
77
+ # Rotate columns (D is symmetric, so update cols too)
78
+ d_col_p = nl.load(D_ref[:, p])
79
+ d_col_q = nl.load(D_ref[:, q])
80
+ nl.store(D_ref[:, p], nl.add(nl.multiply(d_col_p, c), nl.multiply(d_col_q, -s)))
81
+ nl.store(D_ref[:, q], nl.add(nl.multiply(d_col_p, s), nl.multiply(d_col_q, c)))
82
+
83
+ # Zero the (p,q) and (q,p) entries
84
+ nl.store(D_ref[p, q], 0.0)
85
+ nl.store(D_ref[q, p], 0.0)
86
+
87
+ # Accumulate eigenvectors: V' = V @ G
88
+ v_p = nl.load(V_ref[:, p])
89
+ v_q = nl.load(V_ref[:, q])
90
+ nl.store(V_ref[:, p], nl.add(nl.multiply(v_p, c), nl.multiply(v_q, -s)))
91
+ nl.store(V_ref[:, q], nl.add(nl.multiply(v_p, s), nl.multiply(v_q, c)))
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: trnsolver
3
+ Version: 0.3.0
4
+ Summary: Linear solvers and eigendecomposition for AWS Trainium via NKI
5
+ Author-email: Scott Friedman <scttfrdmn@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/trnsci/trnsolver
8
+ Project-URL: Documentation, https://trnsci.dev/trnsolver/
9
+ Project-URL: Repository, https://github.com/trnsci/trnsolver
10
+ Project-URL: Issues, https://github.com/trnsci/trnsolver/issues
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: torch>=2.1
20
+ Requires-Dist: numpy>=1.24
21
+ Provides-Extra: neuron
22
+ Requires-Dist: neuronxcc>=2.24; extra == "neuron"
23
+ Requires-Dist: torch-neuronx>=2.9; extra == "neuron"
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=7.0; extra == "dev"
26
+ Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
27
+ Requires-Dist: scipy>=1.11; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # trnsolver
31
+
32
+ [![CI](https://github.com/trnsci/trnsolver/actions/workflows/ci.yml/badge.svg)](https://github.com/trnsci/trnsolver/actions/workflows/ci.yml)
33
+ [![PyPI](https://img.shields.io/pypi/v/trnsolver)](https://pypi.org/project/trnsolver/)
34
+ [![Python](https://img.shields.io/pypi/pyversions/trnsolver)](https://pypi.org/project/trnsolver/)
35
+ [![License](https://img.shields.io/github/license/trnsci/trnsolver)](LICENSE)
36
+ [![Docs](https://img.shields.io/badge/docs-mkdocs-blue)](https://trnsci.github.io/trnsolver/)
37
+
38
+ Linear solvers and eigendecomposition for AWS Trainium via NKI.
39
+
40
+ Eigenvalue problems, matrix factorizations, and iterative solvers for scientific computing on Trainium. The Jacobi eigensolver is the primary NKI acceleration target — each Givens rotation maps to a 2-row matmul on the Tensor Engine.
41
+
42
+ Part of the trnsci scientific computing suite ([github.com/trnsci](https://github.com/trnsci)).
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install trnsolver
48
+
49
+ # With Neuron hardware support
50
+ pip install trnsolver[neuron]
51
+ ```
52
+
53
+ ## Usage
54
+
55
+ ```python
56
+ import torch
57
+ import trnsolver
58
+
59
+ # Symmetric eigenvalue decomposition (Jacobi on NKI)
60
+ eigenvalues, eigenvectors = trnsolver.eigh(A)
61
+
62
+ # Generalized eigenproblem: A x = λ B x (the SCF problem)
63
+ eigenvalues, eigenvectors = trnsolver.eigh_generalized(F, S)
64
+
65
+ # Factorizations
66
+ L = trnsolver.cholesky(A)
67
+ P, L, U = trnsolver.lu(A)
68
+ Q, R = trnsolver.qr(A)
69
+
70
+ # Direct solvers
71
+ x = trnsolver.solve(A, b)
72
+ x = trnsolver.solve_spd(A, b) # Cholesky-based (faster for SPD)
73
+ A_inv_sqrt = trnsolver.inv_sqrt_spd(A) # A^{-1/2} for density fitting
74
+
75
+ # Iterative solvers
76
+ x, iters, residual = trnsolver.cg(A, b, tol=1e-8)
77
+ x, iters, residual = trnsolver.gmres(A, b, tol=1e-6)
78
+ ```
79
+
80
+ ## SCF Example
81
+
82
+ ```bash
83
+ python examples/scf_eigen.py --demo
84
+ python examples/scf_eigen.py --nbasis 50 --nocc 10
85
+ ```
86
+
87
+ Demonstrates the self-consistent field iteration: build Fock matrix → solve generalized eigenproblem FC = SCε → build density → check convergence.
88
+
89
+ ## Operations
90
+
91
+ | Category | Operation | Description |
92
+ |----------|-----------|-------------|
93
+ | Eigen | `eigh` | Symmetric eigendecomposition (Jacobi / torch) |
94
+ | Eigen | `eigh_generalized` | Generalized: Ax = λBx via Cholesky reduction |
95
+ | Factor | `cholesky` | A = LL^T |
96
+ | Factor | `lu` | PA = LU |
97
+ | Factor | `qr` | A = QR |
98
+ | Solve | `solve` | Ax = b (LU-based) |
99
+ | Solve | `solve_spd` | Ax = b (Cholesky, A is SPD) |
100
+ | Solve | `inv_spd` | A^{-1} for SPD A |
101
+ | Solve | `inv_sqrt_spd` | A^{-1/2} for density fitting metric |
102
+ | Iterative | `cg` | Conjugate Gradient (SPD systems) |
103
+ | Iterative | `gmres` | GMRES (general systems) |
104
+
105
+ ## Status
106
+
107
+ - [x] Jacobi eigensolver with PyTorch backend
108
+ - [x] Generalized eigenvalue problem (Cholesky reduction)
109
+ - [x] Cholesky, LU, QR factorizations
110
+ - [x] Direct and SPD solvers
111
+ - [x] CG and GMRES iterative solvers
112
+ - [x] SCF example (quantum chemistry use case)
113
+ - [ ] NKI Jacobi rotation kernel validation
114
+ - [ ] Newton-Schulz A^{-1/2} via trnblas GEMM
115
+ - [ ] Benchmarks vs LAPACK/cuSOLVER
116
+
117
+ ## Related Projects
118
+
119
+ | Project | What |
120
+ |---------|------|
121
+ | [trnfft](https://github.com/trnsci/trnfft) | FFT + complex ops |
122
+ | [trnblas](https://github.com/trnsci/trnblas) | BLAS operations |
123
+ | trnsolver | This repo |
124
+
125
+ ## License
126
+
127
+ Apache 2.0 — Copyright 2026 Scott Friedman
@@ -0,0 +1,11 @@
1
+ trnsolver/__init__.py,sha256=_b9l0h05EWXkfBx6-vqONlJXEczM4LqmBe5Nwv6BIkM,927
2
+ trnsolver/eigen.py,sha256=DNubX9zGe2_oY5OirtgZ_MkyYx6usLs01NtJ8sHaNlQ,5414
3
+ trnsolver/factor.py,sha256=ocUPIK8vkPdPpa_gmbxTq5DAoY3HrM6b5B02LUEhhtg,4808
4
+ trnsolver/iterative.py,sha256=J3NHCirwY0YhD2GnrqQlguCzRH-GgSI5NU4CP5obCvE,5333
5
+ trnsolver/nki/__init__.py,sha256=931tvEv0-8H-9urnDd9KkSmAUdlxHiCKeBvuDXFkLek,192
6
+ trnsolver/nki/dispatch.py,sha256=aJowSyPncJWWDA-A3tmF7U96BGQ5aSvBdVWMBO2OBOw,2780
7
+ trnsolver-0.3.0.dist-info/licenses/LICENSE,sha256=hTt_varGm4HTIVm8GQ1pGR7jah4vW5IrddFIu94FPAE,11175
8
+ trnsolver-0.3.0.dist-info/METADATA,sha256=vLVlAT40npUx8DEAhPGhKB_2crSX-GQs73P7--ziclM,4420
9
+ trnsolver-0.3.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ trnsolver-0.3.0.dist-info/top_level.txt,sha256=GSWEYFB46Xyi7LrVpr5PKwtA_huGp8HY26_E-668_N4,10
11
+ trnsolver-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2026 Scott Friedman
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for describing the origin of the Work and
143
+ reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may accept support,
169
+ obligations, or other liability only on behalf of Yourself and on
170
+ Your sole responsibility, not on behalf of any other Contributor,
171
+ and only if You agree to indemnify, defend, and hold each Contributor
172
+ harmless for any liability incurred by, or claims asserted against,
173
+ such Contributor by reason of your accepting any such warranty or
174
+ additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Friedman
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ trnsolver