trnsparse 0.12.1__tar.gz → 0.13.0__tar.gz
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-0.12.1 → trnsparse-0.13.0}/CHANGELOG.md +128 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/CLAUDE.md +15 -10
- {trnsparse-0.12.1 → trnsparse-0.13.0}/PKG-INFO +26 -8
- {trnsparse-0.12.1 → trnsparse-0.13.0}/README.md +25 -7
- trnsparse-0.13.0/benchmarks/bench_screened_tiles_trn2.py +151 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/api.md +38 -11
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/architecture.md +37 -18
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/benchmarks.md +175 -4
- trnsparse-0.13.0/docs/index.md +48 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/installation.md +12 -2
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/iterative_solvers.md +5 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/migration_scipy.md +1 -1
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/quickstart.md +2 -2
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/sparse_attention.md +29 -4
- {trnsparse-0.12.1 → trnsparse-0.13.0}/pyproject.toml +1 -1
- trnsparse-0.13.0/tests/conftest.py +51 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_attention.py +52 -0
- trnsparse-0.13.0/tests/test_attn_gather.py +140 -0
- trnsparse-0.13.0/tests/test_conformance.py +1544 -0
- trnsparse-0.13.0/tests/test_formats.py +113 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_iterative.py +39 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_native_dispatch.py +111 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_nki_compile.py +132 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_nki_native.py +72 -0
- trnsparse-0.13.0/tests/test_nki_screened_spmm.py +163 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_nki_sim.py +101 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_ops.py +76 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_screening.py +30 -0
- trnsparse-0.13.0/tests/test_trace_cache_safety.py +583 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/__init__.py +1 -1
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/formats.py +16 -4
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/iterative.py +42 -24
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/nki/_native.py +40 -1
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/nki/dispatch.py +280 -54
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/nki/kernels.py +240 -14
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/ops.py +128 -15
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse.egg-info/PKG-INFO +26 -8
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse.egg-info/SOURCES.txt +3 -0
- trnsparse-0.12.1/docs/index.md +0 -34
- trnsparse-0.12.1/tests/conftest.py +0 -20
- trnsparse-0.12.1/tests/test_attn_gather.py +0 -49
- trnsparse-0.12.1/tests/test_formats.py +0 -66
- trnsparse-0.12.1/tests/test_nki_screened_spmm.py +0 -97
- {trnsparse-0.12.1 → trnsparse-0.13.0}/.github/workflows/ci.yml +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/.github/workflows/notify-umbrella.yml +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/.github/workflows/publish.yml +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/.gitignore +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/.pre-commit-config.yaml +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/CODE_OF_CONDUCT.md +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/CONTRIBUTING.md +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/LICENSE +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_bsr_spmm.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_cg_fused_trn2.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_iterative.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_multicore_trn2.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_multiproc_trn2.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_native_trn2.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_power_fused_trn2.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_screening.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_spmm.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/bench_spmv.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/benchmarks/conftest.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/docs/aws_setup.md +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/examples/block_sparse_attention.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/examples/sparse_fock.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/infra/terraform/.terraform.lock.hcl +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/infra/terraform/README.md +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/infra/terraform/main.tf +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/mkdocs.yml +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/scripts/bench_to_md.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/scripts/run_benchmarks.sh +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/scripts/run_neuron_tests.sh +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/scripts/run_simulator_tests.sh +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/setup.cfg +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_bsr.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_core_split.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_examples.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_multicore.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_nki_attn.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_nki_bsr.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_nki_cg_fused.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_nki_spmm.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/tests/test_nki_tail_audit.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/multicore.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/nki/__init__.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/nki/_native_attn.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse/screening.py +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse.egg-info/dependency_links.txt +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse.egg-info/requires.txt +0 -0
- {trnsparse-0.12.1 → trnsparse-0.13.0}/trnsparse.egg-info/top_level.txt +0 -0
|
@@ -7,6 +7,134 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.13.0] — 2026-11-02
|
|
11
|
+
|
|
12
|
+
Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
|
|
13
|
+
|
|
14
|
+
Headline: **correctness fixes — upgrade recommended.** `COOMatrix.to_dense` dropped duplicate entries (#56); `from_scipy` dropped the imaginary part (#58); attention second derivatives were wrong (#65); `spmv`/`spmm` accepted a broadcasting y/C (#67); `chebyshev_coeffs` was not the Chebyshev polynomial for K ≥ 2 (#73); `bsr_diagonal` padded tall matrices (#74); on device, complex `bsr_spmm` dropped the imaginary part (#78), integer `spmv`/`spmm` returned float32 (#79), and an undersized attention mask was accepted (#82). New: bf16 and head_dim > 128 gather attention (#49), and Schwarz-screened tile skipping that beats dense aten for large screened products (#89).
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- **`screened_spmm` skips screened-out tiles (#61).** On the native
|
|
19
|
+
TorchNeuron path the host classifies each 128 x 128 tile of `A` from the
|
|
20
|
+
Schwarz bounds alone (skip / full / partial, exact in fp32) and one keyed
|
|
21
|
+
kernel loads, transposes and multiplies only the kept tiles; partial
|
|
22
|
+
tiles get the element mask on chip. `A` stays dense on the device and
|
|
23
|
+
nothing is gathered. The plan (classification, key, device bounds) is
|
|
24
|
+
cached while the same bound tensor is reused. New keyword
|
|
25
|
+
`symmetric=True` (for `A == A.T`, as for the pair-index ERI matrix) skips
|
|
26
|
+
the Tensor Engine transposes. On Trn2 (LNC=2) at n = 8192, N = 512 it is
|
|
27
|
+
faster than dense aten `A @ B` up to 80% of tiles kept in fp32 (5.9x at
|
|
28
|
+
5%) and up to ~65% in bf16; at n = 4096 up to ~75% (fp32) / not in bf16;
|
|
29
|
+
at n <= 2048 the ~0.25 ms launch floor loses to aten. It beats
|
|
30
|
+
`(A * mask) @ B` and the previous fused kernel at every density for
|
|
31
|
+
n >= 4096. Results are in
|
|
32
|
+
docs/benchmarks.md. `TRNSPARSE_SCREEN_SKIP_TILES=0` restores the
|
|
33
|
+
all-tiles fused kernel. `trnsparse.nki.dispatch.screened_tile_structure`
|
|
34
|
+
exposes the classification.
|
|
35
|
+
|
|
36
|
+
- **Guard against the NKI trace-cache closure bug ([aws-neuron/aws-neuron-sdk#1454](https://github.com/aws-neuron/aws-neuron-sdk/issues/1454),
|
|
37
|
+
trnsci/trnsci#35).** `tests/test_trace_cache_safety.py` (CPU) finds every
|
|
38
|
+
`@nki.jit` kernel and fails if its body, or a helper it calls, reads a
|
|
39
|
+
closure variable or a module global that is not a constant expression
|
|
40
|
+
(reviewed exceptions are allow-listed with a reason), and checks each
|
|
41
|
+
kernel's `__closure__` at runtime against a stub `nki`.
|
|
42
|
+
- Tests: `conftest.py` no longer turns the NKI trace cache off. Neuron tests
|
|
43
|
+
run with it on, as under `import torch_neuronx`, with a fresh
|
|
44
|
+
`NKI_TRACE_CACHE_URL` directory per session (no stale editable-install
|
|
45
|
+
traces). `NKI_ENABLE_TRACE_CACHE=0` still turns it off.
|
|
46
|
+
- README: known platform issue note for #1454.
|
|
47
|
+
|
|
48
|
+
### Fixed
|
|
49
|
+
|
|
50
|
+
- `screened_spmm` with a 1-D `B` on the NKI backend raised `ValueError`
|
|
51
|
+
(pre-existing on main; found by the conformance suite on Trn2 during #61).
|
|
52
|
+
|
|
53
|
+
- **`bsr_spmm` dropped the imaginary part of complex operands on the NKI
|
|
54
|
+
backend** (silent, #78). The static-structure kernel path cast complex
|
|
55
|
+
blocks and `B` to fp32 and the result back to complex, so the imaginary
|
|
56
|
+
part was zero and the value was wrong. Affects 0.8.0 through 0.12.1 on
|
|
57
|
+
Trainium with `block_size=128`. Complex operands now run as real kernel
|
|
58
|
+
launches: one per real part of A, against `[Re B | Im B]`. Autograd works
|
|
59
|
+
through them. Found by the conformance suite on Trn2 (trnsci/trnsci#35).
|
|
60
|
+
- **`spmv` / `spmm` returned float32 for integer operands on the device**
|
|
61
|
+
(silent dtype change, #79). The default `alpha=1.0` (and `beta=1.0`) were
|
|
62
|
+
applied as `alpha * product`. A Python float times an integer tensor
|
|
63
|
+
promotes, so int32/int64 products on a `neuron` operand came back float32.
|
|
64
|
+
Affects every release with the device dense CSR path, through 0.12.1. A
|
|
65
|
+
scale of 1 is now skipped. Found by the conformance suite on Trn2
|
|
66
|
+
- **`block_sparse_attention_tiled` accepted a mask smaller than `seq_len` on
|
|
67
|
+
the NKI path** (silent, #82). With a `(256, 256)` mask and `seq_len = 384`,
|
|
68
|
+
the native `bsr_attn` op returned output rows 256..383 that no mask block
|
|
69
|
+
covers (garbage values, no error). The PyTorch path raised an opaque
|
|
70
|
+
`IndexError`. Every backend now raises `ValueError` unless
|
|
71
|
+
`mask_bsr.shape == (Q rows, K rows)` and K and V have the same length.
|
|
72
|
+
Affects 0.10.0 through 0.12.1. Found by the round-3 device harness on Trn2
|
|
73
|
+
(trnsci/trnsci#35).
|
|
74
|
+
- **`bsr_diagonal` returned length m for a tall matrix** (silent; every
|
|
75
|
+
release 0.3.2–0.12.1, every backend). For a rectangular (m, n) BSR matrix
|
|
76
|
+
with m > n the result was zero-padded to length m; it now has length
|
|
77
|
+
min(m, n), as `torch.diagonal` and scipy do. Square and wide matrices are
|
|
78
|
+
unchanged (#74).
|
|
79
|
+
- **`COOMatrix.to_dense` dropped duplicate entries** (silent; every release
|
|
80
|
+
0.1.1–0.12.1, backend-independent). Repeated `(row, col)` entries were
|
|
81
|
+
assigned rather than summed, so all but one was lost, while `to_csr()`,
|
|
82
|
+
`torch.sparse_coo_tensor` and `scipy.sparse` sum them. This also affected
|
|
83
|
+
`CSRMatrix.to_coo().to_dense()` for a CSR with a repeated column in a row.
|
|
84
|
+
Duplicates are now summed; matrices without duplicates are unchanged (#56).
|
|
85
|
+
- **`chebyshev_coeffs` / `chebyshev_bsr` did not produce the Chebyshev
|
|
86
|
+
polynomial for K >= 2** (silent; every release 0.4.3–0.12.1, every
|
|
87
|
+
backend, host-side coefficients). The conversion from the Templates
|
|
88
|
+
listing used beta_1 = (c alpha_0 / 2)^2 instead of the special-case
|
|
89
|
+
½(c alpha_0)^2, and every later coefficient inherited the error, so the
|
|
90
|
+
worst-case residual after K steps was up to ~3x the Chebyshev bound
|
|
91
|
+
(K = 7). The coefficients now follow Saad's three-term recurrence
|
|
92
|
+
(Alg. 12.1) and the residual is T_K((d - lam)/c) / T_K(d/c) (#73).
|
|
93
|
+
|
|
94
|
+
- **`from_scipy` discarded the imaginary part of complex matrices** (silent;
|
|
95
|
+
every release 0.1.1–0.12.1). Values were always cast to float32, so a
|
|
96
|
+
complex scipy matrix became its real part (one C++ `UserWarning`, no
|
|
97
|
+
error). Complex input now gives `complex64` values; real input is
|
|
98
|
+
unchanged (float32) (#58).
|
|
99
|
+
|
|
100
|
+
- **Second derivatives of `block_sparse_attention_tiled` were wrong**
|
|
101
|
+
(silent; 0.6.0–0.12.1, the releases with attention autograd, on the
|
|
102
|
+
PyTorch backend and the PyTorch/XLA / simulator paths). The backward
|
|
103
|
+
reused the forward's softmax statistics as constants, so differentiating
|
|
104
|
+
it (`create_graph=True`: `gradgradcheck`, gradient penalties, Hessian-
|
|
105
|
+
vector products) dropped their dependence on Q and K, with no error.
|
|
106
|
+
Double backward now differentiates a graph-carrying recomputation; first-
|
|
107
|
+
order gradients are unchanged (#65).
|
|
108
|
+
|
|
109
|
+
- **`spmv` / `spmm` accepted a `y` / `C` that enlarged the output** (silent;
|
|
110
|
+
every release 0.1.1–0.12.1, all backends). `beta * y` was added with plain
|
|
111
|
+
broadcasting, so a `(m, 1)` `y` turned the `(m,)` product into `(m, m)`
|
|
112
|
+
with no error, where `torch.addmv` / `addmm` raise. Such shapes now raise
|
|
113
|
+
`ValueError`; every `y` / `C` that broadcasts to the product's shape works
|
|
114
|
+
as before (#67).
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
- **bf16 Q / K / V raised on the gather attention kernels** (loud; #49).
|
|
118
|
+
Affects released versions **0.4.4 through 0.12.1** with `backend="nki"`
|
|
119
|
+
(or `"auto"` on Neuron): every bf16 call that took the gather kernels,
|
|
120
|
+
i.e. `head_dim > 128` (K-tiled, since 0.6.0), the XLA path, or the native
|
|
121
|
+
path with the static structure off. The weights @ V, dS @ K, dSᵀ @ Q and
|
|
122
|
+
Pᵀ @ dO matmuls paired fp32 P / dS with bf16 operands, and NKI rejects
|
|
123
|
+
mixed fp32 / bf16 `nc_matmul` operands ("if one input is tfloat32/float32,
|
|
124
|
+
both must be"). With `TRNSPARSE_REQUIRE_NKI=1` the call raised. Without it,
|
|
125
|
+
the call fell back to the PyTorch path, which gives correct results but
|
|
126
|
+
runs off the NKI path. The gather kernels now handle precision like the
|
|
127
|
+
static kernels: one operand dtype per call (bf16 when Q, K, V (and dO) are
|
|
128
|
+
all bf16, else fp32); fp32 scores, softmax statistics, D and PSUM; and P /
|
|
129
|
+
dS rounded to the operand dtype before their matmul. The scale and D are
|
|
130
|
+
computed on the host in fp32. fp32 and fp64 inputs give the same values as
|
|
131
|
+
before.
|
|
132
|
+
- **`head_dim` above 128 that is not a multiple of 128 (e.g. 192) raised on
|
|
133
|
+
the NKI attention path** (`AssertionError` in the gather, released 0.6.0
|
|
134
|
+
through 0.12.1). It is now zero-padded to the next multiple of 128 for the
|
|
135
|
+
K-tiled kernels and sliced back; zero columns change no score and no
|
|
136
|
+
gradient (#49).
|
|
137
|
+
|
|
10
138
|
## [0.12.1] — 2026-11-01
|
|
11
139
|
|
|
12
140
|
Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
|
|
@@ -22,7 +22,8 @@ trnsparse/
|
|
|
22
22
|
│ ├── formats.py # CSRMatrix, COOMatrix, BSRMatrix, from_dense
|
|
23
23
|
│ ├── ops.py # spmv, spmm, bsr_spmm, screened_spmm, add, scale, transpose
|
|
24
24
|
│ ├── screening.py # schwarz_bounds, screen_quartets, density_screen
|
|
25
|
-
│ ├── iterative.py # cg_bsr, power_iteration_bsr, jacobi_preconditioner_bsr
|
|
25
|
+
│ ├── iterative.py # cg_bsr, cg_bsr_fused, power_iteration_bsr(_fused), jacobi_preconditioner_bsr
|
|
26
|
+
│ ├── multicore.py # ShardedBSR, ShardedAttention (logical NeuronCores of one chip)
|
|
26
27
|
│ └── nki/
|
|
27
28
|
│ ├── __init__.py
|
|
28
29
|
│ ├── kernels.py # _bsr_spmm_kernel, _screened_spmm_kernel, attention kernels
|
|
@@ -36,24 +37,28 @@ trnsparse/
|
|
|
36
37
|
│ └── block_sparse_attention.py # Block-sparse attention via bsr_spmm
|
|
37
38
|
```
|
|
38
39
|
|
|
39
|
-
## NKI compute strategy
|
|
40
|
+
## NKI compute strategy
|
|
40
41
|
|
|
41
42
|
**Formats:** CSR/COO are interop and PyTorch-fallback formats.
|
|
42
43
|
BSR at `block_size=128` is the NKI compute format — every nonzero block
|
|
43
|
-
is already a 128×128 Tensor Engine tile, zero gather overhead.
|
|
44
|
+
is already a 128×128 Tensor Engine tile, zero gather overhead. Other block
|
|
45
|
+
sizes go straight to the PyTorch path (raise under `TRNSPARSE_REQUIRE_NKI`).
|
|
44
46
|
|
|
45
47
|
**Dispatch hierarchy:**
|
|
46
|
-
1. `spmm(csr, B)` —
|
|
47
|
-
|
|
48
|
+
1. `spmm(csr, B)` — densify-then-GEMM kernel under `nki` / `auto` with NKI;
|
|
49
|
+
`torch.sparse_csr_tensor` on the PyTorch path (within 2× of scipy).
|
|
48
50
|
2. `bsr_spmm(bsr, B)` — NKI kernel `_bsr_spmm_kernel`; one `nc_matmul`
|
|
49
51
|
per nonzero block. `torch.autograd.Function`-wrapped; gradcheck passes.
|
|
50
52
|
3. `screened_spmm(A, diag, B, threshold)` — fused Schwarz + mask + matmul
|
|
51
53
|
in one NKI dispatch; avoids 4 host passes + CSR build + separate SpMM.
|
|
52
|
-
4. `
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
4. `block_sparse_attention_tiled(Q, K, V, mask_bsr, scale=None)` — two-pass
|
|
55
|
+
attention kernels (forward + backward) over the mask's stored blocks;
|
|
56
|
+
`seq_len` must be a multiple of the block size.
|
|
57
|
+
5. `cg_bsr_fused` / `power_iteration_bsr_fused` — whole solve in one launch,
|
|
58
|
+
A SBUF-resident (#22).
|
|
59
|
+
|
|
60
|
+
**Open gaps:** row-bucketing CSR (#15, NKI capability-gated), sharding
|
|
61
|
+
across chips (#16; within one chip `ShardedBSR` shipped in 0.10.0).
|
|
57
62
|
|
|
58
63
|
## Dependencies
|
|
59
64
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: trnsparse
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.13.0
|
|
4
4
|
Summary: Sparse matrix operations for AWS Trainium via NKI
|
|
5
5
|
Author-email: Scott Friedman <scttfrdmn@gmail.com>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -53,12 +53,16 @@ trnsparse follows the [trnsci 5-phase roadmap](https://trnsci.dev/roadmap/). Act
|
|
|
53
53
|
|
|
54
54
|
- **[Phase 1 — correctness](https://github.com/trnsci/trnsparse/issues/14)** ✅ v0.2.0: NKI SpMM validated on trn1 via densify-then-GEMM (see [`trnsci/trnsci#3`](https://github.com/trnsci/trnsci/issues/3)).
|
|
55
55
|
- **v0.3.0** ✅ [`BSRMatrix`](https://trnsci.dev/trnsparse/architecture/) — Trainium-native 128×128 block-sparse format; `bsr_spmm` NKI kernel. CSR becomes interop; BSR is the compute path.
|
|
56
|
-
- **v0.3.2** ✅ `cg_bsr`, `power_iteration_bsr` — iterative solvers over BSR (Python loop; fused kernel
|
|
56
|
+
- **v0.3.2** ✅ `cg_bsr`, `power_iteration_bsr` — iterative solvers over BSR (Python loop; the fused kernel shipped in 0.11.0, below).
|
|
57
57
|
- **v0.4.0** ✅ `screened_spmm` — fused Schwarz-screened SpMM in one NKI dispatch.
|
|
58
58
|
- **v0.4.2** ✅ Block-sparse attention — `BSRMatrix` + `bsr_spmm` as the primitive; `examples/block_sparse_attention.py` + [`docs/sparse_attention.md`](https://trnsci.dev/trnsparse/sparse_attention/).
|
|
59
59
|
- **v0.4.3** ✅ Architecture-friendly alternatives: `chebyshev_bsr` / `richardson_bsr` (fixed-K solvers, no inner products); `block_sparse_attention_tiled` (two-pass, no O(seq²) intermediate).
|
|
60
|
-
- **
|
|
61
|
-
- **
|
|
60
|
+
- **v0.4.4–v0.6.0** ✅ NKI attention kernel pair, NKI backward, `head_dim` multiples of 128 (K-tiling).
|
|
61
|
+
- **v0.8.0–v0.9.0** ✅ Native TorchNeuron path (Trn2/Trn3): static-structure BSR SpMM and attention kernels, split across both LNC=2 cores, bf16 operands on fp32 PSUM.
|
|
62
|
+
- **v0.10.0** ✅ `ShardedBSR` / `ShardedAttention` across the logical NeuronCores of one chip; pre-transposed BSR SpMM beats dense aten up to ~82–98% block density on one core.
|
|
63
|
+
- **v0.11.0** ✅ `cg_bsr_fused` / `prepare_cg_bsr` — one-launch CG and block-Jacobi PCG with A in SBUF (5–56× faster than CPU on Trn2), `power_iteration_bsr_fused`.
|
|
64
|
+
- **[Phase 3 — perf](https://github.com/trnsci/trnsparse/issues/15)**: nnz-bucketing CSR, streaming large-sparse — parked on NKI indirect DMA gather.
|
|
65
|
+
- **[Phase 4 — multi-chip](https://github.com/trnsci/trnsparse/issues/16)**: sharded BSR across chips (within one chip: `ShardedBSR`, v0.10.0).
|
|
62
66
|
- **[Phase 5 — generation](https://github.com/trnsci/trnsparse/issues/17)**: trn2 DMA bandwidth exploitation.
|
|
63
67
|
|
|
64
68
|
_(No Phase 2 for trnsparse — precision inherited from trnblas.)_
|
|
@@ -97,6 +101,19 @@ to force a path. With an editable install (`pip install -e`), set
|
|
|
97
101
|
`NKI_ENABLE_TRACE_CACHE=0`: the NKI kernel cache only versions installed
|
|
98
102
|
wheels and can serve stale kernels.
|
|
99
103
|
|
|
104
|
+
### Known platform issue: NKI trace cache and kernel factories
|
|
105
|
+
|
|
106
|
+
`import torch_neuronx` turns on the NKI trace cache, and the cache key ignores
|
|
107
|
+
constants captured in a kernel's closure: two `@nki.jit` kernels built by one
|
|
108
|
+
factory, differing only in a captured value, share one trace, and the second
|
|
109
|
+
silently returns the first's results
|
|
110
|
+
([aws-neuron/aws-neuron-sdk#1454](https://github.com/aws-neuron/aws-neuron-sdk/issues/1454)).
|
|
111
|
+
trnsparse's kernels do not rely on closure constants (or on module globals that
|
|
112
|
+
can differ between processes): every value that specialises a kernel is a
|
|
113
|
+
kernel argument, and `tests/test_trace_cache_safety.py` enforces this. If you
|
|
114
|
+
write your own NKI kernels with a factory, set `NKI_ENABLE_TRACE_CACHE=0`
|
|
115
|
+
before importing `torch_neuronx`.
|
|
116
|
+
|
|
100
117
|
## Usage
|
|
101
118
|
|
|
102
119
|
```python
|
|
@@ -125,10 +142,10 @@ stats = trnsparse.sparsity_stats(Q)
|
|
|
125
142
|
| Operation | Description |
|
|
126
143
|
|-----------|-------------|
|
|
127
144
|
| `spmv` | Sparse × dense vector (CSR) |
|
|
128
|
-
| `spmm` | Sparse × dense matrix (CSR,
|
|
129
|
-
| `bsr_spmm` | Block-sparse × dense (BSR-native, Tensor Engine) |
|
|
145
|
+
| `spmm` | Sparse × dense matrix (CSR; densify-then-GEMM on NKI, `torch.sparse` otherwise) |
|
|
146
|
+
| `bsr_spmm` | Block-sparse × dense (BSR-native, Tensor Engine; NKI at `block_size=128`, other sizes run on PyTorch) |
|
|
130
147
|
| `screened_spmm` | Fused Schwarz-screened matmul (one NKI dispatch) |
|
|
131
|
-
| `spmv_symmetric` | Symmetric SpMV (
|
|
148
|
+
| `spmv_symmetric` | Symmetric SpMV; references only the `uplo` triangle, as in BLAS `symv` (0.12.1) |
|
|
132
149
|
| `sparse_add` | C = αA + βB |
|
|
133
150
|
| `sparse_scale` | B = αA |
|
|
134
151
|
| `sparse_transpose` | Aᵀ |
|
|
@@ -139,8 +156,9 @@ stats = trnsparse.sparsity_stats(Q)
|
|
|
139
156
|
| `power_iteration_bsr` | Dominant eigenpair via power iteration |
|
|
140
157
|
| `power_iteration_bsr_fused` | Power iteration in one launch (the fused CG kernel's machinery) |
|
|
141
158
|
| `jacobi_preconditioner_bsr` | Diagonal preconditioner for `cg_bsr` |
|
|
159
|
+
| `ShardedBSR` / `ShardedAttention` | BSR SpMM / attention forward split across logical NeuronCores (`trnsparse.multicore`) |
|
|
142
160
|
| `bsr_diagonal` | Extract main diagonal from BSR matrix |
|
|
143
|
-
| `block_sparse_attention_tiled` | Two-pass sparse attention, no O(seq²) intermediate |
|
|
161
|
+
| `block_sparse_attention_tiled` | Two-pass sparse attention, no O(seq²) intermediate, autograd; `seq_len` must be a multiple of the block size |
|
|
144
162
|
| `schwarz_bounds` | Schwarz screening bounds |
|
|
145
163
|
| `screen_quartets` | Shell quartet significance mask |
|
|
146
164
|
| `density_screen` | Density-weighted screening |
|
|
@@ -18,12 +18,16 @@ trnsparse follows the [trnsci 5-phase roadmap](https://trnsci.dev/roadmap/). Act
|
|
|
18
18
|
|
|
19
19
|
- **[Phase 1 — correctness](https://github.com/trnsci/trnsparse/issues/14)** ✅ v0.2.0: NKI SpMM validated on trn1 via densify-then-GEMM (see [`trnsci/trnsci#3`](https://github.com/trnsci/trnsci/issues/3)).
|
|
20
20
|
- **v0.3.0** ✅ [`BSRMatrix`](https://trnsci.dev/trnsparse/architecture/) — Trainium-native 128×128 block-sparse format; `bsr_spmm` NKI kernel. CSR becomes interop; BSR is the compute path.
|
|
21
|
-
- **v0.3.2** ✅ `cg_bsr`, `power_iteration_bsr` — iterative solvers over BSR (Python loop; fused kernel
|
|
21
|
+
- **v0.3.2** ✅ `cg_bsr`, `power_iteration_bsr` — iterative solvers over BSR (Python loop; the fused kernel shipped in 0.11.0, below).
|
|
22
22
|
- **v0.4.0** ✅ `screened_spmm` — fused Schwarz-screened SpMM in one NKI dispatch.
|
|
23
23
|
- **v0.4.2** ✅ Block-sparse attention — `BSRMatrix` + `bsr_spmm` as the primitive; `examples/block_sparse_attention.py` + [`docs/sparse_attention.md`](https://trnsci.dev/trnsparse/sparse_attention/).
|
|
24
24
|
- **v0.4.3** ✅ Architecture-friendly alternatives: `chebyshev_bsr` / `richardson_bsr` (fixed-K solvers, no inner products); `block_sparse_attention_tiled` (two-pass, no O(seq²) intermediate).
|
|
25
|
-
- **
|
|
26
|
-
- **
|
|
25
|
+
- **v0.4.4–v0.6.0** ✅ NKI attention kernel pair, NKI backward, `head_dim` multiples of 128 (K-tiling).
|
|
26
|
+
- **v0.8.0–v0.9.0** ✅ Native TorchNeuron path (Trn2/Trn3): static-structure BSR SpMM and attention kernels, split across both LNC=2 cores, bf16 operands on fp32 PSUM.
|
|
27
|
+
- **v0.10.0** ✅ `ShardedBSR` / `ShardedAttention` across the logical NeuronCores of one chip; pre-transposed BSR SpMM beats dense aten up to ~82–98% block density on one core.
|
|
28
|
+
- **v0.11.0** ✅ `cg_bsr_fused` / `prepare_cg_bsr` — one-launch CG and block-Jacobi PCG with A in SBUF (5–56× faster than CPU on Trn2), `power_iteration_bsr_fused`.
|
|
29
|
+
- **[Phase 3 — perf](https://github.com/trnsci/trnsparse/issues/15)**: nnz-bucketing CSR, streaming large-sparse — parked on NKI indirect DMA gather.
|
|
30
|
+
- **[Phase 4 — multi-chip](https://github.com/trnsci/trnsparse/issues/16)**: sharded BSR across chips (within one chip: `ShardedBSR`, v0.10.0).
|
|
27
31
|
- **[Phase 5 — generation](https://github.com/trnsci/trnsparse/issues/17)**: trn2 DMA bandwidth exploitation.
|
|
28
32
|
|
|
29
33
|
_(No Phase 2 for trnsparse — precision inherited from trnblas.)_
|
|
@@ -62,6 +66,19 @@ to force a path. With an editable install (`pip install -e`), set
|
|
|
62
66
|
`NKI_ENABLE_TRACE_CACHE=0`: the NKI kernel cache only versions installed
|
|
63
67
|
wheels and can serve stale kernels.
|
|
64
68
|
|
|
69
|
+
### Known platform issue: NKI trace cache and kernel factories
|
|
70
|
+
|
|
71
|
+
`import torch_neuronx` turns on the NKI trace cache, and the cache key ignores
|
|
72
|
+
constants captured in a kernel's closure: two `@nki.jit` kernels built by one
|
|
73
|
+
factory, differing only in a captured value, share one trace, and the second
|
|
74
|
+
silently returns the first's results
|
|
75
|
+
([aws-neuron/aws-neuron-sdk#1454](https://github.com/aws-neuron/aws-neuron-sdk/issues/1454)).
|
|
76
|
+
trnsparse's kernels do not rely on closure constants (or on module globals that
|
|
77
|
+
can differ between processes): every value that specialises a kernel is a
|
|
78
|
+
kernel argument, and `tests/test_trace_cache_safety.py` enforces this. If you
|
|
79
|
+
write your own NKI kernels with a factory, set `NKI_ENABLE_TRACE_CACHE=0`
|
|
80
|
+
before importing `torch_neuronx`.
|
|
81
|
+
|
|
65
82
|
## Usage
|
|
66
83
|
|
|
67
84
|
```python
|
|
@@ -90,10 +107,10 @@ stats = trnsparse.sparsity_stats(Q)
|
|
|
90
107
|
| Operation | Description |
|
|
91
108
|
|-----------|-------------|
|
|
92
109
|
| `spmv` | Sparse × dense vector (CSR) |
|
|
93
|
-
| `spmm` | Sparse × dense matrix (CSR,
|
|
94
|
-
| `bsr_spmm` | Block-sparse × dense (BSR-native, Tensor Engine) |
|
|
110
|
+
| `spmm` | Sparse × dense matrix (CSR; densify-then-GEMM on NKI, `torch.sparse` otherwise) |
|
|
111
|
+
| `bsr_spmm` | Block-sparse × dense (BSR-native, Tensor Engine; NKI at `block_size=128`, other sizes run on PyTorch) |
|
|
95
112
|
| `screened_spmm` | Fused Schwarz-screened matmul (one NKI dispatch) |
|
|
96
|
-
| `spmv_symmetric` | Symmetric SpMV (
|
|
113
|
+
| `spmv_symmetric` | Symmetric SpMV; references only the `uplo` triangle, as in BLAS `symv` (0.12.1) |
|
|
97
114
|
| `sparse_add` | C = αA + βB |
|
|
98
115
|
| `sparse_scale` | B = αA |
|
|
99
116
|
| `sparse_transpose` | Aᵀ |
|
|
@@ -104,8 +121,9 @@ stats = trnsparse.sparsity_stats(Q)
|
|
|
104
121
|
| `power_iteration_bsr` | Dominant eigenpair via power iteration |
|
|
105
122
|
| `power_iteration_bsr_fused` | Power iteration in one launch (the fused CG kernel's machinery) |
|
|
106
123
|
| `jacobi_preconditioner_bsr` | Diagonal preconditioner for `cg_bsr` |
|
|
124
|
+
| `ShardedBSR` / `ShardedAttention` | BSR SpMM / attention forward split across logical NeuronCores (`trnsparse.multicore`) |
|
|
107
125
|
| `bsr_diagonal` | Extract main diagonal from BSR matrix |
|
|
108
|
-
| `block_sparse_attention_tiled` | Two-pass sparse attention, no O(seq²) intermediate |
|
|
126
|
+
| `block_sparse_attention_tiled` | Two-pass sparse attention, no O(seq²) intermediate, autograd; `seq_len` must be a multiple of the block size |
|
|
109
127
|
| `schwarz_bounds` | Schwarz screening bounds |
|
|
110
128
|
| `screen_quartets` | Shell quartet significance mask |
|
|
111
129
|
| `density_screen` | Density-weighted screening |
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Trn2: Schwarz-screened SpMM with tile skipping (#61) vs dense aten.
|
|
2
|
+
|
|
3
|
+
Chemistry-shaped inputs: bounds Q sorted in decreasing order (exponential
|
|
4
|
+
decay, as for shells ordered by extent), symmetric A with |A_ij| <= Q_i Q_j,
|
|
5
|
+
and tau chosen
|
|
6
|
+
so that a target fraction of the 128 x 128 tiles survives. Times (ms,
|
|
7
|
+
median of --reps, `torch.neuron.synchronize()` after every call):
|
|
8
|
+
|
|
9
|
+
- tiles: `screened_spmm` (this PR: kept tiles only)
|
|
10
|
+
- tiles sym: `screened_spmm(..., symmetric=True)` (no Tensor Engine transposes)
|
|
11
|
+
- fused: `screened_spmm` with TRNSPARSE_SCREEN_SKIP_TILES off (main's kernel)
|
|
12
|
+
- dense: aten `A @ B` on the device (no screening)
|
|
13
|
+
- masked: aten `(A * mask) @ B` on the device, mask precomputed on the device
|
|
14
|
+
|
|
15
|
+
Errors are against fp64 on the host: `par` = max|C - C_masked64| / max|C_masked64|
|
|
16
|
+
(parity with the screened result), and `bound` = ||C - A64 B64||_F divided by
|
|
17
|
+
the Schwarz bound tau * sqrt(#dropped) * ||B||_F (<= 1 means within the
|
|
18
|
+
threshold-times-norm bound, up to operand rounding).
|
|
19
|
+
|
|
20
|
+
Usage: python bench_screened_tiles_trn2.py [--sizes 2048,4096,8192] [--widths 512]
|
|
21
|
+
[--kept 0.05,0.2,0.5,0.8] [--dtypes fp32,bf16] [--no-fused]
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import math
|
|
28
|
+
import statistics
|
|
29
|
+
import sys
|
|
30
|
+
import time
|
|
31
|
+
|
|
32
|
+
import torch
|
|
33
|
+
|
|
34
|
+
import trnsparse
|
|
35
|
+
from trnsparse.nki import dispatch as _d
|
|
36
|
+
|
|
37
|
+
DEV = "neuron"
|
|
38
|
+
P = 128
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _sync():
|
|
42
|
+
if hasattr(torch, "neuron"):
|
|
43
|
+
torch.neuron.synchronize()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def bench(fn, warmup=2, reps=10):
|
|
47
|
+
for _ in range(warmup):
|
|
48
|
+
fn()
|
|
49
|
+
_sync()
|
|
50
|
+
ts = []
|
|
51
|
+
for _ in range(reps):
|
|
52
|
+
t0 = time.perf_counter()
|
|
53
|
+
fn()
|
|
54
|
+
_sync()
|
|
55
|
+
ts.append((time.perf_counter() - t0) * 1e3)
|
|
56
|
+
return statistics.median(ts)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def make_case(n, width, kept, seed=0):
|
|
60
|
+
g = torch.Generator().manual_seed(seed)
|
|
61
|
+
x = torch.sort(torch.rand(n, generator=g)).values
|
|
62
|
+
Q = torch.exp(-8.0 * x) # decreasing bounds
|
|
63
|
+
diag = Q * Q
|
|
64
|
+
R = 2 * torch.rand(n, n, generator=g) - 1
|
|
65
|
+
A = (R + R.T) / 2 * torch.outer(Q, Q) # symmetric, like (mu nu | lambda sigma)
|
|
66
|
+
B = torch.randn(n, width, generator=g)
|
|
67
|
+
nt = (n + P - 1) // P
|
|
68
|
+
qpad = torch.zeros(nt * P)
|
|
69
|
+
qpad[:n] = Q
|
|
70
|
+
qmax = qpad.reshape(nt, P).amax(1)
|
|
71
|
+
tile_max = torch.sort(torch.outer(qmax, qmax).flatten(), descending=True).values
|
|
72
|
+
k = max(1, min(len(tile_max) - 1, round(kept * len(tile_max))))
|
|
73
|
+
tau = float((tile_max[k - 1] + tile_max[k]) / 2) # keeps exactly k tiles
|
|
74
|
+
return A, diag, B, Q, tau
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def main():
|
|
78
|
+
ap = argparse.ArgumentParser()
|
|
79
|
+
ap.add_argument("--sizes", default="2048,4096,8192")
|
|
80
|
+
ap.add_argument("--widths", default="512")
|
|
81
|
+
ap.add_argument("--kept", default="0.05,0.2,0.5,0.8")
|
|
82
|
+
ap.add_argument("--dtypes", default="fp32,bf16")
|
|
83
|
+
ap.add_argument("--reps", type=int, default=10)
|
|
84
|
+
ap.add_argument("--no-fused", action="store_true")
|
|
85
|
+
args = ap.parse_args()
|
|
86
|
+
trnsparse.set_backend("nki")
|
|
87
|
+
_d._REQUIRE_NKI = True
|
|
88
|
+
dts = {"fp32": torch.float32, "bf16": torch.bfloat16}
|
|
89
|
+
print(
|
|
90
|
+
"| n | width | dtype | kept tiles | partial | tiles (ms) | tiles sym (ms) | fused main (ms) "
|
|
91
|
+
"| dense aten (ms) | masked aten (ms) | best/dense | par err | bound ratio | compile+1st (s) |"
|
|
92
|
+
)
|
|
93
|
+
print("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|")
|
|
94
|
+
for n in [int(s) for s in args.sizes.split(",")]:
|
|
95
|
+
for width in [int(s) for s in args.widths.split(",")]:
|
|
96
|
+
for dname in args.dtypes.split(","):
|
|
97
|
+
for kept in [float(s) for s in args.kept.split(",")]:
|
|
98
|
+
run_case(n, width, dname, dts[dname], kept, args)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def run_case(n, width, dname, dt, kept, args):
|
|
102
|
+
A, diag, B, Q, tau = make_case(n, width, kept)
|
|
103
|
+
thr = tau * tau
|
|
104
|
+
A = A.to(dt)
|
|
105
|
+
B = B.to(dt)
|
|
106
|
+
_, _, part, frac = _d.screened_tile_structure(Q, tau, n)
|
|
107
|
+
mask = (Q[:, None] * Q[None, :]) > tau
|
|
108
|
+
a_d, b_d = A.to(DEV), B.to(DEV)
|
|
109
|
+
m_d = mask.to(dt).to(DEV)
|
|
110
|
+
|
|
111
|
+
def tiles():
|
|
112
|
+
return trnsparse.screened_spmm(a_d, diag, b_d, thr)
|
|
113
|
+
|
|
114
|
+
def tiles_sym():
|
|
115
|
+
return trnsparse.screened_spmm(a_d, diag, b_d, thr, symmetric=True)
|
|
116
|
+
|
|
117
|
+
t0 = time.perf_counter()
|
|
118
|
+
C = tiles().cpu()
|
|
119
|
+
t_first = time.perf_counter() - t0
|
|
120
|
+
t_tiles = bench(tiles, reps=args.reps)
|
|
121
|
+
C_sym = tiles_sym().cpu()
|
|
122
|
+
t_sym = bench(tiles_sym, reps=args.reps)
|
|
123
|
+
t_fused = float("nan")
|
|
124
|
+
if not args.no_fused and dt == torch.float32: # main's kernel is fp32-only
|
|
125
|
+
_d._SCREEN_SKIP_TILES = False
|
|
126
|
+
try:
|
|
127
|
+
t_fused = bench(tiles, reps=args.reps)
|
|
128
|
+
except Exception as e:
|
|
129
|
+
print(f"# fused failed: {str(e)[:120]}", file=sys.stderr)
|
|
130
|
+
_d._SCREEN_SKIP_TILES = True
|
|
131
|
+
t_dense = bench(lambda: a_d @ b_d, reps=args.reps)
|
|
132
|
+
t_masked = bench(lambda: (a_d * m_d) @ b_d, reps=args.reps)
|
|
133
|
+
A64, B64 = A.double(), B.double()
|
|
134
|
+
ref_m = (A64 * mask) @ B64
|
|
135
|
+
par = max(float((c.double() - ref_m).abs().max() / ref_m.abs().max()) for c in (C, C_sym))
|
|
136
|
+
full = A64 @ B64
|
|
137
|
+
dropped = int((~mask).sum())
|
|
138
|
+
bound = tau * math.sqrt(max(dropped, 1)) * float(B64.norm())
|
|
139
|
+
ratio = float((C.double() - full).norm()) / bound
|
|
140
|
+
best = min(t_tiles, t_sym)
|
|
141
|
+
print(
|
|
142
|
+
f"| {n} | {width} | {dname} | {frac:.0%} | {sum(part)} | **{t_tiles:.2f}** "
|
|
143
|
+
f"| **{t_sym:.2f}** | {t_fused:.2f} | {t_dense:.2f} | {t_masked:.2f} "
|
|
144
|
+
f"| {best / t_dense:.2f} | {par:.1e} | {ratio:.2f} | {t_first:.1f} |",
|
|
145
|
+
flush=True,
|
|
146
|
+
)
|
|
147
|
+
_sync()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
if __name__ == "__main__":
|
|
151
|
+
main()
|
|
@@ -2,29 +2,56 @@
|
|
|
2
2
|
|
|
3
3
|
## Formats
|
|
4
4
|
|
|
5
|
-
- `CSRMatrix(
|
|
6
|
-
- `.from_dense(dense, threshold=0)` — construct by thresholding a dense tensor
|
|
5
|
+
- `CSRMatrix(values, col_indices, row_ptrs, shape)` — compressed sparse row
|
|
7
6
|
- `.to_dense()` — materialize back to a dense `torch.Tensor`
|
|
8
|
-
- `.
|
|
9
|
-
|
|
10
|
-
- `COOMatrix(rows, cols, vals, shape)` — coordinate format
|
|
7
|
+
- `.nnz`, `.shape`, `.dtype`, `.density`
|
|
8
|
+
- `COOMatrix(values, row_indices, col_indices, shape)` — coordinate format
|
|
11
9
|
- `.to_csr()` / `CSRMatrix.to_coo()` — roundtrip conversions
|
|
10
|
+
- `BSRMatrix(blocks, block_col_indices, block_row_ptrs, shape, block_size=128)`
|
|
11
|
+
— block-sparse row, the NKI compute format
|
|
12
|
+
- `.from_dense(dense, block_size=128, threshold=0)`, `.from_csr(csr, ...)`,
|
|
13
|
+
`.to_dense()`, `.to_csr()`
|
|
14
|
+
- The NKI kernels take `block_size=128` only. Other block sizes run on the
|
|
15
|
+
PyTorch path (correct, no NKI), or raise `NotImplementedError` under
|
|
16
|
+
`TRNSPARSE_REQUIRE_NKI=1`.
|
|
17
|
+
- `from_dense(dense, threshold=0)` — CSR from a dense tensor
|
|
18
|
+
- `from_scipy(sp_matrix)`, `eye_sparse(n)`
|
|
12
19
|
|
|
13
20
|
## Ops
|
|
14
21
|
|
|
15
|
-
- `spmv(A, x)` — sparse matrix × dense vector
|
|
16
|
-
- `spmv_symmetric(A, x)` —
|
|
17
|
-
|
|
22
|
+
- `spmv(A, x, alpha=1.0, y=None, beta=0.0)` — sparse matrix × dense vector
|
|
23
|
+
- `spmv_symmetric(A, x, alpha=1.0, uplo="upper")` — symmetric A; only the
|
|
24
|
+
`uplo` triangle is referenced, as in BLAS `symv`, so A may store one
|
|
25
|
+
triangle or the full matrix (0.12.1). A matrix that stores only the
|
|
26
|
+
opposite triangle still uses it, with a `DeprecationWarning` asking for
|
|
27
|
+
the matching `uplo`.
|
|
28
|
+
- `spmm(A, B, alpha=1.0, C=None, beta=0.0)` — sparse matrix × dense matrix
|
|
29
|
+
(on NKI: A densified on the host, then a dense GEMM on the Tensor Engine)
|
|
30
|
+
- `bsr_spmm(A, B)` — BSR × dense, one `nc_matmul` per stored block
|
|
31
|
+
- `screened_spmm(A, diag_integrals, B, threshold)` — fused Schwarz-screened SpMM
|
|
32
|
+
- `block_sparse_attention_tiled(Q, K, V, mask_bsr, scale=None)` — two-pass
|
|
33
|
+
block-sparse attention with autograd; see
|
|
34
|
+
[Sparse attention](sparse_attention.md). `seq_len` must be a multiple of
|
|
35
|
+
`mask_bsr.block_size` (`ValueError` otherwise, since 0.11.0).
|
|
18
36
|
- `sparse_add(A, B, alpha=1.0, beta=1.0)` — `α A + β B`
|
|
19
|
-
- `sparse_scale(A,
|
|
20
|
-
- `
|
|
37
|
+
- `sparse_scale(A, alpha)` — scalar multiply
|
|
38
|
+
- `sparse_transpose(A)` — transpose of a CSR matrix
|
|
39
|
+
- `nnz_per_row(A)`
|
|
40
|
+
|
|
41
|
+
## Iterative solvers
|
|
42
|
+
|
|
43
|
+
`cg_bsr`, `cg_bsr_fused` / `prepare_cg_bsr` (`FusedCGOperator`),
|
|
44
|
+
`chebyshev_bsr`, `chebyshev_coeffs`, `richardson_bsr`,
|
|
45
|
+
`power_iteration_bsr`, `power_iteration_bsr_fused`,
|
|
46
|
+
`jacobi_preconditioner_bsr`, `bsr_diagonal`. See
|
|
47
|
+
[Iterative solvers](iterative_solvers.md).
|
|
21
48
|
|
|
22
49
|
## Screening
|
|
23
50
|
|
|
24
51
|
- `schwarz_bounds(shell_pair_integrals)` — Cauchy-Schwarz bounds $Q_{pq} = \sqrt{(pq|pq)}$
|
|
25
52
|
- `screen_quartets(Q, threshold)` — keep only quartets with $Q_{pq}Q_{rs} > \text{threshold}$
|
|
26
53
|
- `density_screen(Q, P, threshold)` — density-weighted screening
|
|
27
|
-
- `sparsity_stats(
|
|
54
|
+
- `sparsity_stats(Q, threshold=1e-10)` — shell, pair and quartet counts and the sparsity fraction
|
|
28
55
|
|
|
29
56
|
## Dispatch
|
|
30
57
|
|
|
@@ -15,7 +15,7 @@ exact.
|
|
|
15
15
|
|
|
16
16
|
Contrast with CSR, which stores individual nonzero elements. The v0.2.0
|
|
17
17
|
NKI path for CSR materializes the matrix into a dense `(M, K)` tile
|
|
18
|
-
before the matmul (see the [
|
|
18
|
+
before the matmul (see the [dispatch hierarchy](#nki-dispatch-hierarchy) below) —
|
|
19
19
|
necessary for correctness, but it pays the full `M × K` cost whether the
|
|
20
20
|
matrix is sparse or not. BSR skips this because blocks are already dense.
|
|
21
21
|
|
|
@@ -37,11 +37,14 @@ trnsparse/
|
|
|
37
37
|
│ ├── formats.py # CSRMatrix, COOMatrix, BSRMatrix, from_dense
|
|
38
38
|
│ ├── ops.py # spmv, spmm, bsr_spmm, screened_spmm, ...
|
|
39
39
|
│ ├── screening.py # schwarz_bounds, screen_quartets, density_screen
|
|
40
|
-
│ ├── iterative.py # cg_bsr, power_iteration_bsr,
|
|
40
|
+
│ ├── iterative.py # cg_bsr, cg_bsr_fused, power_iteration_bsr(_fused), chebyshev/richardson
|
|
41
|
+
│ ├── multicore.py # ShardedBSR, ShardedAttention (logical NeuronCores of one chip)
|
|
41
42
|
│ └── nki/
|
|
42
43
|
│ ├── __init__.py
|
|
43
|
-
│ ├── kernels.py
|
|
44
|
-
│
|
|
44
|
+
│ ├── kernels.py # BSR / screened / attention / fused CG kernels
|
|
45
|
+
│ ├── dispatch.py # path selection, torch.autograd.Function wrappers (XLA/CPU)
|
|
46
|
+
│ ├── _native.py # TorchNeuron custom ops + register_autograd
|
|
47
|
+
│ └── _native_attn.py # trnsparse::bsr_attn / bsr_attn_bwd composite ops
|
|
45
48
|
├── tests/
|
|
46
49
|
├── examples/
|
|
47
50
|
│ ├── sparse_fock.py # Schwarz-screened Fock (3 paths + trnblas)
|
|
@@ -56,12 +59,17 @@ compute format. `nki/dispatch.py` exposes `HAS_NKI`,
|
|
|
56
59
|
`set_backend("auto"|"pytorch"|"nki")`, `get_backend()`, and the NKI
|
|
57
60
|
entry points.
|
|
58
61
|
|
|
59
|
-
### `spmm(csr, B)` —
|
|
62
|
+
### `spmm(csr, B)` — densify-then-GEMM on NKI, `torch.sparse` otherwise
|
|
60
63
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
64
|
+
On the `pytorch` backend (and under `auto` without NKI) this routes
|
|
65
|
+
through `torch.sparse_csr_tensor` operations, benchmarked within 2× of
|
|
66
|
+
scipy at typical shapes. Under `nki`, and under `auto` when NKI is
|
|
67
|
+
available, A is densified on the host and the v0.2.0 dense GEMM kernel
|
|
68
|
+
runs on the Tensor Engine (`trnsparse::spmm_dense` on the native path). It
|
|
69
|
+
pays the full `M × K` cost, so on Trn2 it stays behind dense aten and far
|
|
70
|
+
behind `torch.sparse` on CPU at low density ([Benchmarks](benchmarks.md)):
|
|
71
|
+
for repeated products on the device, use BSR. SpMV stays on the
|
|
72
|
+
`torch.sparse` path (densified on the host when `x` is on a device).
|
|
65
73
|
|
|
66
74
|
### `bsr_spmm(bsr, B)` — NKI, `_bsr_spmm_kernel`
|
|
67
75
|
|
|
@@ -159,21 +167,32 @@ extension is a follow-up if asked for.
|
|
|
159
167
|
|
|
160
168
|
## Known limits
|
|
161
169
|
|
|
170
|
+
- **BSR block size.** The NKI kernels take `block_size=128` only. Other block
|
|
171
|
+
sizes run on the PyTorch path under `auto` and `nki` (correct, no NKI, no
|
|
172
|
+
failed compile since 0.12.0), and raise `NotImplementedError` under
|
|
173
|
+
`TRNSPARSE_REQUIRE_NKI=1`. `cg_bsr_fused` / `prepare_cg_bsr` raise
|
|
174
|
+
`ValueError` for any other block size.
|
|
162
175
|
- **Row-bucketing CSR** ([#15](https://github.com/trnsci/trnsparse/issues/15)) — parked.
|
|
163
176
|
Requires NKI indirect-DMA gather (not exposed as of NKI 0.3.0). The CSR PyTorch
|
|
164
177
|
fallback is within 2× of scipy; that's the current story.
|
|
165
178
|
- **Fused tile-level attention scores** ([#25](https://github.com/trnsci/trnsparse/issues/25)) —
|
|
166
|
-
|
|
179
|
+
shipped: the NKI kernel pair in v0.4.4, the NKI backward in 0.5.1, and
|
|
180
|
+
K-tiling for `head_dim` a multiple of 128 (256, 512) in 0.6.0.
|
|
167
181
|
`block_sparse_attention_tiled` routes through NKI on the `nki` backend; the
|
|
168
|
-
PyTorch two-pass reference remains on the `pytorch` backend. `
|
|
169
|
-
|
|
182
|
+
PyTorch two-pass reference remains on the `pytorch` backend. `seq_len` must
|
|
183
|
+
be a multiple of the mask's block size (`ValueError` since 0.11.0). bf16
|
|
184
|
+
inputs raise on the gather kernels used for `head_dim > 128`
|
|
185
|
+
([#49](https://github.com/trnsci/trnsparse/issues/49)); the static path
|
|
186
|
+
(`head_dim ≤ 128`) takes bf16.
|
|
170
187
|
- **Fused iterative solvers** ([#22](https://github.com/trnsci/trnsparse/issues/22)) —
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
188
|
+
shipped in 0.11.0: `cg_bsr_fused` runs CG or block-Jacobi PCG in one launch
|
|
189
|
+
with A SBUF-resident and a device-side `nl.while_loop` convergence check, and
|
|
190
|
+
`power_iteration_bsr_fused` uses the same kernel. See
|
|
191
|
+
[Iterative solvers](iterative_solvers.md). `chebyshev_bsr` and
|
|
192
|
+
`richardson_bsr` (v0.4.3) remain host-driven loops over `bsr_spmm`.
|
|
176
193
|
- **Multi-chip sharded BSR** ([#16](https://github.com/trnsci/trnsparse/issues/16)) —
|
|
177
|
-
|
|
194
|
+
across the logical NeuronCores of one Trn2 chip, `ShardedBSR` and
|
|
195
|
+
`ShardedAttention` shipped in 0.10.0 (`trnsparse.multicore`). Sharding across
|
|
196
|
+
chips is still gated on suite-level multi-chip collectives.
|
|
178
197
|
- **SpMV stays PyTorch.** Single output column on the Tensor Engine doesn't amortize
|
|
179
198
|
compile + dispatch overhead.
|