Skip to main content

trnsolver

CI codecov Ruff PyPI Python License Docs

Linear solvers and eigendecomposition for AWS Trainium via NKI.

Eigenvalue problems, matrix factorizations, and iterative solvers for scientific computing on Trainium. The batched Jacobi eigensolver is the primary NKI acceleration target — whole sweeps run SBUF-resident, with the Tensor Engine doing the pair permutations (and, for 33 ≤ n ≤ 128, the Gram and rotation matmuls) and the Vector Engine the rotations. The Newton-Schulz matrix-sqrt-inverse is the secondary target: an all-GEMM iteration whose shape aligns with the Tensor Engine pipeline.

Part of the trnsci scientific computing suite (github.com/trnsci).

Current phase

trnsolver follows the trnsci 5-phase roadmap. Active work is tracked in phase-labeled GitHub issues:

Install

pip install trnsolver

# Trn2/Trn3 with TorchNeuron (native PyTorch, Neuron SDK 2.33+)
pip install "trnsolver[torchneuron]" --extra-index-url https://pip.repos.neuron.amazonaws.com

# Trn1 / PyTorch-XLA lineage
pip install "trnsolver[neuron]" --extra-index-url https://pip.repos.neuron.amazonaws.com

Kernels dispatch on whichever Neuron PyTorch lineage is installed:

  • TorchNeuron (native): Trn2/Trn3, Neuron SDK 2.33+, Python ≥ 3.12, torch 2.14, torch-neuronx 2.14.*. Each kernel is a PyTorch custom op (torch.ops.trnsolver.*) on the neuron device; no torch_xla.
  • PyTorch/XLA: Trn1 (and any host on the torch-neuronx 2.9 lineage). Kernels dispatch through torch_xla, unchanged.

trnsolver picks the native path when the native torch_neuronx and a neuron device are present, and the XLA path when torch_xla is installed. Set TRNSCI_NKI_DISPATCH=native, xla or cpu (shared by all trnsci libraries) to force a path. With an editable install (pip install -e), set NKI_ENABLE_TRACE_CACHE=0: the NKI kernel cache only versions installed wheels and can serve stale kernels. See installation.

Known platform issue: NKI trace cache and kernel factories

