trnsparse 0.13.0__tar.gz → 0.15.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.
Files changed (92) hide show
  1. {trnsparse-0.13.0 → trnsparse-0.15.0}/CHANGELOG.md +303 -0
  2. {trnsparse-0.13.0 → trnsparse-0.15.0}/CLAUDE.md +1 -0
  3. {trnsparse-0.13.0 → trnsparse-0.15.0}/PKG-INFO +21 -1
  4. {trnsparse-0.13.0 → trnsparse-0.15.0}/README.md +20 -0
  5. trnsparse-0.15.0/benchmarks/bench_kernel_matmul_trn2.py +175 -0
  6. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/api.md +62 -0
  7. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/architecture.md +67 -0
  8. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/installation.md +11 -0
  9. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/iterative_solvers.md +5 -1
  10. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/migration_scipy.md +6 -6
  11. {trnsparse-0.13.0 → trnsparse-0.15.0}/pyproject.toml +1 -1
  12. trnsparse-0.15.0/scripts/bench_eager_handle.py +144 -0
  13. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/conftest.py +28 -1
  14. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_conformance.py +86 -38
  15. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_formats.py +29 -3
  16. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_iterative.py +257 -0
  17. trnsparse-0.15.0/tests/test_kernel_dtype_guard.py +955 -0
  18. trnsparse-0.15.0/tests/test_kernel_matmul.py +604 -0
  19. trnsparse-0.15.0/tests/test_kernel_matmul_neuron.py +282 -0
  20. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_native_dispatch.py +361 -3
  21. trnsparse-0.15.0/tests/test_nki_kernel_matmul.py +370 -0
  22. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_native.py +124 -0
  23. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_tail_audit.py +3 -2
  24. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_ops.py +46 -0
  25. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/__init__.py +6 -1
  26. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/formats.py +16 -5
  27. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/iterative.py +252 -32
  28. trnsparse-0.15.0/trnsparse/kernel_matmul.py +399 -0
  29. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/multicore.py +4 -6
  30. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/nki/_native.py +103 -0
  31. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/nki/dispatch.py +865 -54
  32. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/nki/kernels.py +435 -0
  33. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/ops.py +21 -2
  34. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse.egg-info/PKG-INFO +21 -1
  35. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse.egg-info/SOURCES.txt +7 -0
  36. {trnsparse-0.13.0 → trnsparse-0.15.0}/.github/workflows/ci.yml +0 -0
  37. {trnsparse-0.13.0 → trnsparse-0.15.0}/.github/workflows/notify-umbrella.yml +0 -0
  38. {trnsparse-0.13.0 → trnsparse-0.15.0}/.github/workflows/publish.yml +0 -0
  39. {trnsparse-0.13.0 → trnsparse-0.15.0}/.gitignore +0 -0
  40. {trnsparse-0.13.0 → trnsparse-0.15.0}/.pre-commit-config.yaml +0 -0
  41. {trnsparse-0.13.0 → trnsparse-0.15.0}/CODE_OF_CONDUCT.md +0 -0
  42. {trnsparse-0.13.0 → trnsparse-0.15.0}/CONTRIBUTING.md +0 -0
  43. {trnsparse-0.13.0 → trnsparse-0.15.0}/LICENSE +0 -0
  44. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_bsr_spmm.py +0 -0
  45. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_cg_fused_trn2.py +0 -0
  46. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_iterative.py +0 -0
  47. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_multicore_trn2.py +0 -0
  48. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_multiproc_trn2.py +0 -0
  49. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_native_trn2.py +0 -0
  50. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_power_fused_trn2.py +0 -0
  51. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_screened_tiles_trn2.py +0 -0
  52. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_screening.py +0 -0
  53. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_spmm.py +0 -0
  54. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/bench_spmv.py +0 -0
  55. {trnsparse-0.13.0 → trnsparse-0.15.0}/benchmarks/conftest.py +0 -0
  56. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/aws_setup.md +0 -0
  57. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/benchmarks.md +0 -0
  58. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/index.md +0 -0
  59. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/quickstart.md +0 -0
  60. {trnsparse-0.13.0 → trnsparse-0.15.0}/docs/sparse_attention.md +0 -0
  61. {trnsparse-0.13.0 → trnsparse-0.15.0}/examples/block_sparse_attention.py +0 -0
  62. {trnsparse-0.13.0 → trnsparse-0.15.0}/examples/sparse_fock.py +0 -0
  63. {trnsparse-0.13.0 → trnsparse-0.15.0}/infra/terraform/.terraform.lock.hcl +0 -0
  64. {trnsparse-0.13.0 → trnsparse-0.15.0}/infra/terraform/README.md +0 -0
  65. {trnsparse-0.13.0 → trnsparse-0.15.0}/infra/terraform/main.tf +0 -0
  66. {trnsparse-0.13.0 → trnsparse-0.15.0}/mkdocs.yml +0 -0
  67. {trnsparse-0.13.0 → trnsparse-0.15.0}/scripts/bench_to_md.py +0 -0
  68. {trnsparse-0.13.0 → trnsparse-0.15.0}/scripts/run_benchmarks.sh +0 -0
  69. {trnsparse-0.13.0 → trnsparse-0.15.0}/scripts/run_neuron_tests.sh +0 -0
  70. {trnsparse-0.13.0 → trnsparse-0.15.0}/scripts/run_simulator_tests.sh +0 -0
  71. {trnsparse-0.13.0 → trnsparse-0.15.0}/setup.cfg +0 -0
  72. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_attention.py +0 -0
  73. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_attn_gather.py +0 -0
  74. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_bsr.py +0 -0
  75. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_core_split.py +0 -0
  76. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_examples.py +0 -0
  77. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_multicore.py +0 -0
  78. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_attn.py +0 -0
  79. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_bsr.py +0 -0
  80. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_cg_fused.py +0 -0
  81. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_compile.py +0 -0
  82. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_screened_spmm.py +0 -0
  83. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_sim.py +0 -0
  84. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_nki_spmm.py +0 -0
  85. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_screening.py +0 -0
  86. {trnsparse-0.13.0 → trnsparse-0.15.0}/tests/test_trace_cache_safety.py +0 -0
  87. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/nki/__init__.py +0 -0
  88. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/nki/_native_attn.py +0 -0
  89. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse/screening.py +0 -0
  90. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse.egg-info/dependency_links.txt +0 -0
  91. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse.egg-info/requires.txt +0 -0
  92. {trnsparse-0.13.0 → trnsparse-0.15.0}/trnsparse.egg-info/top_level.txt +0 -0
