trnsparse 0.10.0__tar.gz → 0.12.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 (87) hide show
  1. {trnsparse-0.10.0 → trnsparse-0.12.0}/CHANGELOG.md +144 -0
  2. {trnsparse-0.10.0 → trnsparse-0.12.0}/PKG-INFO +3 -1
  3. {trnsparse-0.10.0 → trnsparse-0.12.0}/README.md +2 -0
  4. trnsparse-0.12.0/benchmarks/bench_cg_fused_trn2.py +355 -0
  5. trnsparse-0.12.0/benchmarks/bench_power_fused_trn2.py +136 -0
  6. {trnsparse-0.10.0 → trnsparse-0.12.0}/docs/architecture.md +5 -1
  7. trnsparse-0.12.0/docs/benchmarks.md +1021 -0
  8. trnsparse-0.12.0/docs/iterative_solvers.md +248 -0
  9. {trnsparse-0.10.0 → trnsparse-0.12.0}/pyproject.toml +1 -1
  10. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_attention.py +10 -0
  11. trnsparse-0.12.0/tests/test_iterative.py +523 -0
  12. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_multicore.py +25 -0
  13. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_native_dispatch.py +182 -8
  14. trnsparse-0.12.0/tests/test_nki_cg_fused.py +282 -0
  15. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_nki_compile.py +186 -0
  16. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_nki_native.py +41 -0
  17. trnsparse-0.12.0/tests/test_nki_tail_audit.py +361 -0
  18. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/__init__.py +9 -1
  19. trnsparse-0.12.0/trnsparse/iterative.py +909 -0
  20. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/multicore.py +9 -2
  21. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/nki/_native.py +82 -0
  22. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/nki/_native_attn.py +11 -7
  23. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/nki/dispatch.py +52 -8
  24. trnsparse-0.12.0/trnsparse/nki/kernels.py +2348 -0
  25. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/ops.py +30 -12
  26. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse.egg-info/PKG-INFO +3 -1
  27. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse.egg-info/SOURCES.txt +4 -0
  28. trnsparse-0.10.0/docs/benchmarks.md +0 -453
  29. trnsparse-0.10.0/docs/iterative_solvers.md +0 -115
  30. trnsparse-0.10.0/tests/test_iterative.py +0 -226
  31. trnsparse-0.10.0/trnsparse/iterative.py +0 -352
  32. trnsparse-0.10.0/trnsparse/nki/kernels.py +0 -1135
  33. {trnsparse-0.10.0 → trnsparse-0.12.0}/.github/workflows/ci.yml +0 -0
  34. {trnsparse-0.10.0 → trnsparse-0.12.0}/.github/workflows/notify-umbrella.yml +0 -0
  35. {trnsparse-0.10.0 → trnsparse-0.12.0}/.github/workflows/publish.yml +0 -0
  36. {trnsparse-0.10.0 → trnsparse-0.12.0}/.gitignore +0 -0
  37. {trnsparse-0.10.0 → trnsparse-0.12.0}/.pre-commit-config.yaml +0 -0
  38. {trnsparse-0.10.0 → trnsparse-0.12.0}/CLAUDE.md +0 -0
  39. {trnsparse-0.10.0 → trnsparse-0.12.0}/CODE_OF_CONDUCT.md +0 -0
  40. {trnsparse-0.10.0 → trnsparse-0.12.0}/CONTRIBUTING.md +0 -0
  41. {trnsparse-0.10.0 → trnsparse-0.12.0}/LICENSE +0 -0
  42. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/bench_bsr_spmm.py +0 -0
  43. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/bench_iterative.py +0 -0
  44. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/bench_multicore_trn2.py +0 -0
  45. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/bench_multiproc_trn2.py +0 -0
  46. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/bench_native_trn2.py +0 -0
  47. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/bench_screening.py +0 -0
  48. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/bench_spmm.py +0 -0
  49. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/bench_spmv.py +0 -0
  50. {trnsparse-0.10.0 → trnsparse-0.12.0}/benchmarks/conftest.py +0 -0
  51. {trnsparse-0.10.0 → trnsparse-0.12.0}/docs/api.md +0 -0
  52. {trnsparse-0.10.0 → trnsparse-0.12.0}/docs/aws_setup.md +0 -0
  53. {trnsparse-0.10.0 → trnsparse-0.12.0}/docs/index.md +0 -0
  54. {trnsparse-0.10.0 → trnsparse-0.12.0}/docs/installation.md +0 -0
  55. {trnsparse-0.10.0 → trnsparse-0.12.0}/docs/migration_scipy.md +0 -0
  56. {trnsparse-0.10.0 → trnsparse-0.12.0}/docs/quickstart.md +0 -0
  57. {trnsparse-0.10.0 → trnsparse-0.12.0}/docs/sparse_attention.md +0 -0
  58. {trnsparse-0.10.0 → trnsparse-0.12.0}/examples/block_sparse_attention.py +0 -0
  59. {trnsparse-0.10.0 → trnsparse-0.12.0}/examples/sparse_fock.py +0 -0
  60. {trnsparse-0.10.0 → trnsparse-0.12.0}/infra/terraform/.terraform.lock.hcl +0 -0
  61. {trnsparse-0.10.0 → trnsparse-0.12.0}/infra/terraform/README.md +0 -0
  62. {trnsparse-0.10.0 → trnsparse-0.12.0}/infra/terraform/main.tf +0 -0
  63. {trnsparse-0.10.0 → trnsparse-0.12.0}/mkdocs.yml +0 -0
  64. {trnsparse-0.10.0 → trnsparse-0.12.0}/scripts/bench_to_md.py +0 -0
  65. {trnsparse-0.10.0 → trnsparse-0.12.0}/scripts/run_benchmarks.sh +0 -0
  66. {trnsparse-0.10.0 → trnsparse-0.12.0}/scripts/run_neuron_tests.sh +0 -0
  67. {trnsparse-0.10.0 → trnsparse-0.12.0}/scripts/run_simulator_tests.sh +0 -0
  68. {trnsparse-0.10.0 → trnsparse-0.12.0}/setup.cfg +0 -0
  69. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/conftest.py +0 -0
  70. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_attn_gather.py +0 -0
  71. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_bsr.py +0 -0
  72. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_core_split.py +0 -0
  73. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_examples.py +0 -0
  74. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_formats.py +0 -0
  75. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_nki_attn.py +0 -0
  76. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_nki_bsr.py +0 -0
  77. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_nki_screened_spmm.py +0 -0
  78. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_nki_sim.py +0 -0
  79. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_nki_spmm.py +0 -0
  80. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_ops.py +0 -0
  81. {trnsparse-0.10.0 → trnsparse-0.12.0}/tests/test_screening.py +0 -0
  82. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/formats.py +0 -0
  83. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/nki/__init__.py +0 -0
  84. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse/screening.py +0 -0
  85. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse.egg-info/dependency_links.txt +0 -0
  86. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse.egg-info/requires.txt +0 -0
  87. {trnsparse-0.10.0 → trnsparse-0.12.0}/trnsparse.egg-info/top_level.txt +0 -0