import torch_neuronx turns on the NKI trace cache, and the cache key ignores constants captured in a kernel's closure: two @nki.jit kernels built by one factory, differing only in a captured value, share one trace, and the second silently returns the first's results (aws-neuron/aws-neuron-sdk#1454). trnsolver's kernels do not rely on closure constants (or on module globals that can differ between processes): every value that specialises a kernel is a kernel argument, and tests/test_trace_cache_safety.py enforces this. If you write your own NKI kernels with a factory, set NKI_ENABLE_TRACE_CACHE=0 before importing torch_neuronx.

Quick example

import torch
import trnsolver

# Symmetric eigenvalue decomposition
w, V = trnsolver.eigh(A)

# Generalized eigenproblem: A x = λ B x  (the SCF problem)
w, V = trnsolver.eigh_generalized(F, S)

# Large / diffuse basis: build X once (fp64, host), drop near-dependencies
orth = trnsolver.orthogonalizer(S, "canonical", lindep=1e-7)  # X: (n, m), rank m
w, V = trnsolver.eigh_generalized(F, S, X=orth.X)  # X^T F X, eigh, X C'

# Factorizations + direct solves
L = trnsolver.cholesky(A)
U, s, Vh = trnsolver.svd(A)  # economy SVD: A = U @ diag(s) @ Vh
x = trnsolver.solve_spd(A, b)
M = trnsolver.inv_sqrt_spd(A)  # eigendecomposition-based
M, iters, res = trnsolver.inv_sqrt_spd_ns(A, tol=1e-8)  # Newton-Schulz, all-GEMM

# Pseudoinverse (Moore-Penrose, truncated SVD)
Ap = trnsolver.pinv(A)

# Iterative solvers with preconditioners
precond = trnsolver.jacobi_preconditioner(A)
blk_precond = trnsolver.block_jacobi_preconditioner(A, block_size=16)
ssor_precond = trnsolver.ssor_preconditioner(A, omega=1.0)  # symmetric Gauss-Seidel
x, iters, res = trnsolver.cg(A, b, M=ssor_precond, tol=1e-8)
x, iters, res = trnsolver.gmres(A, b, tol=1e-6)

Why

Trainium has no native LAPACK. Every SCF iteration, every density-fitting metric inversion, every Krylov solve on Trainium currently falls back to torch.linalg on the host CPU or hand-rolled wrappers. trnsolver closes that gap: same solver API surface, NKI-accelerated Jacobi on the Tensor Engine, PyTorch fallback everywhere else.

SCF example

python examples/scf_eigen.py --demo
python examples/scf_eigen.py --nbasis 50 --nocc 10

Demonstrates the self-consistent-field iteration: build Fock matrix → solve generalized eigenproblem FC = SCε → build density → check convergence. This is the headline use case for quantum-chemistry workflows, feeding into DF-MP2 via trnblas.

examples/scf_df_rhf.py is the end-to-end version: density-fitted restricted Hartree–Fock with the J/K build on packed three-centre integrals (trnblas, trntensor), DIIS, and trnsolver.eigh every iteration, on the host or a NeuronCore. scripts/bench_scf.py times each stage against the CPU and float64 (PySCF integrals for real molecules if PySCF is installed; a synthetic s-Gaussian H2 lattice otherwise):

python examples/scf_df_rhf.py --system h2-lattice:16
python scripts/bench_scf.py --systems h2-lattice:16 --modes cpu,cpu64
python scripts/bench_scf.py --systems pyscf:alkane20 --modes cpu,neuron,neuron-nosync   # on Trn2
python examples/scf_df_mp2.py --system pyscf:water --reference   # DF-MP2 on the converged SCF
python scripts/bench_scf_ladder.py --dry-run   # 500-3500 AO ladder: memory, cores / chips, window plan

Status

v0.20.0 — Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron; trnsci/trnsci#35). Opt-in per-core worker-process pool for batched Jacobi eigh (TRNSOLVER_EIGH_POOL=proc with TRNSOLVER_EIGH_CORES): 3.65× scaling on 4 cores; at n = 128, B = 4096 it takes 324 ms against 531 ms for the thread split and 655 ms for 8-thread batch-parallel CPU LAPACK (#57). eigh of a host tensor on a TorchNeuron host now takes the host-LAPACK cutover instead of the NKI path (an n = 64 call was 265 s, now 0.15 ms). New examples/scf_df_rhf.py: DF-RHF SCF end to end on the trnsci libraries (#58).

v0.19.0 — Opt-in batched Jacobi eigh across logical NeuronCores (TRNSOLVER_EIGH_CORES=<k>|auto, one host thread per core): n = 128, B = 1024 goes 310 → 152 ms on four cores (#54). Corrects the v0.18.0 headline: against a CPU baseline that splits the batch over the same threads, single core at n = 128, B = 1024 is 1.13× (310 vs 352 ms), and the best multi-core result is at most 1.25× faster than 8 CPU threads (#54, #55).

v0.18.0 — Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron; LNC=1 and LNC=2; trnsci/trnsci#35). eigh(A, method="jacobi") gains a block Jacobi NKI kernel for 33 ≤ n ≤ 128 (padded sizes 64 and 128), and eigh(method="auto") now uses the Jacobi kernel for FP32 batches on the neuron device inside a measured (n, B) region, where it beats the aten cutover (#52). Outside the region the default cutover is unchanged. The release's "1.5–2.2× faster than CPU LAPACK" (321 vs 668 ms at n=128, B=1024) used batched torch.linalg.eigh as the baseline; corrected in v0.19.0.

v0.17.0 — Native TorchNeuron dispatch (Trn2/Trn3) alongside the PyTorch/XLA path (Trn1, maintenance); validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0; trnsci/trnsci#35). New eigh(A, method="jacobi"): a batched one-sided Jacobi NKI kernel for FP32 n ≤ 128 on the neuron device, with a batched-matmul torch path everywhere else (#50). At n=32, B=1024 it takes 40.2 ms against 60.5 ms for CPU LAPACK. The default eigh dispatch and its small-n cutover to torch.linalg.eigh are unchanged.

v0.16.0 — Trn2 validation (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron device; trnsci/trnsci#35). eigh on the neuron device uses torch.linalg.eigh below TRNSOLVER_EIGH_NKI_MIN_N (default 512), and the NKI path runs its QR iteration on host tensors (#42). apply_reflectors_kernel compiles under NKI 0.7.0 / neuronx-cc 2.28. cholesky, solve, solve_spd, inv_spd, eigh_generalized and qr trace to Neuron-lowerable ops under torch.compile (#41); eigh (NKI path), cg, gmres and gmres_ir are eager-only.

v0.15.0 — gmres_ir(A, b, ...). GMRES with iterative refinement: Carson–Higham two-precision framework for general (non-symmetric) Ax = b. FP32 LU(A) computed once as a left preconditioner; each outer step computes a FP64 residual and solves the preconditioned correction via inner GMRES (FP32 Krylov). Extends the solve_spd(iterative_refinement=True) pattern from SPD Cholesky to general LU. Reliable for cond(A) ≲ 1e7. Returns (x, total_inner_iters, fp64_residual). BF16 inner matvec (50–100× via Tensor Engine + SR) deferred to v0.16.0.

v0.14.0 — BF16-native sketch path for eigh_randomized (Principle 1). New matmul_kernel_fp32out kernel: BF16 inputs → FP32 output via nc_matmul PSUM accumulation. When A is BF16 and NKI is active, eigh_randomized keeps A in BF16, routes all sketch/projection matmuls through matmul_kernel_fp32out, and runs QR/eigh in FP32. This delivers 50–100× BF16 throughput on the Tensor Engine while retaining FP32 accumulation quality — the PSUM upgrade is free.

v0.13.0 — eigh_randomized(A, k, oversampling=10, n_iter=0, seed=None). Randomized symmetric eigensolver implementing the Nakatsukasa–Tropp sketch-and-Rayleigh-Ritz (sRR) algorithm (SIAM SIMAX 45(2), 2024). O(n²k) vs O(n³) for eigh. Returns k eigenvalues of largest absolute magnitude and their corresponding orthonormal eigenvectors.

v0.12.0 — apply_reflectors_kernel. Fused Householder reflector application: the eigenvector assembly step of eigh (n-2 iterations of Q ← Q − 2 v (vᵀQ)) is now a single NKI dispatch resident entirely in SBUF. SBUF layout trick: maintain Q^T in SBUF so the reduction p = v^T Q uses free-dim sum (axis=1, supported) instead of partition-dim sum (unsupported in NKI 0.3.0). All Vector Engine ops; simulator-safe.

v0.11.0 — matmul_kernel (Tensor Engine via nisa.nc_matmul) + matmul_kernel_sim (Vector Engine, simulator-safe). The Rayleigh-Ritz refinement step in eigh now routes all three GEMMs through the Tensor Engine on hardware. Resolves the NKI 0.3.0 free-dim constraint that blocked the earlier vector matvec attempt (#36): a matrix moving operand (n, k) with k > 1 satisfies the constraint. Closes #36.

v0.10.0 — schur(A, tol=1e-10). Schur decomposition: returns (Q, T) with A = Q @ T @ Q.T. T is quasi-upper triangular (2×2 blocks for complex eigenvalue pairs). Implemented via Householder Hessenberg reduction + Francis implicit double-shift QR with deflation. Closes the last Factorizations "Deferred" item.

v0.9.0 — svd(A, full_matrices=False). Singular Value Decomposition: returns (U, s, Vh). Economy SVD by default; BF16/FP16 promoted to FP32. Closes the svd item in the API table.

v0.8.0 — ssor_preconditioner(A, omega=1.0) (#28). SSOR preconditioner for SPD systems: two triangular solves + diagonal scaling per application. Outperforms scalar Jacobi on coupled matrices (1D Laplacian, FEM stiffness). ω ∈ (0, 2); ω=1 is symmetric Gauss-Seidel.

v0.7.0 — BF16/FP16 dtype support across the full public API (#19). All entry points (cholesky, lu, qr, solve, solve_spd, inv_spd, pinv, inv_sqrt_spd, inv_sqrt_spd_ns, eigh, eigh_generalized, cg, gmres, block_jacobi_preconditioner) accept BF16/FP16 inputs, upcast to FP32 internally, and restore the original dtype on output.

v0.6.0 — eigh subspace rotation refinement: one Rayleigh-Ritz step (V^T A V re-diagonalization) after Householder-QR reduces eigenvector residuals by 1–2 orders of magnitude for n ≥ 64 (#31). solve_spd gains iterative_refinement=True: mixed-precision FP64 residual + second Cholesky solve for SPD systems with cond up to ~1e7 (#32).

API coverage:

Category Shipped (v0.20.0) Deferred
Eigensolvers eigh, eigh_generalized, eigh_randomized, occupied_subspace —
Orthogonalizers orthogonalizer (symmetric, canonical, pivoted Cholesky) —
Factorizations cholesky, lu, qr, svd, pinv, schur —
Direct solvers solve, solve_spd, inv_spd, inv_sqrt_spd, inv_sqrt_spd_ns —
Iterative cg (w/ preconditioner), gmres, gmres_ir —
Preconditioners jacobi_preconditioner, block_jacobi_preconditioner, ssor_preconditioner —

Roadmap:

  • v0.4.0 — NKI Householder-QR eigh validated on trn1.2xlarge (#9, #12, #38)
  • v0.4.1 — eigh_generalized NKI triangular-solve path via trnblas.trsm (#11)
  • v0.5.0 — Newton-Schulz trnblas.gemm (#14), FP64 CG/GMRES dots + Rayleigh refinement (#27), block-Jacobi (#16), pinv (#22)
  • v0.6.0 — eigh subspace rotation refinement (#31), solve_spd iterative refinement (#32)
  • v0.7.0 — BF16/FP16 across the full API (#19) ✓
  • v0.8.0 — SSOR preconditioner (#28) ✓
  • v0.9.0 — svd factorization ✓
  • v0.10.0 — schur (implicit-shift QR via Householder + Francis double-shift) ✓
  • v0.11.0 — Tensor Engine matmul kernel (nisa.nc_matmul), Rayleigh-Ritz on NKI (#36) ✓
  • v0.12.0 — Fused Householder reflector application (apply_reflectors_kernel) ✓
  • v0.13.0 — eigh_randomized (Nakatsukasa–Tropp sRR, O(n²k), Tensor Engine sketch) ✓
  • v0.14.0 — matmul_kernel_fp32out + BF16-native sketch in eigh_randomized (Principle 1: BF16→FP32 PSUM, 50–100× at BF16) ✓
  • v0.15.0 — gmres_ir: Carson–Higham iterative refinement for general Ax = b (FP32 LU preconditioner + FP64 outer residual) ✓
  • v0.16.0 — Trn2 validation on Neuron SDK 2.33 (native TorchNeuron device): eigh small-n cutover, NKI 0.7.0 kernel fixes, torch.compile-traceable factorizations ✓
  • v0.17.0 — Native TorchNeuron dispatch; batched Jacobi eigh(method="jacobi") kernel on Trn2 ✓
  • v0.18.0 — Block Jacobi kernel for 33 ≤ n ≤ 128; eigh(method="auto") uses the Jacobi kernel in a measured region on Trn2 ✓
  • v0.19.0 — Batched Jacobi eigh across logical NeuronCores, opt-in TRNSOLVER_EIGH_CORES (#54) ✓
  • v0.20.0 — Per-core worker-process pool for batched Jacobi (TRNSOLVER_EIGH_POOL=proc, #57); DF-RHF SCF example (#58) ✓
  • Later — BF16 inner matvec for GMRES-IR via matmul_kernel_fp32out + SR (Principle 3); block RHS support; NKI Hessenberg reduction kernel

Operations

Category Operation Description
Eigen eigh Symmetric eigendecomposition (Jacobi / torch)
Eigen eigh_generalized Generalized: Ax = λBx via Cholesky reduction, or via a precomputed X=
Eigen orthogonalizer X with XᵀSX = I on S's kept subspace: Löwdin, canonical or pivoted Cholesky, dropping near-linear dependencies
Eigen eigh_randomized Randomized: k dominant eigenpairs, O(n²k), sRR
Eigen occupied_subspace Lowest k eigenpairs for SCF: warm-started Chebyshev-filtered subspace iteration, one NKI launch per pass (F resident in SBUF)
Factor cholesky A = LL^T
Factor lu A = PLU
Factor qr A = QR
Factor svd A = U diag(s) Vh (economy by default)
Factor pinv Moore-Penrose pseudoinverse (truncated SVD)
Solve solve Ax = b (LU-based)
Solve solve_spd Ax = b (Cholesky, A is SPD)
Solve inv_spd A^{-1} for SPD A
Solve inv_sqrt_spd A^{-1/2} via eigendecomposition
Solve inv_sqrt_spd_ns A^{-1/2} via Newton-Schulz (all-GEMM)
Iterative cg Conjugate Gradient (SPD systems)
Iterative gmres GMRES (general systems)
Iterative gmres_ir GMRES-IR: iterative refinement, FP64 outer residual
Iterative jacobi_preconditioner Diagonal preconditioner for CG
Iterative block_jacobi_preconditioner Block-diagonal Cholesky preconditioner for CG
Iterative ssor_preconditioner SSOR / symmetric Gauss-Seidel preconditioner for CG

Benchmarks

CPU baselines (torch.linalg, scipy.linalg, trnsolver PyTorch path) run on every CI build; CUDA baselines (benchmarks/bench_cuda.py, cuSOLVER via torch.linalg) run on a vintage-matched g5.xlarge A10G instance; Trn2 numbers (batched Jacobi eigh, DF-RHF SCF) are measured by scripts/bench_jacobi_multicore.py and scripts/bench_scf.py. See the benchmarks page for the latest table and vintage-matching rationale.

Known issues in earlier releases

Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-04 releases. Details are in the CHANGELOG.

Bug Affected Fixed in
eigh on the NKI Householder path (TRNSOLVER_REQUIRE_NKI=1 or a non-native NKI device): float64 input gave garbage results, and n = 1 returned (1, 1) eigenvalues; eigh_generalized inherited both (#83) through 0.20.0 (n = 1 shape: 0.4.0–0.20.0) 0.21.0
Complex Hermitian and batched input to cholesky(upper=True), solve_spd, inv_spd, inv_sqrt_spd, eigh_generalized, eigh_randomized, pinv and ssor_preconditioner used .T instead of .mH (#64) every release through 0.20.0 (pinv since 0.5.0, ssor_preconditioner since 0.8.0) 0.21.0
cg dropped the imaginary part of complex input (unconjugated inner products cast to real), so a complex Hermitian system returned a wrong x with only a UserWarning; a complex A with a real b also lost A's imaginary part (#100) every release through 0.21.0 0.22.0
cg gave a wrong gradient with respect to A (it differentiated a fixed polynomial in A; rel. err 0.55 at n = 5), and schur returned Q, T that silently contributed zero gradient (#76) every release through 0.21.0 0.22.0

All six siblings are on PyPI, along with the umbrella meta-package:

Project What Latest
trnsci Umbrella meta-package pulling the whole suite v0.1.0
trnfft FFT and complex-valued tensors v0.26.0
trnblas BLAS Level 1–3 v0.9.1
trnrand Philox / Sobol / Halton RNG v0.12.1
trnsolver Linear solvers and eigendecomposition v0.20.0
trnsparse Sparse matrix operations v0.12.1
trntensor Tensor contractions (einsum, TT/Tucker) v0.22.0

License

Apache 2.0 — Copyright 2026 Scott Friedman

Disclaimer

trnsci is an independent open-source project. It is not sponsored by, endorsed by, or affiliated with Amazon.com, Inc., Amazon Web Services, Inc., or Annapurna Labs Ltd.

"AWS", "Amazon", "Trainium", "Inferentia", "NeuronCore", "Neuron SDK", and related identifiers are trademarks of their respective owners and are used here solely for descriptive and interoperability purposes. Use does not imply endorsement, partnership, or any other relationship.

All work, opinions, analyses, benchmark results, architectural commentary, and editorial judgments in this repository and on trnsci.dev are those of the project's contributors. They do not represent the views, positions, or commitments of Amazon, AWS, or Annapurna Labs.

Feedback directed at the Neuron SDK or Trainium hardware is good-faith ecosystem commentary from independent users. It is not privileged information, is not pre-reviewed by AWS, and should not be read as authoritative about product roadmap, behavior, or quality.

For official AWS guidance, see aws-neuron documentation and the AWS Trainium product page.

Metadata

Release files for trnsolver 0.22.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for trnsolver 0.22.1
File Size Uploaded Provenance Actions
trnsolver-0.22.1.tar.gz 421.4 kB With provenance Details for trnsolver-0.22.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for trnsolver 0.22.1
File Interpreter ABI Platform Actions
trnsolver-0.22.1-py3-none-any.whl Python 3 none any Details for trnsolver-0.22.1-py3-none-any.whl

Total release size: 540.7 kB

Release files / trnsolver-0.22.1.tar.gz

Download URL trnsolver-0.22.1.tar.gz
Size 421.4 kB
Tags Source
SHA-256 checksum
How to use checksums
b5a54593401adfd3f8fb3d21158f97586656724f7348062561b46e9220674364
BLAKE2b-256 checksum
How to use checksums
2ee068ed376c1d5d698591a7daa8fa551af8a44396ffd1aeeb60e4f5e9527789
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.

Transparency log

Release files / trnsolver-0.22.1-py3-none-any.whl

Download URL trnsolver-0.22.1-py3-none-any.whl
Size 119.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cd961172414883546088fcbeb7aa1e99399e723275ce8409524bb158a5f209c0
BLAKE2b-256 checksum
How to use checksums
37817eb9c387932588e29f36d3480820b72f49cc5967fd651cc281044d08095f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.

Transparency log

Security for trnsolver 0.22.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for trnsolver-0.22.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page