@@ -7,6 +7,309 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.15.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` auto loop body up to 32 Y tiles at m >= 131072 (#108, #111): rbf R = 128 runs 18% faster, and fp32 error drops from 7.0e-7 to 5.3e-7 at m = 524288. A 2-slot SBUF scratch ring keeps the Matern kernels on NKI allocation at 32 tiles.
15
+
16
+ ### Performance
17
+
18
+ - **`kernel_matmul`: the default loop body grows to 32 Y tiles at
19
+ m >= 131072** (`_KMV_AUTO_GROUP_MAX` 16 -> 32, #108). Trn2, one logical
20
+ core, n = m = 131072 and 524288, `rbf`: R = 128 goes from 4.3e10 to
21
+ 5.1e10 kernel entries/s (+18%, also at LNC=1), R = 768 +19%, R = 33
22
+ +15% to +55% (it varies between runs), R = 1 +2%. Matern-5/2 gains
23
+ 12%, Matern-3/2 4-6%; Matern-1/2 loses 3% at R = 1 and gains 4% at
24
+ R = 128 (both groups with the scratch ring below). The fp32 error falls
25
+ with it, as the g + m/(128 g) model predicts: 7.0e-7 -> 5.3e-7 against
26
+ float64 at m = 524288 (summation-bound case, positive V, lengthscale
27
+ 0.5). `kmv_group(m)` is still about sqrt(m / 128); smaller m and
28
+ `TRNSPARSE_KMV_GROUP` are unchanged.
29
+ - **`kernel_matmul`: Matern intermediates share a 2-slot SBUF ring per
30
+ loop body** (#108). NKI allocations live for their enclosing region, so
31
+ the per-Y-tile temporaries of the Matern kernels (one to three 2 KiB
32
+ tiles each) piled up across a body. Bodies of 24 Matern-5/2 tiles (20 at
33
+ R >= 384), 32 Matern-3/2 tiles (24 at R >= 512) and 32 Matern-1/2 tiles
34
+ at R >= 512 overflowed SBUF and silently fell back to neuronx-cc
35
+ allocation (correct, but without NKI scheduling). Now every kernel keeps
36
+ NKI's allocation at 32 tiles for every R checked (1 to 1500, rbf to
37
+ 3000) at LNC=1 and LNC=2. The
38
+ instructions are the same, so the results are bit-identical at a given
39
+ group, and at group 16 Matern-1/2 and Matern-3/2 run 23% and 14% faster
40
+ (2.83e10 -> 3.49e10 and 2.78e10 -> 3.16e10 entries/s at n = 131072).
41
+
42
+ ## [0.14.0] — 2026-11-04
43
+
44
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
45
+
46
+ 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.
47
+
48
+ ### Performance
49
+
50
+ - **Eager NKI kernel calls skip the per-call handle rebuild and the custom-op
51
+ layer (same fix as trnblas#92).** On the native path a `trnsparse::`
52
+ custom-op call cost about 0.1 ms of host time before the kernel was queued,
53
+ against 0.016 ms for aten. Most of it went to nki's `Kernel.__call__`,
54
+ which rebuilds the torch handle on every call, plus the `torch.library`
55
+ layer. `dispatch._run` / `_launch` and the direct keyed-op calls (keyed
56
+ `bsr_spmm`, attention forward and backward, fused CG and power iteration,
57
+ `ShardedBSR` / `ShardedAttention`) now call a `torch_neuronx.wrap_nki`
58
+ handle built once per kernel, with the op body's `int()` / `tuple()` /
59
+ `float()` conversions of the static arguments. On trn2 (LNC=2), a
60
+ 256x256x128 `spmm_dense` launch drops from 0.126 to 0.036 ms of issue time
61
+ (e2e 0.201 to 0.124 ms), a keyed `bsr_spmm` from 0.255 to 0.157 ms e2e, and
62
+ `cg_bsr_fused` n=256 from 1.36 to 1.19 ms. Results are bit-identical.
63
+ `torch.compile`, requires-grad, int64 and tensor-subclass inputs, and the
64
+ composite `bsr_attn` / `bsr_attn_bwd` ops keep the custom op, as does
65
+ the screened-tile op (`screened_tiles_keyed`, #61) for now. This is the
66
+ same handle cache that `kernel_matmul` launches use (keyed there by
67
+ operand shapes, one handle shared by every row block and core), so
68
+ `TRNSPARSE_NKI_EAGER_HANDLE=0` turns both off;
69
+ `scripts/bench_eager_handle.py` measures it.
70
+
71
+ ### Added
72
+
73
+ - **`kernel_matmul` / `KernelOperator`: fused kernel-matrix product
74
+ K(X, Y) @ V that never forms K** (#93, for trnsci/trnsci#109). RBF and
75
+ Matern-1/2, 3/2, 5/2; per-dimension lengthscales; `noise * V` on the
76
+ square operator. One NKI launch per application: squared distances as a
77
+ TensorEngine matmul on augmented coordinates into PSUM, the kernel
78
+ function on ScalarE straight from PSUM, the product with V on the
79
+ TensorEngine. Coordinates are augmented and transposed on chip
80
+ (`nl.load` + `nisa.nc_transpose`); tile loops are rolled
81
+ (`nl.fori_loop`), so trace and compile time do not grow with n; ragged
82
+ n, m and R are handled in the kernel. Both physical cores at LNC=2 with
83
+ the same control flow on each, and bit-identical results at LNC=1 and
84
+ LNC=2. Hyperparameters are a tensor argument (aws-neuron-sdk#1454).
85
+ Eager launches use a cached `torch_neuronx.wrap_nki` handle (the
86
+ trnblas#92 pattern). CPU tests: PyTorch path against float64
87
+ `torch.cdist`; `nki.simulate` at LNC=1/2, MLIR verify and (with
88
+ neuronx-cc) NEFF compile with NKI allocation at LNC=1/2.
89
+ `benchmarks/bench_kernel_matmul_trn2.py` measures kernel entries/s
90
+ against aten on the device and the host CPU at 2 threads and all vCPUs.
91
+ `tile_mask` is reserved and raises for now.
92
+ - **`kernel_matmul`: row blocks spread across all visible logical
93
+ NeuronCores** (#102). On trn2.3xlarge at LNC=2 (`neuron:0..3`, with
94
+ `NEURON_RT_VISIBLE_CORES=0-3`) a row-blocked product issues its blocks
95
+ round-robin over the cores. The block count rounds up to a multiple of
96
+ the core count (`kmv_block_rows(..., parts=k)`; 20 blocks of 53248 rows
97
+ on 4 cores at n = m = 2^20), so each core gets the same number. Y, V and
98
+ params are staged through the host once and placed on each core before
99
+ any kernel is queued. Launches are issued asynchronously from the calling
100
+ thread (NKI tracing stays on one thread, aws-neuron-sdk#1453) and
101
+ gathered in row order on the operands' device, bit-identical to one
102
+ core. `TRNSPARSE_KMV_CORES`: `auto` (default: every visible core when
103
+ `n * m` exceeds the 6e10-entry block budget, else one), `all`, or an
104
+ int. `TRNSPARSE_KMV_THREADS=1` is a fallback that issues each core's
105
+ blocks from a worker thread, after the first block per core has been
106
+ launched on the calling thread. Target: n = 2^20 from about 42 s to about
107
+ 11 s per apply on 4 cores. CPU stand-in tests cover block-to-core
108
+ assignment, per-core placement and the gather (bitwise against single
109
+ core). A neuron test compares multi-core with single-core bitwise and
110
+ skips below 2 visible cores.
111
+
112
+ ### Changed
113
+
114
+ - **`kernel_matmul`: about 70% fewer instructions per launch** (#103). The
115
+ Trn2 profile on #93 showed the kernel issue-bound: 41% of a launch with
116
+ no engine active. The @V product now takes V's tile as the stationary
117
+ operand and the kernel tile as the moving one. That makes one
118
+ `nc_matmul` per 128 columns of V over all 512 X points of a tile, where
119
+ it was four (one per 128-row chunk, kernel tile stationary). The
120
+ accumulator, out^T, is now one PSUM bank per 128 columns, against four,
121
+ and is transposed back (`nisa.nc_transpose`) once per output block.
122
+ The freed PSUM holds a ring of distance tiles, so a loop body is no
123
+ longer capped at 4 Y tiles. Each body loads its V rows in one DMA,
124
+ against one per Y tile. The body size now defaults to `kmv_group(m)`:
125
+ about sqrt(m / 128) Y tiles, from 4 to 16 (`TRNSPARSE_KMV_GROUP` still
126
+ overrides it, 1 to 32).
127
+ - Instructions per launch, n = 131072, LNC=2, both physical cores,
128
+ counted from the compiled NEFF: **11.5M before, 3.5M now** at group
129
+ 16; 6.2M with the old body of 4. That is 44 against 13 instructions per
130
+ 128 x 512 tile per core.
131
+ - **Summation order:** with a body of 4 Y tiles (m < 3200 by default,
132
+ or `TRNSPARSE_KMV_GROUP=4`) the summation order matches 0.13.0.
133
+ That holds in the simulator, with its matmul summed in contraction
134
+ order like the TensorEngine. On Trn2 hardware it does not: group 4
135
+ differs from 0.13.0 by up to about 1.5e-5, with unchanged error against
136
+ float64 (#107). Larger bodies change where the PSUM partial sums are
137
+ split, so the bits change.
138
+ - **Error against float64** goes from about g + m/(128 g) fp32 roundings
139
+ to its minimum: at m = 131072 the max relative error drops from
140
+ 9.0e-7 to 5.2e-7 (simulator, rbf and Matern-5/2, R = 1 and 33).
141
+ - Bit-identical at LNC=1 and LNC=2, across row blocks and across cores,
142
+ as before: the body size depends on m only.
143
+ - The simulator tests now run `nc_matmul` as a sum in contraction order
144
+ (numpy's BLAS rounds a column differently with the moving operand's
145
+ width). So the LNC=1 against LNC=2 and row-blocked checks are bitwise
146
+ at every d and every ragged tail. The ragged tails were tolerance-only
147
+ before.
148
+ - `benchmarks/bench_kernel_matmul_trn2.py --dump DIR` saves the results,
149
+ to compare two checkouts with `--compare`.
150
+ - **float64 under `auto` now computes in torch at float64 accuracy
151
+ (previously cast to fp32 on the NKI path)** — the trnsci suite fp64
152
+ policy (#84). Trainium computes float64 at fp32 precision, so no kernel
153
+ can give a float64-accurate result. For `spmm`, `bsr_spmm`,
154
+ `screened_spmm`, `block_sparse_attention_tiled` (forward and backward),
155
+ `cg_bsr` (through `bsr_spmm`), `cg_bsr_fused` and
156
+ `power_iteration_bsr_fused`, a float64 value operand (and complex128 in
157
+ `bsr_spmm`, whose complex path runs as real kernel launches):
158
+ - under `set_backend("auto")` (the default) takes the PyTorch path that
159
+ `set_backend("pytorch")` takes, at float64 accuracy, and no kernel runs
160
+ (the fused solvers take their host path);
161
+ - under an explicit `set_backend("nki")` is cast to fp32 (complex64) for
162
+ the kernel as before, now with a one-time `UserWarning` per op saying
163
+ precision is reduced to fp32;
164
+ - under `TRNSPARSE_REQUIRE_NKI=1` raises `NotImplementedError` (on either
165
+ backend; this takes precedence over the explicit-nki cast).
166
+
167
+ The result dtype always equals the pytorch backend's for the same inputs,
168
+ including bf16 / fp16 and mixed-dtype promotion; a kernel result computed
169
+ in fp32 is cast to that dtype. Callers of 0.2.0 through 0.13.0 who
170
+ relied on float64 inputs running on the kernels under `auto` now get
171
+ torch (more precise; on the host or device aten instead of the kernel):
172
+ pass float32 operands, or select `set_backend("nki")`, to keep the
173
+ kernel. float64 validation runs under REQUIRE_NKI must pass fp32 operands
174
+ (or call the autograd Functions directly, as the hardware gradchecks do).
175
+ Lands in 0.14.0. `screened_spmm` decides on `A` and `B`; a float64 bound
176
+ vector `diag_integrals` alone does not change the route. See
177
+ docs/architecture.md, "Precision and dtypes".
178
+
179
+ **float64 on the `neuron` device runs on the host under `auto`.** Device
180
+ aten computes float64 at fp32 precision as well (measured on Trn2), so
181
+ the torch path alone does not give float64 accuracy for device-resident
182
+ data. When a float64 / complex128 operand of `spmv`, `spmm`,
183
+ `spmv_symmetric`, `bsr_spmm`, `screened_spmm`,
184
+ `block_sparse_attention_tiled` (forward and backward), `cg_bsr`,
185
+ `chebyshev_bsr`, `richardson_bsr`, `power_iteration_bsr` or the
186
+ `jacobi_preconditioner_bsr` preconditioner lives on a `neuron` device
187
+ (dense, or a CSR / COO / BSR matrix's values), the operands are copied to
188
+ the host, host torch computes at float64, and the result returns to the
189
+ dense operand's device in float64, with one `UserWarning` per op ("float64
190
+ on the neuron device is computed on the host for float64 accuracy (device
191
+ arithmetic is fp32); pass float32 to stay on device").
192
+ `TRNSPARSE_FP64_ON_DEVICE=1` keeps device aten (fp32 precision, no
193
+ copies). Host-resident float64, explicit `nki` and the pytorch backend
194
+ are unchanged; the fused solvers already ran float64 on the host.
195
+ **`TRNSPARSE_REQUIRE_NKI=1` raises for float64 / complex128 on the neuron
196
+ device** at every public op (backends `auto` and `nki`, also with
197
+ `TRNSPARSE_FP64_ON_DEVICE=1`), before any host copy or kernel. Before, the
198
+ routes with no kernel (CSR `spmv`, `spmv_symmetric`, `spmm`, the Jacobi
199
+ preconditioner) ran device aten at fp32 precision with no error under
200
+ REQUIRE_NKI and `auto` (Trn2 conformance: `test_spmv[float64-*]` rel err
201
+ 1e-8..2e-7 against the 1e-10 tolerance).
202
+
203
+ `kernel_matmul` / `KernelOperator` (#93, new in this release) follow the
204
+ same rules through `dispatch._fp64_route`: under REQUIRE_NKI float64 now
205
+ raises `NotImplementedError` (it raised `TypeError`), and the explicit-nki
206
+ fp32 warning fires once per op (it fired on every call). Integer, bool and
207
+ complex inputs on the NKI path take the PyTorch path, as the pytorch
208
+ backend does (they raised `TypeError`), or raise `NotImplementedError`
209
+ under REQUIRE_NKI. Device-resident float64 under `auto`: `kernel_matmul`
210
+ is guarded like the other ops, and a float64 `KernelOperator` bound for
211
+ the neuron device is built and applied on the host (one `UserWarning`),
212
+ returning each product on V's device.
213
+
214
+ ### Fixed
215
+
216
+ - **No NKI kernel is reached with an operand dtype it does not take** (one
217
+ guard at the kernel boundary; trnsci/trnsci#35, the class of #78 and #79).
218
+ At each entry (`spmm`, `bsr_spmm`, `screened_spmm`,
219
+ `block_sparse_attention_tiled` forward and backward), integer and bool
220
+ values, and complex values except in `bsr_spmm` (real kernel launches,
221
+ #78), now take the PyTorch path that `set_backend("pytorch")` takes, or
222
+ raise `NotImplementedError` under `TRNSPARSE_REQUIRE_NKI`. Before, they went
223
+ into the fp32/bf16 kernels on the NKI and auto backends: complex operands of
224
+ `spmm` / `screened_spmm` reached the kernel unchanged, the static attention
225
+ kernels cast complex Q/K/V to fp32 (imaginary part dropped), the static
226
+ `bsr_spmm` and attention kernels cast integers to fp32 and back, and
227
+ REQUIRE_NKI failed with whatever error the kernel raised. float64 follows
228
+ the fp64 policy below (#84); fp32, bf16 and fp16 are unchanged. Every
229
+ launch now also checks a per-kernel, per-operand dtype table itself
230
+ (`_KERNEL_OPERAND_DTYPES`: the native op table, `_run` on the XLA path and
231
+ the simulator) and raises `TypeError` naming the op and dtypes, so a future
232
+ wrapper without the entry check cannot hand a kernel an unsupported dtype.
233
+ The eager-handle fast path (`_native_call`, and `_kmv_launch` for
234
+ `kernel_matmul`, whose kernels `kmv_self` / `kmv_cross` / `kmv_selfblk`
235
+ are now in the table as fp32-only) skips the guarded op body, so it checks
236
+ the table itself before the launch.
237
+ Affects every release with NKI kernels, through 0.13.0.
238
+
239
+ - **`spmm` with a 1-D `B` raised on the NKI path (#105).** Affected
240
+ 0.2.0–0.13.0: under `set_backend("nki")` / `"auto"` on a Neuron host,
241
+ `spmm(A, b)` with a vector `b` failed in the NKI GEMM wrapper with
242
+ `ValueError: not enough values to unpack (expected 2, got 1)`, while the
243
+ pytorch backend returns `A @ b` of shape `(m,)`. The vector now goes to the
244
+ kernel as one column and the result is squeezed back. Matrix `B` is
245
+ unchanged.
246
+
247
+ - **`kernel_matmul` no longer hits the Neuron runtime's 30 s execution
248
+ timeout at n >= 1e6** (#100). One launch at n = 2^20, R = 33 takes about
249
+ 40 s at LNC=2 and 80 s at LNC=1 on Trn2 and failed with `NRT status 5`.
250
+ Products above 6e10 kernel entries (`n * m`; the rate is flat in R, so
251
+ the budget is not weighted by d + R) now run as host-side row blocks of
252
+ X: the fewest launches the budget allows, split into equal blocks of a
253
+ multiple of 1024 rows (19 launches of 55296 rows at n = m = 2^20, about
254
+ 2.2 s each at LNC=2 and 4.5 s at LNC=1), R kept whole. Large blocks keep
255
+ the fixed per-launch cost (~75 ms, staging Y) near 1% of the run; Y, V
256
+ and params are placed on the device once for all blocks. The ragged last
257
+ block is zero-padded (less than 1024 rows per block), so every launch has
258
+ one shape, one compile and one cached `wrap_nki` handle (now keyed per
259
+ kernel and shape). Blocks of the square operator use a new
260
+ `_kmv_selfblk_kernel` (custom op `trnsparse::kmv_selfblk`) that adds
261
+ `noise * V` for the block's rows in the same fused epilogue, so blocked
262
+ results are bit-identical to one launch. Below the budget nothing
263
+ changes. `TRNSPARSE_KMV_BLOCK_WORK` overrides the budget.
264
+
265
+ - **`cg_bsr` raised `UnboundLocalError` with `max_iter=0` or on a first-step
266
+ breakdown, and reported `iters=max_iter` on any breakdown** (#71, #86).
267
+ `r_norm` was only assigned inside the loop, so `max_iter=0`, `A p = 0`
268
+ (e.g. a zero matrix) or `p . A p = 0` at k=0 (an exact `x0` with `tol=0`)
269
+ raised. A later breakdown (`|p . A p| < 1e-30`, e.g. after exact
270
+ convergence with `tol=0`) returned `iters = max_iter` (500 or 1000 for a
271
+ 1-2 step solve). `cg_bsr` now returns the number of steps actually taken
272
+ and the residual of the returned `x`; `max_iter=0` gives
273
+ `(x0, 0, ||b - A x0|| / ||b||)`. Solutions are unchanged. Affects 0.3.2
274
+ through 0.13.0.
275
+ - **`power_iteration_bsr` gave silently wrong gradients** (#96), as
276
+ `cg_bsr` did (#70). The norms were taken with `.item()`, so autograd
277
+ differentiated the iterations with frozen normalisation instead of the
278
+ eigenvector, and `v0` received a spurious gradient. The eigenvector now
279
+ differentiates as the exact unit eigenvector of `A` (implicit
280
+ differentiation of `A v = lam v`, `||v|| = 1`): backward solves a dense
281
+ bordered `(N+1) x (N+1)` system, so it costs O(N^3), and gives
282
+ `grad_A = -w v^T` on the stored blocks. `v0` gets no gradient, the
283
+ eigenvalue stays a Python float, and backward raises `NotImplementedError`
284
+ for complex `A`. Forward values are unchanged. Affects 0.3.2 through 0.13.0.
285
+ - **`from_scipy` downcast float64 and integer matrices to float32** (silent,
286
+ #69). Every real scipy matrix was stored as float32 (float64 rounded to
287
+ ~3e-8 relative error; int64 exact only up to 2^24) and complex128 as
288
+ complex64, which contradicted the "zero-copy" description in
289
+ docs/migration_scipy.md. The values now keep the scipy dtype, and for CSR
290
+ input share memory with `sp_matrix.data`. Affects 0.1.1 through 0.13.0.
291
+ **Behaviour change:** float64 scipy input now gives a float64 matrix, so
292
+ mixing it with float32 vectors (`spmv(from_scipy(M64), x32)`) raises the
293
+ usual torch dtype-mismatch error; cast one side (`M.astype(np.float32)`).
294
+ docs/migration_scipy.md no longer refers to a nonexistent `.to_scipy()`.
295
+ - **`cg_bsr` gave silently wrong gradients** (#70). The CG step sizes were
296
+ taken with `.item()`, so autograd differentiated a frozen-coefficient
297
+ polynomial in `A` applied to `b`, not the solve: with `b` along an
298
+ eigenvector (one-step convergence) `b.grad` was ~20% off `A^{-1} g`, and
299
+ `A.blocks.grad` had the same problem. `cg_bsr` now differentiates as the
300
+ exact solve (implicit differentiation, like `torch.linalg.solve`):
301
+ backward runs a second CG solve `A lam = grad_x` with the same
302
+ `tol` / `max_iter` / `M`, giving `grad_b = lam` and
303
+ `grad_A = -lam x^H` on the stored blocks. `x0` and `M` no longer receive
304
+ gradients. Forward values are unchanged. Affects 0.3.2 through 0.13.0.
305
+ - **`cg_bsr_fused` / `power_iteration_bsr_fused` gave wrong results for
306
+ complex, integer and bool inputs** (silent, #85). Both pack A and the
307
+ vectors into real float tiles, so on every backend (including
308
+ `set_backend("pytorch")`) a complex A or b lost its imaginary part, and an
309
+ integer or bool b gave a truncated x of b's dtype. They (and
310
+ `prepare_cg_bsr`) now raise `TypeError` for a non-real-float `A.blocks`,
311
+ `b`, `x0` or `v0`, before any backend runs. Affects 0.11.0 through 0.13.0.
312
+
10
313
  ## [0.13.0] — 2026-11-02
11
314
 
12
315
  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.13.0
3
+ Version: 0.15.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 32 (32 from m = 131072), 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)}$