@@ -7,6 +7,150 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.12.0] — 2026-11-01
11
+
12
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
13
+
14
+ Headline: **correctness fix — upgrade recommended if you pass `scale` to block-sparse attention.** In 0.6.0–0.11.0 a custom `scale` passed to `block_sparse_attention_tiled` was silently ignored on the NKI paths (forward and dQ/dK/dV; 29–99% relative error at scale 0.1–2.0). The native `trnsparse::bsr_attn` op was affected from 0.9.0. The PyTorch backend and `ShardedAttention` were correct, and the default `scale=None` was unaffected (#50, #47). Also: BSR block sizes other than 128 go straight to the torch path instead of paying a failed NKI compile on every call (7–41 s first call, 6.7–8.3× steady), which covers `bsr_spmm`, attention and the iterative solvers (#48, #46).
15
+
16
+ ### Fixed
17
+
18
+ - **`block_sparse_attention_tiled` silently ignored a custom `scale` on the
19
+ NKI paths** (released 0.6.0 through 0.11.0; #47). With `backend="nki"` or
20
+ `"auto"` on Neuron, the forward and all three gradients always used
21
+ `head_dim ** -0.5`, and no error was raised. On Trn2 (seq 384, head_dim 64,
22
+ relative error against dense fp64 attention) the forward was off by 29%
23
+ (`scale=0.1`), 93% (`1.0`) and 95% (`2.0`), and dQ / dK by up to 99%. The
24
+ XLA / simulator path (`_AttnTiledFunction` and the no-grad call) was
25
+ affected from 0.6.0, and the native TorchNeuron `trnsparse::bsr_attn` op
26
+ from 0.9.0. The PyTorch backend was always correct. `scale` now reaches
27
+ `nki_bsr_attn_tiled`, `nki_bsr_attn_bwd` and the `bsr_attn` /
28
+ `bsr_attn_bwd` ops, each of which takes a new optional `scale` argument
29
+ (default `head_dim ** -0.5`). The kernels are unchanged: they already take
30
+ `Q * scale`, and the static backward takes `scale` as a kernel argument.
31
+ With the default `scale=None`, outputs and gradients are bit-identical to
32
+ 0.11.0 on Trn2. `ShardedAttention.shard_rows(Q, scale)` was not affected.
33
+ - `bsr_spmm` and `block_sparse_attention_tiled` with a `block_size` other than
34
+ 128 (16, 32 and 64 in the audit) no longer try an NKI kernel first. The
35
+ kernels take 128x128 blocks only, so that trace always failed, and the call
36
+ fell back to torch only after paying for it: 7-9 s on the first `bsr_spmm`
37
+ call and 27-41 s on the first attention call on Trn2. These block sizes now
38
+ go straight to the PyTorch path under `auto` (and under `nki` when
39
+ `TRNSPARSE_REQUIRE_NKI` is not set). Under `TRNSPARSE_REQUIRE_NKI` they raise
40
+ `NotImplementedError` naming the supported block size. The unfused
41
+ iterative solvers (`cg_bsr`, `power_iteration_bsr`, `chebyshev_bsr`,
42
+ `richardson_bsr`) also benefit, because they call `bsr_spmm` on every
43
+ iteration (#46).
44
+
45
+ ## [0.11.0] — 2026-11-01
46
+
47
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
48
+
49
+ Headline: fused CG/PCG (`cg_bsr_fused`) with a column matvec is 5–56× faster than CPU, and the fixed per-iteration cost is halved (#41, #43); fused power iteration (#41). **Fix:** in 0.6.0–0.10.0, `block_sparse_attention_tiled` silently returned zero rows for a partial last block on the PyTorch path; it now raises (#44). A host `BSRMatrix` with device `b` in `cg_bsr_fused` now works (#42).
50
+
51
+ ### Fixed
52
+
53
+ - **`block_sparse_attention_tiled` silently returned zero rows for a partial
54
+ last block** (released 0.6.0 through 0.10.0, PyTorch path). With
55
+ `seq_len % block_size != 0` the query rows past the last whole block were
56
+ left at 0 (seq_len 200, block 128: rows 128-199 zero, max error 0.79). It now
57
+ raises `ValueError` on every backend; partial blocks need -inf key masking,
58
+ not zero padding. `ShardedAttention` raises the same error.
59
+ - `ShardedBSR.gather` (0.10.0) raised a `RuntimeError` from `view` when the row
60
+ count was not a multiple of 128. It now gathers at the padded row count and
61
+ slices back.
62
+
63
+ ### Added
64
+
65
+ - `tests/test_nki_tail_audit.py`: every NKI kernel (CSR and BSR SpMM, screened
66
+ SpMM, attention, fused CG and power iteration) at awkward sizes (1, 127, 129,
67
+ 200, 1000, 4097; odd N; free dims not a multiple of 512) against fp64
68
+ references (trnsci/trnsci#35).
69
+
70
+ #### Fused SBUF-resident CG (#22)
71
+
72
+ - `cg_bsr_fused(A, b, ...)` and `prepare_cg_bsr(A, preconditioner=None |
73
+ "block_jacobi", device=...)` (a reusable `FusedCGOperator`): the whole
74
+ CG or block-Jacobi PCG solve runs in one NKI launch
75
+ (`trnsparse::cg_bsr_keyed`). A's blocks are loaded into SBUF once
76
+ (`TRNSPARSE_CG_SBUF_KIB`, default 160 KiB per partition; any overflow
77
+ streams from HBM inside the loop). Vectors stay in SBUF, dot products
78
+ reduce through PSUM, and an `nl.while_loop` checks convergence on the
79
+ device every `check_every` steps, with masked steps so the iteration
80
+ count is exact. At LNC=2 the two physical cores split the block rows
81
+ and exchange partial dots and halves of p with `sendrecv`. `b` may be
82
+ `(n, R)`: R independent solves share each matmul.
83
+ - Host fallback with the same algorithm (fp64 stays fp64), CPU tests,
84
+ MLIR verify and NEFF compile at LNC=1/2, and hardware tests
85
+ (`tests/test_nki_cg_fused.py`).
86
+ - `benchmarks/bench_cg_fused_trn2.py`: time to tolerance against a
87
+ host-driven loop over the BSR SpMM op, `cg_bsr`, dense aten CG on the
88
+ device, scipy and torch on the CPU, on synthetic block-screened
89
+ Gaussian-overlap matrices.
90
+
91
+ #### Fused CG follow-ups (#22): column matvec, bf16 A, fused power iteration
92
+
93
+ - `cg_bsr_fused(..., matvec="auto" | "row" | "column")`: the
94
+ **vector-stationary ("column") matvec** is the new default for up to 32
95
+ right-hand sides. The vector is the TensorE stationary operand, the
96
+ stored block streams through as the moving operand, and four 32-column
97
+ PE tiles work in turn. Each 16 block rows are then transposed back to
98
+ the column layout on TensorE (bit-exact). That is about 50 ns per
99
+ resident fp32 block against 425 ns for the row form, with the same
100
+ fp32 arithmetic in a different summation order. It needs no relayout
101
+ of the stored blocks. More than 32 right-hand sides keep `"row"`.
102
+ - Two `sendrecv` exchanges per CG step at LNC=2 instead of three. The
103
+ cores swap their rows of r (and z) and then compute r.z, r.r and
104
+ p = z + beta p over the full width, bit-identically on both cores.
105
+ This replaces separate exchanges of the partial dots and of p.
106
+ - `precision="bf16" | "bf16x2"` (opt-in, column matvec, R <= 16): bf16 A,
107
+ or bf16 hi + lo A, with fp32 vectors (split into bf16 hi + lo on the
108
+ device) and fp32 accumulation. The host path emulates both.
109
+ - `power_iteration_bsr_fused(A, v0, max_iter, tol, ...)`
110
+ (`trnsparse::power_bsr_keyed`): power iteration in one launch on the
111
+ same kernel (Rayleigh quotient, device-side stop on |Δλ| < tol, LNC=2
112
+ row split).
113
+ - `benchmarks/bench_cg_fused_trn2.py --matvec row,column,column:bf16,...`
114
+ and `benchmarks/bench_power_fused_trn2.py`.
115
+
116
+ #### Fused CG: fixed per-iteration cost (#22)
117
+
118
+ - Plain CG at LNC=2 exchanges **once per step**: the cores swap their rows
119
+ of q = A p and then compute p.q, r, r.r and p over the full width,
120
+ bit-identically. PCG still exchanges twice, but the second exchange
121
+ carries z with the partial r.z and r.r. Full-width vectors use a
122
+ segment layout (each core's rows contiguous), so every exchange is one
123
+ `sendrecv` with no copies, and exchanges up to 1 KiB per partition use
124
+ GpSimd's SBUF-to-SBUF DMA (about 0.9 µs against 2.4 µs).
125
+ - Column matvec: "spread" source vectors (each block column after
126
+ (G - 1) R zero columns) put up to 4 G block rows into one PSUM slot, so
127
+ a chunk takes one PSUM-to-SBUF copy and one TensorE transpose instead of
128
+ one of each per four rows (fp32 A, R in 1, 2, 4, 8).
129
+ - `cg_row_order`: each core's block rows are reordered so the four
130
+ concurrent TensorE column groups carry about the same number of blocks
131
+ (b, x0 and x are permuted by DMA in the kernel).
132
+ - Shorter step-size chain (no `max` before the reciprocal of p.Ap; r.z x
133
+ act formed off the critical path), the x update deferred into the next
134
+ matvec, the all-ones reduction matmul flagged `is_stationary_onezero`.
135
+ - PSUM tiles are allocated once per trip of the device loop and re-zeroed,
136
+ so NKI's allocator no longer falls back to neuronx-cc allocation and
137
+ scheduling.
138
+ - `cg_bsr_fused(..., recurrence="chronopoulos_gear")` (opt-in, plain CG):
139
+ the Chronopoulos–Gear recurrence, one reduction phase per step. The host
140
+ path runs the same recurrence.
141
+ - Measured on Trn2 (#22, `docs/benchmarks.md`): the fixed cost per plain
142
+ CG iteration falls from about 11 µs to about 4 µs at LNC=2 and from about
143
+ 8 µs to about 3.5 µs at LNC=1.
144
+
145
+ ### Fixed
146
+
147
+ - `cg_bsr_fused` / `power_iteration_bsr_fused` with a host `BSRMatrix` and
148
+ `b` (or `v0`) on the `neuron` device raised `ModuleNotFoundError:
149
+ torch_neuronx.pyhlo`: the kernel got host tensors and NKI fell back to
150
+ its torch-xla framework (#42). A `BSRMatrix` is now prepared on b's
151
+ device, and the fused kernel runs only for an operator on a `neuron`
152
+ device (a host operator takes the host path).
153
+
10
154
  ## [0.10.0] — 2026-10-31
11
155
 
12
156
  Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trnsparse
3
- Version: 0.10.0
3
+ Version: 0.12.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
@@ -133,9 +133,11 @@ stats = trnsparse.sparsity_stats(Q)
133
133
  | `sparse_scale` | B = αA |
134
134
  | `sparse_transpose` | Aᵀ |
135
135
  | `cg_bsr` | Conjugate Gradient on BSR matrix |
136
+ | `cg_bsr_fused` / `prepare_cg_bsr` | One-launch CG / block-Jacobi PCG, A in SBUF, vector-stationary TensorE matvec, device-side convergence check, multi-RHS, opt-in bf16 A |
136
137
  | `chebyshev_bsr` | Fixed-K Chebyshev semi-iteration (no inner products) |
137
138
  | `richardson_bsr` | Fixed-K Richardson iteration |
138
139
  | `power_iteration_bsr` | Dominant eigenpair via power iteration |
140
+ | `power_iteration_bsr_fused` | Power iteration in one launch (the fused CG kernel's machinery) |
139
141
  | `jacobi_preconditioner_bsr` | Diagonal preconditioner for `cg_bsr` |
140
142
  | `bsr_diagonal` | Extract main diagonal from BSR matrix |
141
143
  | `block_sparse_attention_tiled` | Two-pass sparse attention, no O(seq²) intermediate |
@@ -98,9 +98,11 @@ stats = trnsparse.sparsity_stats(Q)
98
98
  | `sparse_scale` | B = αA |
99
99
  | `sparse_transpose` | Aᵀ |
100
100
  | `cg_bsr` | Conjugate Gradient on BSR matrix |
101
+ | `cg_bsr_fused` / `prepare_cg_bsr` | One-launch CG / block-Jacobi PCG, A in SBUF, vector-stationary TensorE matvec, device-side convergence check, multi-RHS, opt-in bf16 A |
101
102
  | `chebyshev_bsr` | Fixed-K Chebyshev semi-iteration (no inner products) |
102
103
  | `richardson_bsr` | Fixed-K Richardson iteration |
103
104
  | `power_iteration_bsr` | Dominant eigenpair via power iteration |
105
+ | `power_iteration_bsr_fused` | Power iteration in one launch (the fused CG kernel's machinery) |
104
106
  | `jacobi_preconditioner_bsr` | Diagonal preconditioner for `cg_bsr` |
105
107
  | `bsr_diagonal` | Extract main diagonal from BSR matrix |
106
108
  | `block_sparse_attention_tiled` | Two-pass sparse attention, no O(seq²) intermediate |
@@ -0,0 +1,355 @@
1
+ """Time-to-tolerance for the fused SBUF-resident CG (`cg_bsr_fused`, #22).
2
+
3
+ Standalone script (not pytest-benchmark), one matrix per process, one JSON
4
+ line per (method, preconditioner) row, appended to ``--out``:
5
+
6
+ NKI_ENABLE_TRACE_CACHE=0 taskset -c 10,11 \\
7
+ python benchmarks/bench_cg_fused_trn2.py --tiles 32 --density 0.25
8
+
9
+ Test matrices are synthetic and chemistry-flavoured: the overlap matrix of
10
+ normalised s-type Gaussians on a synthetic molecular cluster. Each 128-row
11
+ block row is one "fragment" (128 Gaussians with jittered centres and
12
+ log-uniform exponents around a fragment centre); fragment centres are
13
+ random in a box. Blocks between fragments farther apart than a cutoff are
14
+ dropped (block screening), the cutoff chosen to hit ``--density``; then a
15
+ level shift sets the condition number to ``--kappa`` exactly, which keeps
16
+ the screened matrix SPD. A is built in fp64; every solver gets the fp32
17
+ rounding of it except the fp64 CPU baselines.
18
+
19
+ Methods (each row reports wall time to tolerance, iterations, and the true
20
+ residual ||b - A x|| / ||b|| and the error against an fp64 direct solve):
21
+
22
+ fused cg_bsr_fused: one launch, A's blocks in SBUF, device-side
23
+ convergence check every --check-every steps; one row per
24
+ --matvec variant (row, column, column:bf16, column:bf16x2)
25
+ host_bsr host-driven CG over the keyed pre-transposed BSR SpMM op,
26
+ device tensors, no host sync except every --check-every
27
+ steps
28
+ cg_bsr trnsparse.cg_bsr as shipped (one .item() sync per dot)
29
+ dense_aten CG with torch.mv on a dense fp32 A on the device, synced
30
+ every --check-every steps
31
+ scipy scipy.sparse.linalg.cg on a BSR (fp64) matrix, on the host
32
+ torch_cpu the cg_bsr_fused host path (fp64 and fp32 block bmm)
33
+
34
+ Plain CG and block-Jacobi PCG (exact inverses of the 128x128 diagonal
35
+ blocks) for fused, host_bsr, scipy and torch_cpu. Host threads are whatever
36
+ the process is pinned to (``taskset``), with OMP_NUM_THREADS matching.
37
+ """
38
+
39
+ # ruff: noqa: B023 (every closure is benchmarked before its loop variables change)
40
+ from __future__ import annotations
41
+
42
+ import argparse
43
+ import json
44
+ import os
45
+ import statistics
46
+ import sys
47
+ import time
48
+ from pathlib import Path
49
+
50
+ import numpy as np
51
+ import torch
52
+
53
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
54
+
55
+ import trnsparse # noqa: E402
56
+ from trnsparse.iterative import prepare_cg_bsr # noqa: E402
57
+
58
+ P = 128
59
+
60
+
61
+ def cluster_overlap(T: int, density: float, kappa: float, seed: int = 0):
62
+ """Block-screened Gaussian overlap of a synthetic cluster, shifted to kappa."""
63
+ rng = np.random.default_rng(seed)
64
+ n = T * P
65
+ side = 3.5 * T ** (1 / 3) # about one fragment per 3.5^3 volume
66
+ centres = rng.uniform(0, side, size=(T, 3))
67
+ pos = np.repeat(centres, P, axis=0) + rng.normal(0, 0.8, size=(n, 3))
68
+ expo = np.exp(rng.uniform(np.log(0.15), np.log(3.0), size=n))
69
+ d = np.linalg.norm(centres[:, None] - centres[None], axis=-1)
70
+ off = np.sort(d[np.triu_indices(T, 1)])
71
+ n_pairs = max(0, round((density * T * T - T) / 2))
72
+ keep = d <= (off[n_pairs - 1] if n_pairs > 0 else -1.0)
73
+ np.fill_diagonal(keep, True)
74
+ A = np.zeros((n, n))
75
+ for i in range(T):
76
+ si = slice(i * P, (i + 1) * P)
77
+ for j in range(i, T):
78
+ if not keep[i, j]:
79
+ continue
80
+ sj = slice(j * P, (j + 1) * P)
81
+ ai, aj = expo[si, None], expo[None, sj]
82
+ r2 = ((pos[si, None, :] - pos[None, sj, :]) ** 2).sum(-1)
83
+ s = (2 * np.sqrt(ai * aj) / (ai + aj)) ** 1.5 * np.exp(-(ai * aj / (ai + aj)) * r2)
84
+ A[si, sj] = s
85
+ A[sj, si] = s.T
86
+ ev = np.linalg.eigvalsh(A) if n <= 8192 else None
87
+ lo, hi = ev[0], ev[-1]
88
+ mu = (hi - kappa * lo) / (kappa - 1)
89
+ A[np.diag_indices(n)] += mu
90
+ return A, keep
91
+
92
+
93
+ def _sync():
94
+ if hasattr(torch, "neuron"):
95
+ torch.neuron.synchronize()
96
+
97
+
98
+ def timed(fn, reps):
99
+ out = fn() # warm (compiles)
100
+ ts = []
101
+ for _ in range(reps):
102
+ _sync()
103
+ t = time.perf_counter()
104
+ out = fn()
105
+ _sync()
106
+ ts.append(time.perf_counter() - t)
107
+ return statistics.median(ts), out
108
+
109
+
110
+ def host_cg(matvec, precond, b, tol, max_iter, check_every):
111
+ """CG on device tensors (b: (n, R), one solve per column) with a host
112
+ sync only every `check_every` steps, when all columns are tested."""
113
+ x = torch.zeros_like(b)
114
+ r = b.clone()
115
+ z = precond(r) if precond else r
116
+ p = z.clone()
117
+ rz = (r * z).sum(0)
118
+ thr = tol * tol * (b * b).sum(0).cpu()
119
+ k = 0
120
+ while k < max_iter:
121
+ for _ in range(check_every):
122
+ q = matvec(p)
123
+ alpha = rz / (p * q).sum(0).clamp_min(1e-30)
124
+ x = x + alpha * p
125
+ r = r - alpha * q
126
+ z = precond(r) if precond else r
127
+ rz_new = (r * z).sum(0)
128
+ p = z + (rz_new / rz.clamp_min(1e-30)) * p
129
+ rz = rz_new
130
+ k += 1
131
+ if bool(((r * r).sum(0).cpu() <= thr).all()):
132
+ break
133
+ return x, k
134
+
135
+
136
+ def main():
137
+ ap = argparse.ArgumentParser()
138
+ ap.add_argument("--tiles", type=int, required=True, help="block rows T (n = 128 T)")
139
+ ap.add_argument("--density", type=float, required=True, help="target block density")
140
+ ap.add_argument("--kappa", type=float, default=1e3)
141
+ ap.add_argument("--tol", type=float, default=1e-5)
142
+ ap.add_argument("--max-iter", type=int, default=5000)
143
+ ap.add_argument("--check-every", type=int, default=8)
144
+ ap.add_argument("--reps", type=int, default=3)
145
+ ap.add_argument("--methods", default="fused,host_bsr,cg_bsr,dense_aten,scipy,torch_cpu")
146
+ ap.add_argument("--precond", default="none,block_jacobi")
147
+ ap.add_argument("--out", default="cg_fused.jsonl")
148
+ ap.add_argument("--tag", default="")
149
+ ap.add_argument("--rhs", type=int, default=1, help="right-hand sides solved together")
150
+ ap.add_argument(
151
+ "--matvec",
152
+ default="auto",
153
+ help="fused variants, comma-separated matvec[:precision], e.g. row,column,column:bf16",
154
+ )
155
+ ap.add_argument(
156
+ "--recurrence",
157
+ default="standard",
158
+ help="fused CG recurrence: standard or chronopoulos_gear (plain CG only)",
159
+ )
160
+ args = ap.parse_args()
161
+ methods = args.methods.split(",")
162
+ preconds = [None if p == "none" else p for p in args.precond.split(",")]
163
+
164
+ t0 = time.time()
165
+ A64, keep = cluster_overlap(args.tiles, args.density, args.kappa)
166
+ n = A64.shape[0]
167
+ rng = np.random.default_rng(1)
168
+ R = args.rhs
169
+ b64 = rng.standard_normal((n, R))
170
+ x_ref = np.linalg.solve(A64, b64)
171
+ gen_s = time.time() - t0
172
+ A32 = torch.from_numpy(A64).float()
173
+ bsr = trnsparse.BSRMatrix.from_dense(A32, block_size=P)
174
+ b = torch.from_numpy(b64 if R > 1 else b64[:, 0])
175
+ base = dict(
176
+ n=n,
177
+ tiles=args.tiles,
178
+ n_blocks=bsr.n_blocks,
179
+ density=round(bsr.n_blocks / args.tiles**2, 4),
180
+ kappa=args.kappa,
181
+ tol=args.tol,
182
+ check_every=args.check_every,
183
+ tag=args.tag,
184
+ rhs=R,
185
+ lnc=os.environ.get("NEURON_LOGICAL_NC_CONFIG", "2"),
186
+ )
187
+ print(f"# n={n} blocks={bsr.n_blocks} gen {gen_s:.1f}s", file=sys.stderr, flush=True)
188
+
189
+ def emit(method, pc, secs, x, iters, extra=None):
190
+ x = np.asarray(x.detach().cpu().double().numpy() if torch.is_tensor(x) else x)
191
+ x = x.reshape(n, R)
192
+ iters = int(np.max(np.asarray(iters)))
193
+ row = dict(base, method=method, precond=pc or "none", ms=round(secs * 1e3, 3))
194
+ res = np.linalg.norm(b64 - A64 @ x, axis=0) / np.linalg.norm(b64, axis=0)
195
+ err = np.linalg.norm(x - x_ref, axis=0) / np.linalg.norm(x_ref, axis=0)
196
+ row.update(
197
+ ms_per_rhs=round(secs * 1e3 / R, 4),
198
+ iters=iters,
199
+ us_per_iter=round(secs * 1e6 / max(iters, 1), 2),
200
+ true_rel_res=float(res.max()),
201
+ rel_err=float(err.max()),
202
+ )
203
+ if extra:
204
+ row.update(extra)
205
+ print(json.dumps(row), flush=True)
206
+ with open(args.out, "a") as f:
207
+ f.write(json.dumps(row) + "\n")
208
+
209
+ from trnsparse.nki.dispatch import _get_native_ops
210
+
211
+ trnsparse.set_backend("nki")
212
+ ops = _get_native_ops()
213
+ dev = torch.device("neuron")
214
+
215
+ for pc in preconds:
216
+ op_dev = prepare_cg_bsr(bsr, preconditioner=pc, device=dev)
217
+ # Chronopoulos-Gear is plain CG only
218
+ rec = args.recurrence if pc is None else "standard"
219
+ for spec in args.matvec.split(",") if "fused" in methods else []:
220
+ mv, _, prec = spec.partition(":")
221
+ prec = prec or "fp32"
222
+ fn = lambda: trnsparse.cg_bsr_fused( # noqa: E731
223
+ op_dev,
224
+ b,
225
+ tol=args.tol,
226
+ max_iter=args.max_iter,
227
+ check_every=args.check_every,
228
+ return_info=True,
229
+ matvec=mv,
230
+ precision=prec,
231
+ recurrence=rec,
232
+ )
233
+ tc = time.time()
234
+ op_dev._device_operands(prec)
235
+ fn()
236
+ compile_s = time.time() - tc
237
+ secs, (x, it, rel, info) = timed(fn, args.reps)
238
+ it = int(torch.as_tensor(it).max())
239
+ # fixed cost: same launch with max_iter=0 (A load, r0, transfers)
240
+ secs0, _ = timed(
241
+ lambda: trnsparse.cg_bsr_fused(
242
+ op_dev, b, tol=args.tol, max_iter=0, matvec=mv, precision=prec, recurrence=rec
243
+ ),
244
+ args.reps,
245
+ )
246
+ emit(
247
+ "fused",
248
+ pc,
249
+ secs,
250
+ x,
251
+ it,
252
+ dict(
253
+ matvec=info["matvec"],
254
+ precision=prec,
255
+ recurrence=rec,
256
+ resident_blocks=info["resident_blocks"],
257
+ trips=info["trips"],
258
+ ms_fixed=round(secs0 * 1e3, 3),
259
+ us_per_iter_marginal=round((secs - secs0) * 1e6 / max(it, 1), 2),
260
+ first_call_s=round(compile_s, 1),
261
+ rec_rel_res=float(torch.as_tensor(rel).max()),
262
+ ),
263
+ )
264
+ if "host_bsr" in methods:
265
+ bt, mt, key = op_dev._device_operands()
266
+ T = args.tiles
267
+ dkey = trnsparse.nki.kernels.register_structure(list(range(T + 1)), list(range(T)))
268
+ mv = lambda v: ops["bsr_spmm_t_keyed"](bt, v, key) # noqa: E731
269
+ pre = (lambda v: ops["bsr_spmm_t_keyed"](mt, v, dkey)) if pc else None # noqa: E731
270
+ bd = b.float().reshape(n, R).to(dev)
271
+ secs, (x, it) = timed(
272
+ lambda: host_cg(mv, pre, bd, args.tol, args.max_iter, args.check_every), args.reps
273
+ )
274
+ emit("host_bsr", pc, secs, x, it)
275
+ if "cg_bsr" in methods and pc is None and R == 1:
276
+ blocks_dev = trnsparse.BSRMatrix(
277
+ bsr.blocks.to(dev), bsr.block_col_indices, bsr.block_row_ptrs, bsr.shape, P
278
+ )
279
+ bd = b.float().to(dev)
280
+ secs, (x, it, rel) = timed(
281
+ lambda: trnsparse.cg_bsr(blocks_dev, bd, tol=args.tol, max_iter=args.max_iter),
282
+ 1,
283
+ )
284
+ emit("cg_bsr", pc, secs, x, it)
285
+ if "dense_aten" in methods and pc is None:
286
+ Ad = A32.to(dev)
287
+ bd = b.float().reshape(n, R).to(dev)
288
+ secs, (x, it) = timed(
289
+ lambda: host_cg(
290
+ lambda v: Ad @ v, None, bd, args.tol, args.max_iter, args.check_every
291
+ ),
292
+ args.reps,
293
+ )
294
+ emit("dense_aten", pc, secs, x, it)
295
+ del Ad
296
+ if "scipy" in methods:
297
+ import scipy.sparse as sp
298
+ import scipy.sparse.linalg as spla
299
+
300
+ As = sp.bsr_matrix(A64, blocksize=(P, P))
301
+ M = None
302
+ if pc:
303
+ minv = op_dev._minv64.numpy()
304
+
305
+ def mfun(v):
306
+ return np.einsum("tij,tj->ti", minv, v.reshape(-1, P)).reshape(-1)
307
+
308
+ M = spla.LinearOperator((n, n), matvec=mfun)
309
+ cnt = [0]
310
+
311
+ def cb(_):
312
+ cnt[0] += 1
313
+
314
+ def run(): # one solve per column (scipy's cg takes a vector)
315
+ cnt[0] = 0
316
+ cols = [
317
+ spla.cg(
318
+ As,
319
+ b64[:, c],
320
+ rtol=args.tol,
321
+ atol=0.0,
322
+ maxiter=args.max_iter,
323
+ M=M,
324
+ callback=cb,
325
+ )[0]
326
+ for c in range(R)
327
+ ]
328
+ return np.stack(cols, axis=1)
329
+
330
+ secs, x = timed(run, args.reps)
331
+ emit("scipy", pc, secs, x, cnt[0] // R, dict(threads=torch.get_num_threads()))
332
+ if "torch_cpu" in methods:
333
+ op_cpu = prepare_cg_bsr(bsr, preconditioner=pc, device="cpu")
334
+ for dt in (torch.float64, torch.float32):
335
+ bb = b.to(dt)
336
+ secs, (x, it, rel) = timed(
337
+ lambda: trnsparse.cg_bsr_fused(
338
+ op_cpu, bb, tol=args.tol, max_iter=args.max_iter
339
+ ),
340
+ args.reps,
341
+ )
342
+ emit(
343
+ f"torch_cpu_{'fp64' if dt == torch.float64 else 'fp32'}",
344
+ pc,
345
+ secs,
346
+ x,
347
+ it,
348
+ dict(threads=torch.get_num_threads()),
349
+ )
350
+ op_dev = None # free the device operands before the next case
351
+ _sync()
352
+
353
+
354
+ if __name__ == "__main__":
355
+ main()
@@ -0,0 +1,136 @@
1
+ """Fused power iteration (`power_iteration_bsr_fused`, #22) on Trn2.
2
+
3
+ Standalone script, one matrix per process, one JSON line per method,
4
+ appended to ``--out``. A fixed number of iterations (tol = 0), so every
5
+ method does the same work:
6
+
7
+ NKI_ENABLE_TRACE_CACHE=0 taskset -c 10,11 \\
8
+ python benchmarks/bench_power_fused_trn2.py --tiles 32 --density 0.25
9
+
10
+ Matrices: the synthetic block-screened Gaussian-overlap matrix of
11
+ `bench_cg_fused_trn2.py` (fp64; the device and fp32 columns get its fp32
12
+ rounding). Methods:
13
+
14
+ fused_column / fused_row power_iteration_bsr_fused, one launch
15
+ host_bsr power_iteration_bsr on the device (the
16
+ shipped loop: BSR SpMM op + two .item() syncs
17
+ per iteration)
18
+ torch_cpu_fp64 / fp32 the power_iteration_bsr_fused host path
19
+ (block bmm), same masked iteration
20
+ scipy the same iteration with a scipy BSR matvec
21
+
22
+ Each row reports ms, µs per iteration, and lam against an fp64 eigvalsh.
23
+ """
24
+
25
+ # ruff: noqa: B023
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import json
30
+ import os
31
+ import sys
32
+ from pathlib import Path
33
+
34
+ import numpy as np
35
+ import torch
36
+
37
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
38
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
39
+
40
+ from bench_cg_fused_trn2 import P, cluster_overlap, timed # noqa: E402
41
+
42
+ import trnsparse # noqa: E402
43
+
44
+
45
+ def main():
46
+ ap = argparse.ArgumentParser()
47
+ ap.add_argument("--tiles", type=int, required=True)
48
+ ap.add_argument("--density", type=float, required=True)
49
+ ap.add_argument("--kappa", type=float, default=1e3)
50
+ ap.add_argument("--iters", type=int, default=200)
51
+ ap.add_argument("--reps", type=int, default=3)
52
+ ap.add_argument("--methods", default="fused_column,fused_row,host_bsr,torch_cpu,scipy")
53
+ ap.add_argument("--out", default="power_fused.jsonl")
54
+ args = ap.parse_args()
55
+ methods = args.methods.split(",")
56
+ K = args.iters
57
+
58
+ A64, _ = cluster_overlap(args.tiles, args.density, args.kappa)
59
+ n = A64.shape[0]
60
+ top = float(np.linalg.eigvalsh(A64)[-1])
61
+ A32 = torch.from_numpy(A64).float()
62
+ bsr = trnsparse.BSRMatrix.from_dense(A32, block_size=P)
63
+ v0 = torch.from_numpy(np.random.default_rng(2).standard_normal(n))
64
+ base = dict(
65
+ n=n,
66
+ tiles=args.tiles,
67
+ n_blocks=bsr.n_blocks,
68
+ density=round(bsr.n_blocks / args.tiles**2, 4),
69
+ iters=K,
70
+ lam_ref=top,
71
+ lnc=os.environ.get("NEURON_LOGICAL_NC_CONFIG", "2"),
72
+ )
73
+
74
+ def emit(method, secs, lam, extra=None):
75
+ row = dict(base, method=method, ms=round(secs * 1e3, 3))
76
+ row.update(us_per_iter=round(secs * 1e6 / K, 2), lam=lam, lam_rel_err=abs(lam - top) / top)
77
+ if extra:
78
+ row.update(extra)
79
+ print(json.dumps(row), flush=True)
80
+ with open(args.out, "a") as f:
81
+ f.write(json.dumps(row) + "\n")
82
+
83
+ trnsparse.set_backend("nki")
84
+ dev = torch.device("neuron")
85
+ op = trnsparse.prepare_cg_bsr(bsr, device=dev)
86
+ for mv in ("column", "row"):
87
+ if f"fused_{mv}" not in methods:
88
+ continue
89
+
90
+ def fn():
91
+ return trnsparse.power_iteration_bsr_fused(
92
+ op, v0=v0, tol=0.0, max_iter=K, matvec=mv, return_info=True
93
+ )
94
+
95
+ secs, (lam, _, k, info) = timed(fn, args.reps)
96
+ assert k == K
97
+ emit(f"fused_{mv}", secs, lam, dict(resident_blocks=info["resident_blocks"]))
98
+ if "host_bsr" in methods:
99
+ bd = trnsparse.BSRMatrix(
100
+ bsr.blocks.to(dev), bsr.block_col_indices, bsr.block_row_ptrs, bsr.shape, P
101
+ )
102
+ vd = v0.float().to(dev)
103
+ secs, (lam, _, k) = timed(
104
+ lambda: trnsparse.power_iteration_bsr(bd, v0=vd, max_iter=K, tol=0.0), 1
105
+ )
106
+ emit("host_bsr", secs, lam)
107
+ op = None
108
+ if "torch_cpu" in methods:
109
+ op_cpu = trnsparse.prepare_cg_bsr(bsr, device="cpu")
110
+ for dt in (torch.float64, torch.float32):
111
+ vv = v0.to(dt)
112
+ secs, (lam, _, _) = timed(
113
+ lambda: trnsparse.power_iteration_bsr_fused(op_cpu, v0=vv, tol=0.0, max_iter=K),
114
+ args.reps,
115
+ )
116
+ emit(f"torch_cpu_{'fp64' if dt == torch.float64 else 'fp32'}", secs, lam)
117
+ if "scipy" in methods:
118
+ import scipy.sparse as sp
119
+
120
+ As = sp.bsr_matrix(A64, blocksize=(P, P))
121
+
122
+ def run():
123
+ v = v0.numpy() / np.linalg.norm(v0.numpy())
124
+ lam = 0.0
125
+ for _ in range(K):
126
+ q = As @ v
127
+ lam = float(v @ q)
128
+ v = q / np.linalg.norm(q)
129
+ return lam
130
+
131
+ secs, lam = timed(run, args.reps)
132
+ emit("scipy", secs, lam)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ main()