trnsparse 0.1.1__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.
- trnsparse/__init__.py +22 -0
- trnsparse/formats.py +167 -0
- trnsparse/nki/__init__.py +3 -0
- trnsparse/nki/dispatch.py +41 -0
- trnsparse/ops.py +137 -0
- trnsparse/screening.py +90 -0
- trnsparse-0.1.1.dist-info/METADATA +85 -0
- trnsparse-0.1.1.dist-info/RECORD +11 -0
- trnsparse-0.1.1.dist-info/WHEEL +5 -0
- trnsparse-0.1.1.dist-info/licenses/LICENSE +201 -0
- trnsparse-0.1.1.dist-info/top_level.txt +1 -0
trnsparse/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""
|
|
2
|
+
trnsparse — Sparse matrix operations for AWS Trainium via NKI.
|
|
3
|
+
|
|
4
|
+
CSR/COO formats, SpMV, SpMM, and integral screening for
|
|
5
|
+
sparse scientific computing. Part of the trnsci scientific computing suite.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
from .formats import CSRMatrix, COOMatrix, from_dense, from_scipy, eye_sparse
|
|
11
|
+
from .ops import (spmv, spmm, spmv_symmetric, sparse_add, sparse_scale,
|
|
12
|
+
sparse_transpose, nnz_per_row)
|
|
13
|
+
from .screening import schwarz_bounds, screen_quartets, density_screen, sparsity_stats
|
|
14
|
+
from .nki import HAS_NKI, set_backend, get_backend
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"CSRMatrix", "COOMatrix", "from_dense", "from_scipy", "eye_sparse",
|
|
18
|
+
"spmv", "spmm", "spmv_symmetric", "sparse_add", "sparse_scale",
|
|
19
|
+
"sparse_transpose", "nnz_per_row",
|
|
20
|
+
"schwarz_bounds", "screen_quartets", "density_screen", "sparsity_stats",
|
|
21
|
+
"HAS_NKI", "set_backend", "get_backend",
|
|
22
|
+
]
|
trnsparse/formats.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sparse matrix formats for Trainium.
|
|
3
|
+
|
|
4
|
+
CSR (Compressed Sparse Row) and COO (Coordinate) formats with
|
|
5
|
+
conversion routines. CSR is the primary compute format; COO is
|
|
6
|
+
the natural construction format.
|
|
7
|
+
|
|
8
|
+
For quantum chemistry: the two-electron integral tensor (μν|λσ) is
|
|
9
|
+
extremely sparse after Schwarz screening — typically >99% zero for
|
|
10
|
+
large molecules. Storing and operating on it in dense format is
|
|
11
|
+
the difference between O(N⁴) and O(N²) effective cost.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import torch
|
|
17
|
+
from typing import Optional, Tuple
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class CSRMatrix:
|
|
23
|
+
"""Compressed Sparse Row format.
|
|
24
|
+
|
|
25
|
+
For an m×n matrix with nnz non-zeros:
|
|
26
|
+
values: (nnz,) — non-zero values
|
|
27
|
+
col_indices: (nnz,) — column index for each value
|
|
28
|
+
row_ptrs: (m+1,) — row_ptrs[i]:row_ptrs[i+1] span row i's entries
|
|
29
|
+
shape: (m, n)
|
|
30
|
+
"""
|
|
31
|
+
values: torch.Tensor
|
|
32
|
+
col_indices: torch.Tensor
|
|
33
|
+
row_ptrs: torch.Tensor
|
|
34
|
+
shape: Tuple[int, int]
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def nnz(self) -> int:
|
|
38
|
+
return self.values.shape[0]
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def dtype(self) -> torch.dtype:
|
|
42
|
+
return self.values.dtype
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def density(self) -> float:
|
|
46
|
+
return self.nnz / (self.shape[0] * self.shape[1])
|
|
47
|
+
|
|
48
|
+
def to_dense(self) -> torch.Tensor:
|
|
49
|
+
"""Convert to dense tensor."""
|
|
50
|
+
m, n = self.shape
|
|
51
|
+
dense = torch.zeros(m, n, dtype=self.dtype)
|
|
52
|
+
for i in range(m):
|
|
53
|
+
start, end = self.row_ptrs[i].item(), self.row_ptrs[i + 1].item()
|
|
54
|
+
cols = self.col_indices[start:end]
|
|
55
|
+
vals = self.values[start:end]
|
|
56
|
+
dense[i, cols] = vals
|
|
57
|
+
return dense
|
|
58
|
+
|
|
59
|
+
def to_coo(self) -> COOMatrix:
|
|
60
|
+
"""Convert to COO format."""
|
|
61
|
+
rows = []
|
|
62
|
+
for i in range(self.shape[0]):
|
|
63
|
+
start, end = self.row_ptrs[i].item(), self.row_ptrs[i + 1].item()
|
|
64
|
+
rows.extend([i] * (end - start))
|
|
65
|
+
return COOMatrix(
|
|
66
|
+
values=self.values.clone(),
|
|
67
|
+
row_indices=torch.tensor(rows, dtype=torch.long),
|
|
68
|
+
col_indices=self.col_indices.clone(),
|
|
69
|
+
shape=self.shape,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
def __repr__(self) -> str:
|
|
73
|
+
return f"CSRMatrix(shape={self.shape}, nnz={self.nnz}, density={self.density:.4f})"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class COOMatrix:
|
|
78
|
+
"""Coordinate (triplet) format.
|
|
79
|
+
|
|
80
|
+
values: (nnz,) — non-zero values
|
|
81
|
+
row_indices: (nnz,) — row index for each value
|
|
82
|
+
col_indices: (nnz,) — column index for each value
|
|
83
|
+
shape: (m, n)
|
|
84
|
+
"""
|
|
85
|
+
values: torch.Tensor
|
|
86
|
+
row_indices: torch.Tensor
|
|
87
|
+
col_indices: torch.Tensor
|
|
88
|
+
shape: Tuple[int, int]
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def nnz(self) -> int:
|
|
92
|
+
return self.values.shape[0]
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def dtype(self) -> torch.dtype:
|
|
96
|
+
return self.values.dtype
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def density(self) -> float:
|
|
100
|
+
return self.nnz / (self.shape[0] * self.shape[1])
|
|
101
|
+
|
|
102
|
+
def to_dense(self) -> torch.Tensor:
|
|
103
|
+
m, n = self.shape
|
|
104
|
+
dense = torch.zeros(m, n, dtype=self.dtype)
|
|
105
|
+
dense[self.row_indices, self.col_indices] = self.values
|
|
106
|
+
return dense
|
|
107
|
+
|
|
108
|
+
def to_csr(self) -> CSRMatrix:
|
|
109
|
+
"""Convert to CSR format."""
|
|
110
|
+
m, n = self.shape
|
|
111
|
+
# Sort by row then column
|
|
112
|
+
sort_idx = torch.argsort(self.row_indices * n + self.col_indices)
|
|
113
|
+
sorted_rows = self.row_indices[sort_idx]
|
|
114
|
+
sorted_cols = self.col_indices[sort_idx]
|
|
115
|
+
sorted_vals = self.values[sort_idx]
|
|
116
|
+
|
|
117
|
+
# Build row pointers
|
|
118
|
+
row_ptrs = torch.zeros(m + 1, dtype=torch.long)
|
|
119
|
+
for r in sorted_rows:
|
|
120
|
+
row_ptrs[r + 1] += 1
|
|
121
|
+
row_ptrs = torch.cumsum(row_ptrs, dim=0)
|
|
122
|
+
|
|
123
|
+
return CSRMatrix(
|
|
124
|
+
values=sorted_vals,
|
|
125
|
+
col_indices=sorted_cols,
|
|
126
|
+
row_ptrs=row_ptrs,
|
|
127
|
+
shape=self.shape,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
def __repr__(self) -> str:
|
|
131
|
+
return f"COOMatrix(shape={self.shape}, nnz={self.nnz}, density={self.density:.4f})"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# --- Construction helpers ---
|
|
135
|
+
|
|
136
|
+
def from_dense(A: torch.Tensor, threshold: float = 0.0) -> CSRMatrix:
|
|
137
|
+
"""Convert dense matrix to CSR, dropping values with |v| <= threshold."""
|
|
138
|
+
m, n = A.shape
|
|
139
|
+
mask = torch.abs(A) > threshold
|
|
140
|
+
rows, cols = torch.where(mask)
|
|
141
|
+
vals = A[mask]
|
|
142
|
+
|
|
143
|
+
# Build CSR
|
|
144
|
+
coo = COOMatrix(values=vals, row_indices=rows, col_indices=cols, shape=(m, n))
|
|
145
|
+
return coo.to_csr()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def from_scipy(sp_matrix) -> CSRMatrix:
|
|
149
|
+
"""Convert scipy.sparse matrix to CSRMatrix."""
|
|
150
|
+
import scipy.sparse as sp
|
|
151
|
+
csr = sp.csr_matrix(sp_matrix)
|
|
152
|
+
return CSRMatrix(
|
|
153
|
+
values=torch.tensor(csr.data, dtype=torch.float32),
|
|
154
|
+
col_indices=torch.tensor(csr.indices, dtype=torch.long),
|
|
155
|
+
row_ptrs=torch.tensor(csr.indptr, dtype=torch.long),
|
|
156
|
+
shape=csr.shape,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def eye_sparse(n: int, dtype: torch.dtype = torch.float32) -> CSRMatrix:
|
|
161
|
+
"""Sparse identity matrix."""
|
|
162
|
+
return CSRMatrix(
|
|
163
|
+
values=torch.ones(n, dtype=dtype),
|
|
164
|
+
col_indices=torch.arange(n, dtype=torch.long),
|
|
165
|
+
row_ptrs=torch.arange(n + 1, dtype=torch.long),
|
|
166
|
+
shape=(n, n),
|
|
167
|
+
)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NKI dispatch for sparse operations.
|
|
3
|
+
|
|
4
|
+
SpMM is the primary NKI target: gather non-zero column indices into
|
|
5
|
+
dense tiles, run matmul on Tensor Engine, scatter results.
|
|
6
|
+
|
|
7
|
+
The gather/scatter pattern uses the DMA engine for indirect memory
|
|
8
|
+
access, while the matmul runs on the systolic array. This is the
|
|
9
|
+
same pattern used in sparse attention implementations.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
import neuronxcc.nki as nki
|
|
16
|
+
import neuronxcc.nki.language as nl
|
|
17
|
+
HAS_NKI = True
|
|
18
|
+
except ImportError:
|
|
19
|
+
HAS_NKI = False
|
|
20
|
+
|
|
21
|
+
_backend = "auto"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def set_backend(backend: str):
|
|
25
|
+
global _backend
|
|
26
|
+
assert backend in ("auto", "pytorch", "nki")
|
|
27
|
+
if backend == "nki" and not HAS_NKI:
|
|
28
|
+
raise RuntimeError("NKI backend requires neuronxcc")
|
|
29
|
+
_backend = backend
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_backend() -> str:
|
|
33
|
+
return _backend
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _use_nki() -> bool:
|
|
37
|
+
if _backend == "nki":
|
|
38
|
+
return True
|
|
39
|
+
if _backend == "pytorch":
|
|
40
|
+
return False
|
|
41
|
+
return HAS_NKI
|
trnsparse/ops.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sparse matrix operations for Trainium.
|
|
3
|
+
|
|
4
|
+
SpMV (sparse × dense vector), SpMM (sparse × dense matrix),
|
|
5
|
+
sparse addition, and sparse scaling.
|
|
6
|
+
|
|
7
|
+
For quantum chemistry:
|
|
8
|
+
- SpMV: Fock matrix × MO vector in iterative eigensolvers (CG/Davidson)
|
|
9
|
+
- SpMM: Sparse integral tensor × dense MO coefficient matrix
|
|
10
|
+
- Sparse add: Accumulating screened integral contributions
|
|
11
|
+
|
|
12
|
+
On Trainium, SpMV/SpMM map to gather-matmul patterns on the Tensor Engine:
|
|
13
|
+
gather non-zero rows/cols into dense tiles, matmul, scatter back.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import torch
|
|
19
|
+
from typing import Optional
|
|
20
|
+
|
|
21
|
+
from .formats import CSRMatrix, COOMatrix
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def spmv(A: CSRMatrix, x: torch.Tensor, alpha: float = 1.0,
|
|
25
|
+
y: Optional[torch.Tensor] = None, beta: float = 0.0) -> torch.Tensor:
|
|
26
|
+
"""Sparse matrix × dense vector: y = alpha * A @ x + beta * y
|
|
27
|
+
|
|
28
|
+
CSR row-wise dot products — each row's non-zeros dot with
|
|
29
|
+
corresponding entries of x.
|
|
30
|
+
"""
|
|
31
|
+
m, n = A.shape
|
|
32
|
+
assert x.shape[0] == n, f"Dimension mismatch: A is {A.shape}, x is {x.shape}"
|
|
33
|
+
|
|
34
|
+
result = torch.zeros(m, dtype=A.dtype)
|
|
35
|
+
for i in range(m):
|
|
36
|
+
start = A.row_ptrs[i].item()
|
|
37
|
+
end = A.row_ptrs[i + 1].item()
|
|
38
|
+
if start < end:
|
|
39
|
+
cols = A.col_indices[start:end]
|
|
40
|
+
vals = A.values[start:end]
|
|
41
|
+
result[i] = torch.dot(vals, x[cols])
|
|
42
|
+
|
|
43
|
+
result = alpha * result
|
|
44
|
+
if y is not None and beta != 0.0:
|
|
45
|
+
result = result + beta * y
|
|
46
|
+
return result
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def spmm(A: CSRMatrix, B: torch.Tensor, alpha: float = 1.0,
|
|
50
|
+
C: Optional[torch.Tensor] = None, beta: float = 0.0) -> torch.Tensor:
|
|
51
|
+
"""Sparse matrix × dense matrix: C = alpha * A @ B + beta * C
|
|
52
|
+
|
|
53
|
+
Each row of A selects and weights rows of B.
|
|
54
|
+
On NKI: gather selected B rows into dense tile, matmul, scatter.
|
|
55
|
+
"""
|
|
56
|
+
m, n = A.shape
|
|
57
|
+
k = B.shape[1]
|
|
58
|
+
assert B.shape[0] == n, f"Dimension mismatch: A is {A.shape}, B is {B.shape}"
|
|
59
|
+
|
|
60
|
+
result = torch.zeros(m, k, dtype=A.dtype)
|
|
61
|
+
for i in range(m):
|
|
62
|
+
start = A.row_ptrs[i].item()
|
|
63
|
+
end = A.row_ptrs[i + 1].item()
|
|
64
|
+
if start < end:
|
|
65
|
+
cols = A.col_indices[start:end]
|
|
66
|
+
vals = A.values[start:end]
|
|
67
|
+
# vals (nnz_row,) × B[cols] (nnz_row, k) → (k,)
|
|
68
|
+
result[i] = vals @ B[cols]
|
|
69
|
+
|
|
70
|
+
result = alpha * result
|
|
71
|
+
if C is not None and beta != 0.0:
|
|
72
|
+
result = result + beta * C
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def spmv_symmetric(A: CSRMatrix, x: torch.Tensor, alpha: float = 1.0,
|
|
77
|
+
uplo: str = "upper") -> torch.Tensor:
|
|
78
|
+
"""Symmetric sparse matrix × vector using only stored triangle.
|
|
79
|
+
|
|
80
|
+
For symmetric matrices (like the overlap matrix S or density P),
|
|
81
|
+
only half the non-zeros need to be stored. This computes A @ x
|
|
82
|
+
using only the upper or lower triangle entries.
|
|
83
|
+
"""
|
|
84
|
+
m, n = A.shape
|
|
85
|
+
assert m == n, "Matrix must be square for symmetric SpMV"
|
|
86
|
+
result = torch.zeros(m, dtype=A.dtype)
|
|
87
|
+
|
|
88
|
+
for i in range(m):
|
|
89
|
+
start = A.row_ptrs[i].item()
|
|
90
|
+
end = A.row_ptrs[i + 1].item()
|
|
91
|
+
for idx in range(start, end):
|
|
92
|
+
j = A.col_indices[idx].item()
|
|
93
|
+
v = A.values[idx].item()
|
|
94
|
+
result[i] += v * x[j]
|
|
95
|
+
if i != j:
|
|
96
|
+
result[j] += v * x[i] # Symmetric contribution
|
|
97
|
+
|
|
98
|
+
return alpha * result
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def sparse_add(A: CSRMatrix, B: CSRMatrix, alpha: float = 1.0, beta: float = 1.0) -> CSRMatrix:
|
|
102
|
+
"""Sparse matrix addition: C = alpha * A + beta * B
|
|
103
|
+
|
|
104
|
+
Result may have more non-zeros than either input (union of patterns).
|
|
105
|
+
"""
|
|
106
|
+
assert A.shape == B.shape, f"Shape mismatch: {A.shape} vs {B.shape}"
|
|
107
|
+
# Simple implementation via dense (fine for moderate sizes)
|
|
108
|
+
dense = alpha * A.to_dense() + beta * B.to_dense()
|
|
109
|
+
from .formats import from_dense
|
|
110
|
+
return from_dense(dense, threshold=0.0)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def sparse_scale(A: CSRMatrix, alpha: float) -> CSRMatrix:
|
|
114
|
+
"""Scale sparse matrix: B = alpha * A"""
|
|
115
|
+
return CSRMatrix(
|
|
116
|
+
values=alpha * A.values,
|
|
117
|
+
col_indices=A.col_indices.clone(),
|
|
118
|
+
row_ptrs=A.row_ptrs.clone(),
|
|
119
|
+
shape=A.shape,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def sparse_transpose(A: CSRMatrix) -> CSRMatrix:
|
|
124
|
+
"""Transpose sparse matrix (CSR → CSR of A^T)."""
|
|
125
|
+
coo = A.to_coo()
|
|
126
|
+
transposed = COOMatrix(
|
|
127
|
+
values=coo.values,
|
|
128
|
+
row_indices=coo.col_indices,
|
|
129
|
+
col_indices=coo.row_indices,
|
|
130
|
+
shape=(A.shape[1], A.shape[0]),
|
|
131
|
+
)
|
|
132
|
+
return transposed.to_csr()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def nnz_per_row(A: CSRMatrix) -> torch.Tensor:
|
|
136
|
+
"""Number of non-zeros per row."""
|
|
137
|
+
return A.row_ptrs[1:] - A.row_ptrs[:-1]
|
trnsparse/screening.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Integral screening utilities for sparse quantum chemistry.
|
|
3
|
+
|
|
4
|
+
Schwarz screening: |(μν|λσ)| ≤ √(μν|μν) √(λσ|λσ)
|
|
5
|
+
Density screening: |P_λσ (μν|λσ)| ≤ |P_λσ| Q_μν Q_λσ
|
|
6
|
+
|
|
7
|
+
These bounds determine which shell quartets contribute significantly
|
|
8
|
+
to the Fock matrix, turning O(N⁴) integral evaluation into O(N²) for
|
|
9
|
+
large molecules. The sparsity pattern feeds into trnsparse CSR matrices.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
from typing import Tuple
|
|
16
|
+
|
|
17
|
+
from .formats import CSRMatrix, from_dense
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def schwarz_bounds(diagonal_integrals: torch.Tensor) -> torch.Tensor:
|
|
21
|
+
"""Compute Schwarz upper bounds Q_μν = √(μν|μν).
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
diagonal_integrals: (nshells, nshells) diagonal ERI values (μν|μν)
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
Q: (nshells, nshells) Schwarz bounds
|
|
28
|
+
"""
|
|
29
|
+
return torch.sqrt(torch.abs(diagonal_integrals))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def screen_quartets(
|
|
33
|
+
Q: torch.Tensor,
|
|
34
|
+
threshold: float = 1e-10,
|
|
35
|
+
) -> torch.Tensor:
|
|
36
|
+
"""Screen shell quartets using Schwarz inequality.
|
|
37
|
+
|
|
38
|
+
Returns a boolean mask (nshells, nshells) for significant shell pairs.
|
|
39
|
+
A quartet (μν|λσ) is significant if Q_μν * Q_λσ > threshold.
|
|
40
|
+
"""
|
|
41
|
+
# Significant pairs: Q_μν > √threshold (since Q_μν * Q_λσ > threshold)
|
|
42
|
+
pair_threshold = threshold ** 0.5
|
|
43
|
+
return Q > pair_threshold
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def density_screen(
|
|
47
|
+
Q: torch.Tensor,
|
|
48
|
+
P: torch.Tensor,
|
|
49
|
+
threshold: float = 1e-10,
|
|
50
|
+
) -> torch.Tensor:
|
|
51
|
+
"""Density-weighted screening.
|
|
52
|
+
|
|
53
|
+
A quartet contributes if |P_λσ| * Q_μν * Q_λσ > threshold.
|
|
54
|
+
Returns significant (μν) mask given density P and bounds Q.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
Q: (n, n) Schwarz bounds
|
|
58
|
+
P: (n, n) density matrix
|
|
59
|
+
threshold: screening threshold
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
mask: (n, n) boolean — True for significant shell pairs
|
|
63
|
+
"""
|
|
64
|
+
# Max |P_λσ * Q_λσ| over λσ gives the bound for each μν
|
|
65
|
+
PQ = torch.abs(P) * Q
|
|
66
|
+
max_PQ = PQ.max() # Conservative: use global max
|
|
67
|
+
return Q * max_PQ > threshold
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def sparsity_stats(Q: torch.Tensor, threshold: float = 1e-10) -> dict:
|
|
71
|
+
"""Report sparsity statistics for a set of Schwarz bounds.
|
|
72
|
+
|
|
73
|
+
Returns dict with total quartets, significant quartets, sparsity fraction.
|
|
74
|
+
"""
|
|
75
|
+
n = Q.shape[0]
|
|
76
|
+
mask = screen_quartets(Q, threshold)
|
|
77
|
+
n_sig_pairs = mask.sum().item()
|
|
78
|
+
n_total_pairs = n * n
|
|
79
|
+
n_total_quartets = n_total_pairs * n_total_pairs
|
|
80
|
+
n_sig_quartets = n_sig_pairs * n_sig_pairs # Upper bound
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
"n_shells": n,
|
|
84
|
+
"total_pairs": n_total_pairs,
|
|
85
|
+
"significant_pairs": n_sig_pairs,
|
|
86
|
+
"pair_sparsity": 1.0 - n_sig_pairs / n_total_pairs,
|
|
87
|
+
"total_quartets": n_total_quartets,
|
|
88
|
+
"significant_quartets_upper": n_sig_quartets,
|
|
89
|
+
"quartet_sparsity_lower": 1.0 - n_sig_quartets / n_total_quartets,
|
|
90
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: trnsparse
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Sparse matrix operations for AWS Trainium via NKI
|
|
5
|
+
Author-email: Scott Friedman <3011922+scttfrdmn@users.noreply.github.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/trnsci/trnsparse
|
|
8
|
+
Project-URL: Repository, https://github.com/trnsci/trnsparse
|
|
9
|
+
Project-URL: Issues, https://github.com/trnsci/trnsparse/issues
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: torch>=2.1
|
|
18
|
+
Requires-Dist: numpy>=1.24
|
|
19
|
+
Provides-Extra: neuron
|
|
20
|
+
Requires-Dist: neuronxcc>=2.24; extra == "neuron"
|
|
21
|
+
Requires-Dist: torch-neuronx>=2.9; extra == "neuron"
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
24
|
+
Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
|
|
25
|
+
Requires-Dist: scipy>=1.11; extra == "dev"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# trnsparse
|
|
29
|
+
|
|
30
|
+
[](https://github.com/trnsci/trnsparse/actions/workflows/ci.yml)
|
|
31
|
+
[](https://pypi.org/project/trnsparse/)
|
|
32
|
+
[](https://pypi.org/project/trnsparse/)
|
|
33
|
+
[](LICENSE)
|
|
34
|
+
[](https://trnsci.github.io/trnsparse/)
|
|
35
|
+
|
|
36
|
+
Sparse matrix operations for AWS Trainium via NKI.
|
|
37
|
+
|
|
38
|
+
CSR/COO formats, SpMV, SpMM, and integral screening for sparse scientific computing on Trainium. Part of the trnsci scientific computing suite ([github.com/trnsci](https://github.com/trnsci)).
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install trnsparse
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
import torch
|
|
50
|
+
import trnsparse
|
|
51
|
+
|
|
52
|
+
# Dense → sparse
|
|
53
|
+
A = torch.randn(100, 100)
|
|
54
|
+
A[torch.abs(A) < 1.0] = 0.0
|
|
55
|
+
csr = trnsparse.from_dense(A)
|
|
56
|
+
|
|
57
|
+
# SpMV: y = A @ x
|
|
58
|
+
y = trnsparse.spmv(csr, x, alpha=2.0)
|
|
59
|
+
|
|
60
|
+
# SpMM: C = A @ B
|
|
61
|
+
C = trnsparse.spmm(csr, B)
|
|
62
|
+
|
|
63
|
+
# Integral screening
|
|
64
|
+
Q = trnsparse.schwarz_bounds(diagonal_integrals)
|
|
65
|
+
mask = trnsparse.screen_quartets(Q, threshold=1e-10)
|
|
66
|
+
stats = trnsparse.sparsity_stats(Q)
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Operations
|
|
70
|
+
|
|
71
|
+
| Operation | Description |
|
|
72
|
+
|-----------|-------------|
|
|
73
|
+
| `spmv` | Sparse × dense vector |
|
|
74
|
+
| `spmm` | Sparse × dense matrix |
|
|
75
|
+
| `spmv_symmetric` | Symmetric SpMV (half storage) |
|
|
76
|
+
| `sparse_add` | C = αA + βB |
|
|
77
|
+
| `sparse_scale` | B = αA |
|
|
78
|
+
| `sparse_transpose` | A^T |
|
|
79
|
+
| `schwarz_bounds` | Schwarz screening bounds |
|
|
80
|
+
| `screen_quartets` | Shell quartet significance mask |
|
|
81
|
+
| `density_screen` | Density-weighted screening |
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
Apache 2.0 — Copyright 2026 Scott Friedman
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
trnsparse/__init__.py,sha256=WGySJX8sYRTeqRQxgLmHEaudW9yQvfImvP2FuRO98rM,883
|
|
2
|
+
trnsparse/formats.py,sha256=wbMcz7tuJvA94YDRoFkiUVbmDGLFfHsxG-L0DgC-LKc,5069
|
|
3
|
+
trnsparse/ops.py,sha256=m3qDcV7JkUwmiBLjDfp44SZUSomi2jk32Bh0RnilSkA,4520
|
|
4
|
+
trnsparse/screening.py,sha256=N1PK_KOUH9xrW4gD7y9GORTmYeAtJKk4h7aK7xDrcUk,2822
|
|
5
|
+
trnsparse/nki/__init__.py,sha256=x_GaYNPTHt8zQ2kyYKoqFHwfo27pkJz3yesMLMXsUlU,150
|
|
6
|
+
trnsparse/nki/dispatch.py,sha256=LmR3i3uKV6HG_D6JkE5wyvLvskqxysy3BN4F1KRlvBQ,969
|
|
7
|
+
trnsparse-0.1.1.dist-info/licenses/LICENSE,sha256=hTt_varGm4HTIVm8GQ1pGR7jah4vW5IrddFIu94FPAE,11175
|
|
8
|
+
trnsparse-0.1.1.dist-info/METADATA,sha256=-8IsCi2jYuYnJyEzm9an44tRzBi4VqVkoOMiXvZhIHg,2763
|
|
9
|
+
trnsparse-0.1.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
10
|
+
trnsparse-0.1.1.dist-info/top_level.txt,sha256=vQPLVFUEd4e6_JJm4hNvDZ_Fk5jDQJimQyKzQg9jtyE,10
|
|
11
|
+
trnsparse-0.1.1.dist-info/RECORD,,
|
|
@@ -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
|
+
trnsparse
|