trnsparse 0.13.0__tar.gz → 0.14.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.13.0 → trnsparse-0.14.0}/CHANGELOG.md +270 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/CLAUDE.md +1 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/PKG-INFO +21 -1
- {trnsparse-0.13.0 → trnsparse-0.14.0}/README.md +20 -0
- trnsparse-0.14.0/benchmarks/bench_kernel_matmul_trn2.py +175 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/api.md +62 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/architecture.md +67 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/installation.md +11 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/iterative_solvers.md +5 -1
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/migration_scipy.md +6 -6
- {trnsparse-0.13.0 → trnsparse-0.14.0}/pyproject.toml +1 -1
- trnsparse-0.14.0/scripts/bench_eager_handle.py +144 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/conftest.py +28 -1
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_conformance.py +86 -38
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_formats.py +29 -3
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_iterative.py +257 -0
- trnsparse-0.14.0/tests/test_kernel_dtype_guard.py +955 -0
- trnsparse-0.14.0/tests/test_kernel_matmul.py +600 -0
- trnsparse-0.14.0/tests/test_kernel_matmul_neuron.py +262 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_native_dispatch.py +361 -3
- trnsparse-0.14.0/tests/test_nki_kernel_matmul.py +358 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_native.py +124 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_tail_audit.py +3 -2
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_ops.py +46 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/__init__.py +6 -1
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/formats.py +16 -5
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/iterative.py +252 -32
- trnsparse-0.14.0/trnsparse/kernel_matmul.py +399 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/multicore.py +4 -6
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/nki/_native.py +103 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/nki/dispatch.py +865 -54
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/nki/kernels.py +411 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/ops.py +21 -2
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse.egg-info/PKG-INFO +21 -1
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse.egg-info/SOURCES.txt +7 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/.github/workflows/ci.yml +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/.github/workflows/notify-umbrella.yml +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/.github/workflows/publish.yml +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/.gitignore +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/.pre-commit-config.yaml +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/CODE_OF_CONDUCT.md +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/CONTRIBUTING.md +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/LICENSE +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_bsr_spmm.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_cg_fused_trn2.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_iterative.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_multicore_trn2.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_multiproc_trn2.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_native_trn2.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_power_fused_trn2.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_screened_tiles_trn2.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_screening.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_spmm.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/bench_spmv.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/benchmarks/conftest.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/aws_setup.md +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/benchmarks.md +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/index.md +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/quickstart.md +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/docs/sparse_attention.md +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/examples/block_sparse_attention.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/examples/sparse_fock.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/infra/terraform/.terraform.lock.hcl +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/infra/terraform/README.md +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/infra/terraform/main.tf +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/mkdocs.yml +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/scripts/bench_to_md.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/scripts/run_benchmarks.sh +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/scripts/run_neuron_tests.sh +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/scripts/run_simulator_tests.sh +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/setup.cfg +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_attention.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_attn_gather.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_bsr.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_core_split.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_examples.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_multicore.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_attn.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_bsr.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_cg_fused.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_compile.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_screened_spmm.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_sim.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_nki_spmm.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_screening.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/tests/test_trace_cache_safety.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/nki/__init__.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/nki/_native_attn.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse/screening.py +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse.egg-info/dependency_links.txt +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse.egg-info/requires.txt +0 -0
- {trnsparse-0.13.0 → trnsparse-0.14.0}/trnsparse.egg-info/top_level.txt +0 -0
|
@@ -7,6 +7,276 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.14.0] — 2026-11-04
|
|
11
|
+
|
|
12
|
+
Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
|
|
13
|
+
|
|
14
|
+
Headline: `kernel_matmul` / `KernelOperator`, a fused kernel-matrix product for matrix-free GP and kernel methods (#93, #102, #103), cached eager NKI handles, and the trnsci float64 policy with a dtype guard at the kernel boundary; `cg_bsr` and `power_iteration_bsr` gradients and `from_scipy` dtypes fixed.
|
|
15
|
+
|
|
16
|
+
### Performance
|
|
17
|
+
|
|
18
|
+
- **Eager NKI kernel calls skip the per-call handle rebuild and the custom-op
|
|
19
|
+
layer (same fix as trnblas#92).** On the native path a `trnsparse::`
|
|
20
|
+
custom-op call cost about 0.1 ms of host time before the kernel was queued,
|
|
21
|
+
against 0.016 ms for aten. Most of it went to nki's `Kernel.__call__`,
|
|
22
|
+
which rebuilds the torch handle on every call, plus the `torch.library`
|
|
23
|
+
layer. `dispatch._run` / `_launch` and the direct keyed-op calls (keyed
|
|
24
|
+
`bsr_spmm`, attention forward and backward, fused CG and power iteration,
|
|
25
|
+
`ShardedBSR` / `ShardedAttention`) now call a `torch_neuronx.wrap_nki`
|
|
26
|
+
handle built once per kernel, with the op body's `int()` / `tuple()` /
|
|
27
|
+
`float()` conversions of the static arguments. On trn2 (LNC=2), a
|
|
28
|
+
256x256x128 `spmm_dense` launch drops from 0.126 to 0.036 ms of issue time
|
|
29
|
+
(e2e 0.201 to 0.124 ms), a keyed `bsr_spmm` from 0.255 to 0.157 ms e2e, and
|
|
30
|
+
`cg_bsr_fused` n=256 from 1.36 to 1.19 ms. Results are bit-identical.
|
|
31
|
+
`torch.compile`, requires-grad, int64 and tensor-subclass inputs, and the
|
|
32
|
+
composite `bsr_attn` / `bsr_attn_bwd` ops keep the custom op, as does
|
|
33
|
+
the screened-tile op (`screened_tiles_keyed`, #61) for now. This is the
|
|
34
|
+
same handle cache that `kernel_matmul` launches use (keyed there by
|
|
35
|
+
operand shapes, one handle shared by every row block and core), so
|
|
36
|
+
`TRNSPARSE_NKI_EAGER_HANDLE=0` turns both off;
|
|
37
|
+
`scripts/bench_eager_handle.py` measures it.
|
|
38
|
+
|
|
39
|
+
### Added
|
|
40
|
+
|
|
41
|
+
- **`kernel_matmul` / `KernelOperator`: fused kernel-matrix product
|
|
42
|
+
K(X, Y) @ V that never forms K** (#93, for trnsci/trnsci#109). RBF and
|
|
43
|
+
Matern-1/2, 3/2, 5/2; per-dimension lengthscales; `noise * V` on the
|
|
44
|
+
square operator. One NKI launch per application: squared distances as a
|
|
45
|
+
TensorEngine matmul on augmented coordinates into PSUM, the kernel
|
|
46
|
+
function on ScalarE straight from PSUM, the product with V on the
|
|
47
|
+
TensorEngine. Coordinates are augmented and transposed on chip
|
|
48
|
+
(`nl.load` + `nisa.nc_transpose`); tile loops are rolled
|
|
49
|
+
(`nl.fori_loop`), so trace and compile time do not grow with n; ragged
|
|
50
|
+
n, m and R are handled in the kernel. Both physical cores at LNC=2 with
|
|
51
|
+
the same control flow on each, and bit-identical results at LNC=1 and
|
|
52
|
+
LNC=2. Hyperparameters are a tensor argument (aws-neuron-sdk#1454).
|
|
53
|
+
Eager launches use a cached `torch_neuronx.wrap_nki` handle (the
|
|
54
|
+
trnblas#92 pattern). CPU tests: PyTorch path against float64
|
|
55
|
+
`torch.cdist`; `nki.simulate` at LNC=1/2, MLIR verify and (with
|
|
56
|
+
neuronx-cc) NEFF compile with NKI allocation at LNC=1/2.
|
|
57
|
+
`benchmarks/bench_kernel_matmul_trn2.py` measures kernel entries/s
|
|
58
|
+
against aten on the device and the host CPU at 2 threads and all vCPUs.
|
|
59
|
+
`tile_mask` is reserved and raises for now.
|
|
60
|
+
- **`kernel_matmul`: row blocks spread across all visible logical
|
|
61
|
+
NeuronCores** (#102). On trn2.3xlarge at LNC=2 (`neuron:0..3`, with
|
|
62
|
+
`NEURON_RT_VISIBLE_CORES=0-3`) a row-blocked product issues its blocks
|
|
63
|
+
round-robin over the cores. The block count rounds up to a multiple of
|
|
64
|
+
the core count (`kmv_block_rows(..., parts=k)`; 20 blocks of 53248 rows
|
|
65
|
+
on 4 cores at n = m = 2^20), so each core gets the same number. Y, V and
|
|
66
|
+
params are staged through the host once and placed on each core before
|
|
67
|
+
any kernel is queued. Launches are issued asynchronously from the calling
|
|
68
|
+
thread (NKI tracing stays on one thread, aws-neuron-sdk#1453) and
|
|
69
|
+
gathered in row order on the operands' device, bit-identical to one
|
|
70
|
+
core. `TRNSPARSE_KMV_CORES`: `auto` (default: every visible core when
|
|
71
|
+
`n * m` exceeds the 6e10-entry block budget, else one), `all`, or an
|
|
72
|
+
int. `TRNSPARSE_KMV_THREADS=1` is a fallback that issues each core's
|
|
73
|
+
blocks from a worker thread, after the first block per core has been
|
|
74
|
+
launched on the calling thread. Target: n = 2^20 from about 42 s to about
|
|
75
|
+
11 s per apply on 4 cores. CPU stand-in tests cover block-to-core
|
|
76
|
+
assignment, per-core placement and the gather (bitwise against single
|
|
77
|
+
core). A neuron test compares multi-core with single-core bitwise and
|
|
78
|
+
skips below 2 visible cores.
|
|
79
|
+
|
|
80
|
+
### Changed
|
|
81
|
+
|
|
82
|
+
- **`kernel_matmul`: about 70% fewer instructions per launch** (#103). The
|
|
83
|
+
Trn2 profile on #93 showed the kernel issue-bound: 41% of a launch with
|
|
84
|
+
no engine active. The @V product now takes V's tile as the stationary
|
|
85
|
+
operand and the kernel tile as the moving one. That makes one
|
|
86
|
+
`nc_matmul` per 128 columns of V over all 512 X points of a tile, where
|
|
87
|
+
it was four (one per 128-row chunk, kernel tile stationary). The
|
|
88
|
+
accumulator, out^T, is now one PSUM bank per 128 columns, against four,
|
|
89
|
+
and is transposed back (`nisa.nc_transpose`) once per output block.
|
|
90
|
+
The freed PSUM holds a ring of distance tiles, so a loop body is no
|
|
91
|
+
longer capped at 4 Y tiles. Each body loads its V rows in one DMA,
|
|
92
|
+
against one per Y tile. The body size now defaults to `kmv_group(m)`:
|
|
93
|
+
about sqrt(m / 128) Y tiles, from 4 to 16 (`TRNSPARSE_KMV_GROUP` still
|
|
94
|
+
overrides it, 1 to 32).
|
|
95
|
+
- Instructions per launch, n = 131072, LNC=2, both physical cores,
|
|
96
|
+
counted from the compiled NEFF: **11.5M before, 3.5M now** at group
|
|
97
|
+
16; 6.2M with the old body of 4. That is 44 against 13 instructions per
|
|
98
|
+
128 x 512 tile per core.
|
|
99
|
+
- **Summation order:** with a body of 4 Y tiles (m < 3200 by default,
|
|
100
|
+
or `TRNSPARSE_KMV_GROUP=4`) the result is bit-identical to 0.13.0.
|
|
101
|
+
That is checked in the simulator, with its matmul summed in
|
|
102
|
+
contraction order like the TensorEngine; the device check is on the
|
|
103
|
+
PR. Larger bodies change where the PSUM partial sums are split, so the
|
|
104
|
+
bits change.
|
|
105
|
+
- **Error against float64** goes from about g + m/(128 g) fp32 roundings
|
|
106
|
+
to its minimum: at m = 131072 the max relative error drops from
|
|
107
|
+
9.0e-7 to 5.2e-7 (simulator, rbf and Matern-5/2, R = 1 and 33).
|
|
108
|
+
- Bit-identical at LNC=1 and LNC=2, across row blocks and across cores,
|
|
109
|
+
as before: the body size depends on m only.
|
|
110
|
+
- The simulator tests now run `nc_matmul` as a sum in contraction order
|
|
111
|
+
(numpy's BLAS rounds a column differently with the moving operand's
|
|
112
|
+
width). So the LNC=1 against LNC=2 and row-blocked checks are bitwise
|
|
113
|
+
at every d and every ragged tail. The ragged tails were tolerance-only
|
|
114
|
+
before.
|
|
115
|
+
- `benchmarks/bench_kernel_matmul_trn2.py --dump DIR` saves the results,
|
|
116
|
+
to compare two checkouts with `--compare`.
|
|
117
|
+
- **float64 under `auto` now computes in torch at float64 accuracy
|
|
118
|
+
(previously cast to fp32 on the NKI path)** — the trnsci suite fp64
|
|
119
|
+
policy (#84). Trainium computes float64 at fp32 precision, so no kernel
|
|
120
|
+
can give a float64-accurate result. For `spmm`, `bsr_spmm`,
|
|
121
|
+
`screened_spmm`, `block_sparse_attention_tiled` (forward and backward),
|
|
122
|
+
`cg_bsr` (through `bsr_spmm`), `cg_bsr_fused` and
|
|
123
|
+
`power_iteration_bsr_fused`, a float64 value operand (and complex128 in
|
|
124
|
+
`bsr_spmm`, whose complex path runs as real kernel launches):
|
|
125
|
+
- under `set_backend("auto")` (the default) takes the PyTorch path that
|
|
126
|
+
`set_backend("pytorch")` takes, at float64 accuracy, and no kernel runs
|
|
127
|
+
(the fused solvers take their host path);
|
|
128
|
+
- under an explicit `set_backend("nki")` is cast to fp32 (complex64) for
|
|
129
|
+
the kernel as before, now with a one-time `UserWarning` per op saying
|
|
130
|
+
precision is reduced to fp32;
|
|
131
|
+
- under `TRNSPARSE_REQUIRE_NKI=1` raises `NotImplementedError` (on either
|
|
132
|
+
backend; this takes precedence over the explicit-nki cast).
|
|
133
|
+
|
|
134
|
+
The result dtype always equals the pytorch backend's for the same inputs,
|
|
135
|
+
including bf16 / fp16 and mixed-dtype promotion; a kernel result computed
|
|
136
|
+
in fp32 is cast to that dtype. Callers of 0.2.0 through 0.13.0 who
|
|
137
|
+
relied on float64 inputs running on the kernels under `auto` now get
|
|
138
|
+
torch (more precise; on the host or device aten instead of the kernel):
|
|
139
|
+
pass float32 operands, or select `set_backend("nki")`, to keep the
|
|
140
|
+
kernel. float64 validation runs under REQUIRE_NKI must pass fp32 operands
|
|
141
|
+
(or call the autograd Functions directly, as the hardware gradchecks do).
|
|
142
|
+
Lands in 0.14.0. `screened_spmm` decides on `A` and `B`; a float64 bound
|
|
143
|
+
vector `diag_integrals` alone does not change the route. See
|
|
144
|
+
docs/architecture.md, "Precision and dtypes".
|
|
145
|
+
|
|
146
|
+
**float64 on the `neuron` device runs on the host under `auto`.** Device
|
|
147
|
+
aten computes float64 at fp32 precision as well (measured on Trn2), so
|
|
148
|
+
the torch path alone does not give float64 accuracy for device-resident
|
|
149
|
+
data. When a float64 / complex128 operand of `spmv`, `spmm`,
|
|
150
|
+
`spmv_symmetric`, `bsr_spmm`, `screened_spmm`,
|
|
151
|
+
`block_sparse_attention_tiled` (forward and backward), `cg_bsr`,
|
|
152
|
+
`chebyshev_bsr`, `richardson_bsr`, `power_iteration_bsr` or the
|
|
153
|
+
`jacobi_preconditioner_bsr` preconditioner lives on a `neuron` device
|
|
154
|
+
(dense, or a CSR / COO / BSR matrix's values), the operands are copied to
|
|
155
|
+
the host, host torch computes at float64, and the result returns to the
|
|
156
|
+
dense operand's device in float64, with one `UserWarning` per op ("float64
|
|
157
|
+
on the neuron device is computed on the host for float64 accuracy (device
|
|
158
|
+
arithmetic is fp32); pass float32 to stay on device").
|
|
159
|
+
`TRNSPARSE_FP64_ON_DEVICE=1` keeps device aten (fp32 precision, no
|
|
160
|
+
copies). Host-resident float64, explicit `nki` and the pytorch backend
|
|
161
|
+
are unchanged; the fused solvers already ran float64 on the host.
|
|
162
|
+
**`TRNSPARSE_REQUIRE_NKI=1` raises for float64 / complex128 on the neuron
|
|
163
|
+
device** at every public op (backends `auto` and `nki`, also with
|
|
164
|
+
`TRNSPARSE_FP64_ON_DEVICE=1`), before any host copy or kernel. Before, the
|
|
165
|
+
routes with no kernel (CSR `spmv`, `spmv_symmetric`, `spmm`, the Jacobi
|
|
166
|
+
preconditioner) ran device aten at fp32 precision with no error under
|
|
167
|
+
REQUIRE_NKI and `auto` (Trn2 conformance: `test_spmv[float64-*]` rel err
|
|
168
|
+
1e-8..2e-7 against the 1e-10 tolerance).
|
|
169
|
+
|
|
170
|
+
`kernel_matmul` / `KernelOperator` (#93, new in this release) follow the
|
|
171
|
+
same rules through `dispatch._fp64_route`: under REQUIRE_NKI float64 now
|
|
172
|
+
raises `NotImplementedError` (it raised `TypeError`), and the explicit-nki
|
|
173
|
+
fp32 warning fires once per op (it fired on every call). Integer, bool and
|
|
174
|
+
complex inputs on the NKI path take the PyTorch path, as the pytorch
|
|
175
|
+
backend does (they raised `TypeError`), or raise `NotImplementedError`
|
|
176
|
+
under REQUIRE_NKI. Device-resident float64 under `auto`: `kernel_matmul`
|
|
177
|
+
is guarded like the other ops, and a float64 `KernelOperator` bound for
|
|
178
|
+
the neuron device is built and applied on the host (one `UserWarning`),
|
|
179
|
+
returning each product on V's device.
|
|
180
|
+
|
|
181
|
+
### Fixed
|
|
182
|
+
|
|
183
|
+
- **No NKI kernel is reached with an operand dtype it does not take** (one
|
|
184
|
+
guard at the kernel boundary; trnsci/trnsci#35, the class of #78 and #79).
|
|
185
|
+
At each entry (`spmm`, `bsr_spmm`, `screened_spmm`,
|
|
186
|
+
`block_sparse_attention_tiled` forward and backward), integer and bool
|
|
187
|
+
values, and complex values except in `bsr_spmm` (real kernel launches,
|
|
188
|
+
#78), now take the PyTorch path that `set_backend("pytorch")` takes, or
|
|
189
|
+
raise `NotImplementedError` under `TRNSPARSE_REQUIRE_NKI`. Before, they went
|
|
190
|
+
into the fp32/bf16 kernels on the NKI and auto backends: complex operands of
|
|
191
|
+
`spmm` / `screened_spmm` reached the kernel unchanged, the static attention
|
|
192
|
+
kernels cast complex Q/K/V to fp32 (imaginary part dropped), the static
|
|
193
|
+
`bsr_spmm` and attention kernels cast integers to fp32 and back, and
|
|
194
|
+
REQUIRE_NKI failed with whatever error the kernel raised. float64 follows
|
|
195
|
+
the fp64 policy below (#84); fp32, bf16 and fp16 are unchanged. Every
|
|
196
|
+
launch now also checks a per-kernel, per-operand dtype table itself
|
|
197
|
+
(`_KERNEL_OPERAND_DTYPES`: the native op table, `_run` on the XLA path and
|
|
198
|
+
the simulator) and raises `TypeError` naming the op and dtypes, so a future
|
|
199
|
+
wrapper without the entry check cannot hand a kernel an unsupported dtype.
|
|
200
|
+
The eager-handle fast path (`_native_call`, and `_kmv_launch` for
|
|
201
|
+
`kernel_matmul`, whose kernels `kmv_self` / `kmv_cross` / `kmv_selfblk`
|
|
202
|
+
are now in the table as fp32-only) skips the guarded op body, so it checks
|
|
203
|
+
the table itself before the launch.
|
|
204
|
+
Affects every release with NKI kernels, through 0.13.0.
|
|
205
|
+
|
|
206
|
+
- **`spmm` with a 1-D `B` raised on the NKI path (#105).** Affected
|
|
207
|
+
0.2.0–0.13.0: under `set_backend("nki")` / `"auto"` on a Neuron host,
|
|
208
|
+
`spmm(A, b)` with a vector `b` failed in the NKI GEMM wrapper with
|
|
209
|
+
`ValueError: not enough values to unpack (expected 2, got 1)`, while the
|
|
210
|
+
pytorch backend returns `A @ b` of shape `(m,)`. The vector now goes to the
|
|
211
|
+
kernel as one column and the result is squeezed back. Matrix `B` is
|
|
212
|
+
unchanged.
|
|
213
|
+
|
|
214
|
+
- **`kernel_matmul` no longer hits the Neuron runtime's 30 s execution
|
|
215
|
+
timeout at n >= 1e6** (#100). One launch at n = 2^20, R = 33 takes about
|
|
216
|
+
40 s at LNC=2 and 80 s at LNC=1 on Trn2 and failed with `NRT status 5`.
|
|
217
|
+
Products above 6e10 kernel entries (`n * m`; the rate is flat in R, so
|
|
218
|
+
the budget is not weighted by d + R) now run as host-side row blocks of
|
|
219
|
+
X: the fewest launches the budget allows, split into equal blocks of a
|
|
220
|
+
multiple of 1024 rows (19 launches of 55296 rows at n = m = 2^20, about
|
|
221
|
+
2.2 s each at LNC=2 and 4.5 s at LNC=1), R kept whole. Large blocks keep
|
|
222
|
+
the fixed per-launch cost (~75 ms, staging Y) near 1% of the run; Y, V
|
|
223
|
+
and params are placed on the device once for all blocks. The ragged last
|
|
224
|
+
block is zero-padded (less than 1024 rows per block), so every launch has
|
|
225
|
+
one shape, one compile and one cached `wrap_nki` handle (now keyed per
|
|
226
|
+
kernel and shape). Blocks of the square operator use a new
|
|
227
|
+
`_kmv_selfblk_kernel` (custom op `trnsparse::kmv_selfblk`) that adds
|
|
228
|
+
`noise * V` for the block's rows in the same fused epilogue, so blocked
|
|
229
|
+
results are bit-identical to one launch. Below the budget nothing
|
|
230
|
+
changes. `TRNSPARSE_KMV_BLOCK_WORK` overrides the budget.
|
|
231
|
+
|
|
232
|
+
- **`cg_bsr` raised `UnboundLocalError` with `max_iter=0` or on a first-step
|
|
233
|
+
breakdown, and reported `iters=max_iter` on any breakdown** (#71, #86).
|
|
234
|
+
`r_norm` was only assigned inside the loop, so `max_iter=0`, `A p = 0`
|
|
235
|
+
(e.g. a zero matrix) or `p . A p = 0` at k=0 (an exact `x0` with `tol=0`)
|
|
236
|
+
raised. A later breakdown (`|p . A p| < 1e-30`, e.g. after exact
|
|
237
|
+
convergence with `tol=0`) returned `iters = max_iter` (500 or 1000 for a
|
|
238
|
+
1-2 step solve). `cg_bsr` now returns the number of steps actually taken
|
|
239
|
+
and the residual of the returned `x`; `max_iter=0` gives
|
|
240
|
+
`(x0, 0, ||b - A x0|| / ||b||)`. Solutions are unchanged. Affects 0.3.2
|
|
241
|
+
through 0.13.0.
|
|
242
|
+
- **`power_iteration_bsr` gave silently wrong gradients** (#96), as
|
|
243
|
+
`cg_bsr` did (#70). The norms were taken with `.item()`, so autograd
|
|
244
|
+
differentiated the iterations with frozen normalisation instead of the
|
|
245
|
+
eigenvector, and `v0` received a spurious gradient. The eigenvector now
|
|
246
|
+
differentiates as the exact unit eigenvector of `A` (implicit
|
|
247
|
+
differentiation of `A v = lam v`, `||v|| = 1`): backward solves a dense
|
|
248
|
+
bordered `(N+1) x (N+1)` system, so it costs O(N^3), and gives
|
|
249
|
+
`grad_A = -w v^T` on the stored blocks. `v0` gets no gradient, the
|
|
250
|
+
eigenvalue stays a Python float, and backward raises `NotImplementedError`
|
|
251
|
+
for complex `A`. Forward values are unchanged. Affects 0.3.2 through 0.13.0.
|
|
252
|
+
- **`from_scipy` downcast float64 and integer matrices to float32** (silent,
|
|
253
|
+
#69). Every real scipy matrix was stored as float32 (float64 rounded to
|
|
254
|
+
~3e-8 relative error; int64 exact only up to 2^24) and complex128 as
|
|
255
|
+
complex64, which contradicted the "zero-copy" description in
|
|
256
|
+
docs/migration_scipy.md. The values now keep the scipy dtype, and for CSR
|
|
257
|
+
input share memory with `sp_matrix.data`. Affects 0.1.1 through 0.13.0.
|
|
258
|
+
**Behaviour change:** float64 scipy input now gives a float64 matrix, so
|
|
259
|
+
mixing it with float32 vectors (`spmv(from_scipy(M64), x32)`) raises the
|
|
260
|
+
usual torch dtype-mismatch error; cast one side (`M.astype(np.float32)`).
|
|
261
|
+
docs/migration_scipy.md no longer refers to a nonexistent `.to_scipy()`.
|
|
262
|
+
- **`cg_bsr` gave silently wrong gradients** (#70). The CG step sizes were
|
|
263
|
+
taken with `.item()`, so autograd differentiated a frozen-coefficient
|
|
264
|
+
polynomial in `A` applied to `b`, not the solve: with `b` along an
|
|
265
|
+
eigenvector (one-step convergence) `b.grad` was ~20% off `A^{-1} g`, and
|
|
266
|
+
`A.blocks.grad` had the same problem. `cg_bsr` now differentiates as the
|
|
267
|
+
exact solve (implicit differentiation, like `torch.linalg.solve`):
|
|
268
|
+
backward runs a second CG solve `A lam = grad_x` with the same
|
|
269
|
+
`tol` / `max_iter` / `M`, giving `grad_b = lam` and
|
|
270
|
+
`grad_A = -lam x^H` on the stored blocks. `x0` and `M` no longer receive
|
|
271
|
+
gradients. Forward values are unchanged. Affects 0.3.2 through 0.13.0.
|
|
272
|
+
- **`cg_bsr_fused` / `power_iteration_bsr_fused` gave wrong results for
|
|
273
|
+
complex, integer and bool inputs** (silent, #85). Both pack A and the
|
|
274
|
+
vectors into real float tiles, so on every backend (including
|
|
275
|
+
`set_backend("pytorch")`) a complex A or b lost its imaginary part, and an
|
|
276
|
+
integer or bool b gave a truncated x of b's dtype. They (and
|
|
277
|
+
`prepare_cg_bsr`) now raise `TypeError` for a non-real-float `A.blocks`,
|
|
278
|
+
`b`, `x0` or `v0`, before any backend runs. Affects 0.11.0 through 0.13.0.
|
|
279
|
+
|
|
10
280
|
## [0.13.0] — 2026-11-02
|
|
11
281
|
|
|
12
282
|
Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
|
|
@@ -24,6 +24,7 @@ trnsparse/
|
|
|
24
24
|
│ ├── screening.py # schwarz_bounds, screen_quartets, density_screen
|
|
25
25
|
│ ├── iterative.py # cg_bsr, cg_bsr_fused, power_iteration_bsr(_fused), jacobi_preconditioner_bsr
|
|
26
26
|
│ ├── multicore.py # ShardedBSR, ShardedAttention (logical NeuronCores of one chip)
|
|
27
|
+
│ ├── kernel_matmul.py # kernel_matmul, KernelOperator: fused K(X, Y) @ V, K never formed (#93)
|
|
27
28
|
│ └── nki/
|
|
28
29
|
│ ├── __init__.py
|
|
29
30
|
│ ├── kernels.py # _bsr_spmm_kernel, _screened_spmm_kernel, attention kernels
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: trnsparse
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.14.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
|
|
@@ -114,6 +114,26 @@ kernel argument, and `tests/test_trace_cache_safety.py` enforces this. If you
|
|
|
114
114
|
write your own NKI kernels with a factory, set `NKI_ENABLE_TRACE_CACHE=0`
|
|
115
115
|
before importing `torch_neuronx`.
|
|
116
116
|
|
|
117
|
+
## Known issues in earlier releases
|
|
118
|
+
|
|
119
|
+
Silent wrong results fixed in the 2026-10-31 to 2026-11-02 releases. If you
|
|
120
|
+
use an affected version, upgrade. Details are in the [CHANGELOG](CHANGELOG.md).
|
|
121
|
+
|
|
122
|
+
| Bug | Affected | Fixed in |
|
|
123
|
+
|---|---|---|
|
|
124
|
+
| `block_sparse_attention_tiled` returned zero rows for a partial last block (PyTorch path) (#44) | 0.6.0–0.10.0 | 0.11.0 |
|
|
125
|
+
| `block_sparse_attention_tiled` ignored a custom `scale` on the NKI paths (#47) | 0.6.0–0.11.0 | 0.12.0 |
|
|
126
|
+
| `spmv_symmetric` ignored `uplo` and used both triangles (#52) | through 0.12.0 | 0.12.1 |
|
|
127
|
+
| `COOMatrix.to_dense` dropped duplicate entries instead of summing them (#56) | 0.1.1–0.12.1 | 0.13.0 |
|
|
128
|
+
| `from_scipy` dropped the imaginary part of complex matrices (#58) | 0.1.1–0.12.1 | 0.13.0 |
|
|
129
|
+
| Second derivatives of `block_sparse_attention_tiled` were wrong (#65) | 0.6.0–0.12.1 | 0.13.0 |
|
|
130
|
+
| `spmv` / `spmm` accepted a `y` / `C` that broadcast the output to a larger shape (#67) | 0.1.1–0.12.1 | 0.13.0 |
|
|
131
|
+
| `chebyshev_coeffs` / `chebyshev_bsr` were not the Chebyshev polynomial for K >= 2 (#73) | 0.4.3–0.12.1 | 0.13.0 |
|
|
132
|
+
| `bsr_diagonal` returned length m (zero-padded) for a tall matrix (#74) | 0.3.2–0.12.1 | 0.13.0 |
|
|
133
|
+
| `bsr_spmm` dropped the imaginary part of complex operands on the NKI backend (#78) | 0.8.0–0.12.1 | 0.13.0 |
|
|
134
|
+
| `spmv` / `spmm` returned float32 for integer operands on the device (#79) | through 0.12.1 (device CSR path) | 0.13.0 |
|
|
135
|
+
| `block_sparse_attention_tiled` accepted a mask smaller than `seq_len` on the NKI path (#82) | 0.10.0–0.12.1 | 0.13.0 |
|
|
136
|
+
|
|
117
137
|
## Usage
|
|
118
138
|
|
|
119
139
|
```python
|
|
@@ -79,6 +79,26 @@ kernel argument, and `tests/test_trace_cache_safety.py` enforces this. If you
|
|
|
79
79
|
write your own NKI kernels with a factory, set `NKI_ENABLE_TRACE_CACHE=0`
|
|
80
80
|
before importing `torch_neuronx`.
|
|
81
81
|
|
|
82
|
+
## Known issues in earlier releases
|
|
83
|
+
|
|
84
|
+
Silent wrong results fixed in the 2026-10-31 to 2026-11-02 releases. If you
|
|
85
|
+
use an affected version, upgrade. Details are in the [CHANGELOG](CHANGELOG.md).
|
|
86
|
+
|
|
87
|
+
| Bug | Affected | Fixed in |
|
|
88
|
+
|---|---|---|
|
|
89
|
+
| `block_sparse_attention_tiled` returned zero rows for a partial last block (PyTorch path) (#44) | 0.6.0–0.10.0 | 0.11.0 |
|
|
90
|
+
| `block_sparse_attention_tiled` ignored a custom `scale` on the NKI paths (#47) | 0.6.0–0.11.0 | 0.12.0 |
|
|
91
|
+
| `spmv_symmetric` ignored `uplo` and used both triangles (#52) | through 0.12.0 | 0.12.1 |
|
|
92
|
+
| `COOMatrix.to_dense` dropped duplicate entries instead of summing them (#56) | 0.1.1–0.12.1 | 0.13.0 |
|
|
93
|
+
| `from_scipy` dropped the imaginary part of complex matrices (#58) | 0.1.1–0.12.1 | 0.13.0 |
|
|
94
|
+
| Second derivatives of `block_sparse_attention_tiled` were wrong (#65) | 0.6.0–0.12.1 | 0.13.0 |
|
|
95
|
+
| `spmv` / `spmm` accepted a `y` / `C` that broadcast the output to a larger shape (#67) | 0.1.1–0.12.1 | 0.13.0 |
|
|
96
|
+
| `chebyshev_coeffs` / `chebyshev_bsr` were not the Chebyshev polynomial for K >= 2 (#73) | 0.4.3–0.12.1 | 0.13.0 |
|
|
97
|
+
| `bsr_diagonal` returned length m (zero-padded) for a tall matrix (#74) | 0.3.2–0.12.1 | 0.13.0 |
|
|
98
|
+
| `bsr_spmm` dropped the imaginary part of complex operands on the NKI backend (#78) | 0.8.0–0.12.1 | 0.13.0 |
|
|
99
|
+
| `spmv` / `spmm` returned float32 for integer operands on the device (#79) | through 0.12.1 (device CSR path) | 0.13.0 |
|
|
100
|
+
| `block_sparse_attention_tiled` accepted a mask smaller than `seq_len` on the NKI path (#82) | 0.10.0–0.12.1 | 0.13.0 |
|
|
101
|
+
|
|
82
102
|
## Usage
|
|
83
103
|
|
|
84
104
|
```python
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Fused kernel-matrix product K(X, X) @ V (#93): kernel entries per second.
|
|
2
|
+
|
|
3
|
+
Modes (rates in kernel entries/s = n * m / time; one application):
|
|
4
|
+
|
|
5
|
+
- nki: `KernelOperator` on the device (one fused launch, K never formed)
|
|
6
|
+
- aten: the same augmented-GEMM algorithm in aten ops on the device
|
|
7
|
+
(blocked addmm + exp + matmul, the PyTorch path of kernel_matmul)
|
|
8
|
+
- cpu2: the aten algorithm on the host CPU, 2 threads (the suite's
|
|
9
|
+
same-box convention, trnsci/trnsci#35)
|
|
10
|
+
- cpuall: the same with all host vCPUs
|
|
11
|
+
|
|
12
|
+
CPU modes time a block of `--cpu-rows` output rows against all n points
|
|
13
|
+
(the rate is per entry, so this measures the same thing in bounded time);
|
|
14
|
+
device modes apply the full operator. Each device result is checked
|
|
15
|
+
against float64 on the host on sampled rows.
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
python benchmarks/bench_kernel_matmul_trn2.py --device \
|
|
19
|
+
[--sizes 131072,262144,524288,1048576] [--rhs 1,16,64,128] \
|
|
20
|
+
[--modes nki,aten,cpu2,cpuall] [--kernel rbf] [--json out.json]
|
|
21
|
+
python benchmarks/bench_kernel_matmul_trn2.py --compare A.pt B.pt # bitwise LNC check
|
|
22
|
+
|
|
23
|
+
`--dump DIR` saves every nki result, so two checkouts (or LNC settings) can
|
|
24
|
+
be compared with `--compare`. The package version and the
|
|
25
|
+
`TRNSPARSE_KMV_GROUP` in effect are printed with the header.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import argparse
|
|
31
|
+
import json
|
|
32
|
+
import os
|
|
33
|
+
import statistics
|
|
34
|
+
import sys
|
|
35
|
+
import time
|
|
36
|
+
|
|
37
|
+
import torch
|
|
38
|
+
|
|
39
|
+
import trnsparse
|
|
40
|
+
from trnsparse.kernel_matmul import _torch_kernel_matmul
|
|
41
|
+
|
|
42
|
+
DEV = "neuron"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _sync(device):
|
|
46
|
+
if device == DEV and hasattr(torch, "neuron"):
|
|
47
|
+
torch.neuron.synchronize()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _time(fn, device, warmup, reps):
|
|
51
|
+
for _ in range(warmup):
|
|
52
|
+
fn()
|
|
53
|
+
_sync(device)
|
|
54
|
+
ts = []
|
|
55
|
+
for _ in range(reps):
|
|
56
|
+
t0 = time.perf_counter()
|
|
57
|
+
fn()
|
|
58
|
+
_sync(device)
|
|
59
|
+
ts.append(time.perf_counter() - t0)
|
|
60
|
+
return statistics.median(ts)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _check(out, X, V, kernel, ell, noise, rows=256):
|
|
64
|
+
idx = torch.linspace(0, X.shape[0] - 1, rows).long()
|
|
65
|
+
ref = (
|
|
66
|
+
trnsparse.kernel_matmul_reference(X[idx], X, V, kernel, ell, 1.0) + noise * V[idx].double()
|
|
67
|
+
)
|
|
68
|
+
got = out.cpu()[idx].double()
|
|
69
|
+
return float((got - ref).abs().max() / ref.abs().max())
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def main():
|
|
73
|
+
ap = argparse.ArgumentParser()
|
|
74
|
+
ap.add_argument("--device", action="store_true", help="run the nki and aten modes on neuron")
|
|
75
|
+
ap.add_argument("--sizes", default="131072,262144,524288,1048576")
|
|
76
|
+
ap.add_argument("--rhs", default="1,16,64,128")
|
|
77
|
+
ap.add_argument("--modes", default="nki,aten,cpu2,cpuall")
|
|
78
|
+
ap.add_argument("--kernel", default="rbf")
|
|
79
|
+
ap.add_argument("--d", type=int, default=3)
|
|
80
|
+
ap.add_argument("--cpu-rows", type=int, default=2048)
|
|
81
|
+
ap.add_argument(
|
|
82
|
+
"--aten-max", type=int, default=262144, help="largest n for the aten mode (it is slow)"
|
|
83
|
+
)
|
|
84
|
+
ap.add_argument("--reps", type=int, default=3)
|
|
85
|
+
ap.add_argument("--json", default=None)
|
|
86
|
+
ap.add_argument("--compare", nargs=2, metavar=("A", "B"))
|
|
87
|
+
ap.add_argument(
|
|
88
|
+
"--dump", default=None, help="save each nki result to DIR/kmv_n{n}_R{R}.pt (for --compare)"
|
|
89
|
+
)
|
|
90
|
+
args = ap.parse_args()
|
|
91
|
+
|
|
92
|
+
if args.compare:
|
|
93
|
+
a, b = (torch.load(p) for p in args.compare)
|
|
94
|
+
same = torch.equal(a, b)
|
|
95
|
+
print(f"bitwise equal: {same}; max |diff| = {float((a - b).abs().max()):.3e}")
|
|
96
|
+
sys.exit(0 if same else 1)
|
|
97
|
+
|
|
98
|
+
modes = [m for m in args.modes.split(",") if m]
|
|
99
|
+
if not args.device:
|
|
100
|
+
modes = [m for m in modes if m.startswith("cpu")]
|
|
101
|
+
sizes = [int(s) for s in args.sizes.split(",")]
|
|
102
|
+
rhs = [int(r) for r in args.rhs.split(",")]
|
|
103
|
+
ell, noise = 0.05, 1e-4
|
|
104
|
+
rows = []
|
|
105
|
+
print(
|
|
106
|
+
f"kernel={args.kernel} d={args.d} lnc={os.environ.get('NEURON_LOGICAL_NC_CONFIG', 'default')}"
|
|
107
|
+
f" trnsparse={trnsparse.__file__}"
|
|
108
|
+
f" group={os.environ.get('TRNSPARSE_KMV_GROUP', 'auto')}"
|
|
109
|
+
)
|
|
110
|
+
print(f"{'n':>9} {'R':>4} {'mode':>7} {'time_s':>10} {'entries/s':>11} {'relerr':>9}")
|
|
111
|
+
for n in sizes:
|
|
112
|
+
g = torch.Generator().manual_seed(n)
|
|
113
|
+
X = torch.rand(n, args.d, generator=g)
|
|
114
|
+
for R in rhs:
|
|
115
|
+
V = torch.randn(n, R, generator=g)
|
|
116
|
+
for mode in modes:
|
|
117
|
+
if mode == "aten" and n > args.aten_max:
|
|
118
|
+
continue
|
|
119
|
+
rec = {"n": n, "R": R, "mode": mode, "kernel": args.kernel, "d": args.d}
|
|
120
|
+
if mode == "nki":
|
|
121
|
+
trnsparse.set_backend("nki")
|
|
122
|
+
op = trnsparse.KernelOperator(X, args.kernel, ell, 1.0, noise=noise, device=DEV)
|
|
123
|
+
Vd = V.to(DEV)
|
|
124
|
+
t_cold = time.perf_counter()
|
|
125
|
+
op(Vd)
|
|
126
|
+
_sync(DEV)
|
|
127
|
+
rec["first_call_s"] = time.perf_counter() - t_cold
|
|
128
|
+
t = _time(lambda op=op, Vd=Vd: op(Vd), DEV, 1, args.reps)
|
|
129
|
+
res = op(Vd).cpu()
|
|
130
|
+
rec["relerr"] = _check(res, X, V, args.kernel, ell, noise)
|
|
131
|
+
if args.dump:
|
|
132
|
+
os.makedirs(args.dump, exist_ok=True)
|
|
133
|
+
torch.save(res, os.path.join(args.dump, f"kmv_n{n}_R{R}.pt"))
|
|
134
|
+
entries = n * n
|
|
135
|
+
elif mode == "aten":
|
|
136
|
+
trnsparse.set_backend("pytorch")
|
|
137
|
+
op = trnsparse.KernelOperator(X, args.kernel, ell, 1.0, noise=noise, device=DEV)
|
|
138
|
+
Vd = V.to(DEV)
|
|
139
|
+
t = _time(lambda op=op, Vd=Vd: op(Vd), DEV, 1, args.reps)
|
|
140
|
+
rec["relerr"] = _check(op(Vd), X, V, args.kernel, ell, noise)
|
|
141
|
+
entries = n * n
|
|
142
|
+
else:
|
|
143
|
+
threads = 2 if mode == "cpu2" else os.cpu_count()
|
|
144
|
+
torch.set_num_threads(threads)
|
|
145
|
+
rec["threads"] = threads
|
|
146
|
+
trnsparse.set_backend("pytorch")
|
|
147
|
+
op = trnsparse.KernelOperator(X, args.kernel, ell, 1.0, noise=noise)
|
|
148
|
+
k = min(args.cpu_rows, n)
|
|
149
|
+
Xa = op.X[:k].contiguous()
|
|
150
|
+
t = _time(
|
|
151
|
+
lambda Xa=Xa, op=op, V=V: _torch_kernel_matmul(
|
|
152
|
+
Xa, op.X, V, op.kind, op._a, 1.0, 0.0
|
|
153
|
+
),
|
|
154
|
+
"cpu",
|
|
155
|
+
1,
|
|
156
|
+
args.reps,
|
|
157
|
+
)
|
|
158
|
+
entries = k * n
|
|
159
|
+
rec["rows_timed"] = k
|
|
160
|
+
rec["time_s"] = t
|
|
161
|
+
rec["entries_per_s"] = entries / t
|
|
162
|
+
rec["full_apply_s"] = n * n / rec["entries_per_s"]
|
|
163
|
+
rows.append(rec)
|
|
164
|
+
print(
|
|
165
|
+
f"{n:>9} {R:>4} {mode:>7} {t:>10.4f} {rec['entries_per_s']:>11.3e} "
|
|
166
|
+
f"{rec.get('relerr', float('nan')):>9.2e}",
|
|
167
|
+
flush=True,
|
|
168
|
+
)
|
|
169
|
+
if args.json:
|
|
170
|
+
with open(args.json, "w") as f:
|
|
171
|
+
json.dump(rows, f, indent=1)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
if __name__ == "__main__":
|
|
175
|
+
main()
|
|
@@ -46,6 +46,68 @@
|
|
|
46
46
|
`jacobi_preconditioner_bsr`, `bsr_diagonal`. See
|
|
47
47
|
[Iterative solvers](iterative_solvers.md).
|
|
48
48
|
|
|
49
|
+
## Kernel-matrix products (`kernel_matmul`, #93)
|
|
50
|
+
|
|
51
|
+
`K(X, Y) @ V` without forming `K`, for stationary kernels of the distance:
|
|
52
|
+
`"rbf"`, `"matern12"`, `"matern32"`, `"matern52"` (`trnsparse.KERNELS`).
|
|
53
|
+
The operator of matrix-free Gaussian-process regression and kernel ridge
|
|
54
|
+
regression.
|
|
55
|
+
|
|
56
|
+
- `kernel_matmul(X, Y, V, kernel="rbf", lengthscale=1.0, outputscale=1.0, noise=0.0)`
|
|
57
|
+
— `Y=None` gives `(K(X, X) + noise I) @ V`. `lengthscale` is a float or a
|
|
58
|
+
`(d,)` tensor (per-dimension lengthscales). `V` is `(m,)` or `(m, R)`.
|
|
59
|
+
- `KernelOperator(X, kernel, lengthscale, outputscale, noise, device=None)` —
|
|
60
|
+
prepares `X` once (centred, rescaled, fp32 on the device) for repeated
|
|
61
|
+
applications: `op(V)`, `op.cross(Y, W)` = `K(Y, X) @ W`, `op.diag()`,
|
|
62
|
+
`op.rows(idx)` (rows of `K` for pivoted-Cholesky preconditioners).
|
|
63
|
+
- `kernel_matmul_reference(...)` — dense float64 `torch.cdist` reference.
|
|
64
|
+
|
|
65
|
+
NKI path: one launch per application, or one per row block of `X` when the
|
|
66
|
+
product exceeds 6e10 kernel entries `n * m` (#100): the Neuron runtime
|
|
67
|
+
stops a launch after 30 s, and a single launch at n = 2^20 takes 40-80 s on
|
|
68
|
+
Trn2. The rate is flat in R, so the budget counts entries only: about 2.2 s
|
|
69
|
+
per launch at LNC=2, 4.5 s at LNC=1. The product runs in the fewest
|
|
70
|
+
launches the budget allows, as equal blocks of a multiple of 1024 rows (19
|
|
71
|
+
blocks of 55296 rows at n = m = 2^20), the last one zero-padded to the same
|
|
72
|
+
shape, so every block reuses one compile and one cached handle. Rows are
|
|
73
|
+
independent, so the blocked result is bit-identical to a single
|
|
74
|
+
launch.
|
|
75
|
+
|
|
76
|
+
Multi-core (#102): with several visible logical cores
|
|
77
|
+
(`NEURON_RT_VISIBLE_CORES=0-3` on trn2.3xlarge at LNC=2) a row-blocked
|
|
78
|
+
product spreads its blocks round-robin over the cores. The block count is
|
|
79
|
+
rounded up to a multiple of the core count (20 blocks of 53248 rows on 4
|
|
80
|
+
cores at n = m = 2^20), so every core gets the same number. Each core gets
|
|
81
|
+
its own copy of `Y`, `V` and the parameters, staged through the host once
|
|
82
|
+
per product, before any kernel is queued. All launches are issued from the
|
|
83
|
+
calling thread and run asynchronously, and the blocks are gathered in row
|
|
84
|
+
order on the operands' device. The result is bit-identical to one core.
|
|
85
|
+
`TRNSPARSE_KMV_CORES` is `auto` (the default: every visible core when
|
|
86
|
+
`n * m` exceeds the block budget, one core below it), `all`, or a number
|
|
87
|
+
of cores (`1` turns it off). `TRNSPARSE_KMV_THREADS=1` issues each core's
|
|
88
|
+
blocks from its own worker thread instead, after the first block of every
|
|
89
|
+
core has been launched (and the handle traced) on the calling thread.
|
|
90
|
+
|
|
91
|
+
Per 128 x 512 tile the squared
|
|
92
|
+
distances are one TensorEngine matmul on augmented coordinates
|
|
93
|
+
`[x, |x|^2, 1] . [-2y, 1, |y|^2]` into PSUM, the kernel function runs on
|
|
94
|
+
ScalarE reading PSUM (`exp(a D + log s)` for RBF), and the product with `V`
|
|
95
|
+
accumulates on the TensorEngine. Lengthscale, outputscale and noise are a
|
|
96
|
+
tensor argument, so new hyperparameters do not recompile. Output rows are
|
|
97
|
+
split over both physical cores (LNC=2); results are bit-identical at LNC=1
|
|
98
|
+
and LNC=2 by construction (same Y-tile order). `d <= 126`.
|
|
99
|
+
|
|
100
|
+
Precision: fp32, with inputs centred on the host. The distance expansion
|
|
101
|
+
cancels for near-coincident points (relative error about
|
|
102
|
+
`u (|x|^2 + |y|^2) / |x - y|^2`); the smooth kernels see that at first order,
|
|
103
|
+
Matern-1/2 (a cusp at 0) as `sqrt(u |x|^2) / l`. float64 follows the suite
|
|
104
|
+
policy: `auto` computes in torch float64, explicit `nki` casts with a
|
|
105
|
+
warning, `TRNSPARSE_REQUIRE_NKI` raises. Env: `TRNSPARSE_KMV_GROUP` (Y tiles
|
|
106
|
+
per loop body, 1 to 32; default `kmv_group(m)`: about `sqrt(m / 128)`, from 4
|
|
107
|
+
to 16, which also minimises the fp32 summation error), `TRNSPARSE_KMV_BLOCK_WORK` (kernel entries
|
|
108
|
+
per launch, default `6e10`), `TRNSPARSE_NKI_EAGER_HANDLE=0` (custom op instead
|
|
109
|
+
of the cached `wrap_nki` handle).
|
|
110
|
+
|
|
49
111
|
## Screening
|
|
50
112
|
|
|
51
113
|
- `schwarz_bounds(shell_pair_integrals)` — Cauchy-Schwarz bounds $Q_{pq} = \sqrt{(pq|pq)}$
|