trnsparse 0.9.0__tar.gz → 0.11.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.9.0 → trnsparse-0.11.0}/CHANGELOG.md +151 -0
  2. {trnsparse-0.9.0 → trnsparse-0.11.0}/PKG-INFO +3 -1
  3. {trnsparse-0.9.0 → trnsparse-0.11.0}/README.md +2 -0
  4. trnsparse-0.11.0/benchmarks/bench_cg_fused_trn2.py +355 -0
  5. trnsparse-0.11.0/benchmarks/bench_multicore_trn2.py +466 -0
  6. trnsparse-0.11.0/benchmarks/bench_multiproc_trn2.py +130 -0
  7. trnsparse-0.11.0/benchmarks/bench_power_fused_trn2.py +136 -0
  8. {trnsparse-0.9.0 → trnsparse-0.11.0}/docs/api.md +31 -0
  9. trnsparse-0.11.0/docs/benchmarks.md +1021 -0
  10. trnsparse-0.11.0/docs/iterative_solvers.md +248 -0
  11. {trnsparse-0.9.0 → trnsparse-0.11.0}/pyproject.toml +1 -1
  12. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_attention.py +10 -0
  13. trnsparse-0.11.0/tests/test_iterative.py +523 -0
  14. trnsparse-0.11.0/tests/test_multicore.py +231 -0
  15. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_native_dispatch.py +72 -5
  16. trnsparse-0.11.0/tests/test_nki_cg_fused.py +282 -0
  17. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_nki_compile.py +229 -0
  18. trnsparse-0.11.0/tests/test_nki_tail_audit.py +324 -0
  19. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse/__init__.py +9 -1
  20. trnsparse-0.11.0/trnsparse/iterative.py +909 -0
  21. trnsparse-0.11.0/trnsparse/multicore.py +322 -0
  22. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse/nki/_native.py +164 -0
  23. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse/nki/dispatch.py +41 -10
  24. trnsparse-0.11.0/trnsparse/nki/kernels.py +2348 -0
  25. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse/ops.py +10 -0
  26. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse.egg-info/PKG-INFO +3 -1
  27. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse.egg-info/SOURCES.txt +8 -0
  28. trnsparse-0.9.0/docs/benchmarks.md +0 -294
  29. trnsparse-0.9.0/docs/iterative_solvers.md +0 -115
  30. trnsparse-0.9.0/tests/test_iterative.py +0 -226
  31. trnsparse-0.9.0/trnsparse/iterative.py +0 -352
  32. trnsparse-0.9.0/trnsparse/nki/kernels.py +0 -956
  33. {trnsparse-0.9.0 → trnsparse-0.11.0}/.github/workflows/ci.yml +0 -0
  34. {trnsparse-0.9.0 → trnsparse-0.11.0}/.github/workflows/notify-umbrella.yml +0 -0
  35. {trnsparse-0.9.0 → trnsparse-0.11.0}/.github/workflows/publish.yml +0 -0
  36. {trnsparse-0.9.0 → trnsparse-0.11.0}/.gitignore +0 -0
  37. {trnsparse-0.9.0 → trnsparse-0.11.0}/.pre-commit-config.yaml +0 -0
  38. {trnsparse-0.9.0 → trnsparse-0.11.0}/CLAUDE.md +0 -0
  39. {trnsparse-0.9.0 → trnsparse-0.11.0}/CODE_OF_CONDUCT.md +0 -0
  40. {trnsparse-0.9.0 → trnsparse-0.11.0}/CONTRIBUTING.md +0 -0
  41. {trnsparse-0.9.0 → trnsparse-0.11.0}/LICENSE +0 -0
  42. {trnsparse-0.9.0 → trnsparse-0.11.0}/benchmarks/bench_bsr_spmm.py +0 -0
  43. {trnsparse-0.9.0 → trnsparse-0.11.0}/benchmarks/bench_iterative.py +0 -0
  44. {trnsparse-0.9.0 → trnsparse-0.11.0}/benchmarks/bench_native_trn2.py +0 -0
  45. {trnsparse-0.9.0 → trnsparse-0.11.0}/benchmarks/bench_screening.py +0 -0
  46. {trnsparse-0.9.0 → trnsparse-0.11.0}/benchmarks/bench_spmm.py +0 -0
  47. {trnsparse-0.9.0 → trnsparse-0.11.0}/benchmarks/bench_spmv.py +0 -0
  48. {trnsparse-0.9.0 → trnsparse-0.11.0}/benchmarks/conftest.py +0 -0
  49. {trnsparse-0.9.0 → trnsparse-0.11.0}/docs/architecture.md +0 -0
  50. {trnsparse-0.9.0 → trnsparse-0.11.0}/docs/aws_setup.md +0 -0
  51. {trnsparse-0.9.0 → trnsparse-0.11.0}/docs/index.md +0 -0
  52. {trnsparse-0.9.0 → trnsparse-0.11.0}/docs/installation.md +0 -0
  53. {trnsparse-0.9.0 → trnsparse-0.11.0}/docs/migration_scipy.md +0 -0
  54. {trnsparse-0.9.0 → trnsparse-0.11.0}/docs/quickstart.md +0 -0
  55. {trnsparse-0.9.0 → trnsparse-0.11.0}/docs/sparse_attention.md +0 -0
  56. {trnsparse-0.9.0 → trnsparse-0.11.0}/examples/block_sparse_attention.py +0 -0
  57. {trnsparse-0.9.0 → trnsparse-0.11.0}/examples/sparse_fock.py +0 -0
  58. {trnsparse-0.9.0 → trnsparse-0.11.0}/infra/terraform/.terraform.lock.hcl +0 -0
  59. {trnsparse-0.9.0 → trnsparse-0.11.0}/infra/terraform/README.md +0 -0
  60. {trnsparse-0.9.0 → trnsparse-0.11.0}/infra/terraform/main.tf +0 -0
  61. {trnsparse-0.9.0 → trnsparse-0.11.0}/mkdocs.yml +0 -0
  62. {trnsparse-0.9.0 → trnsparse-0.11.0}/scripts/bench_to_md.py +0 -0
  63. {trnsparse-0.9.0 → trnsparse-0.11.0}/scripts/run_benchmarks.sh +0 -0
  64. {trnsparse-0.9.0 → trnsparse-0.11.0}/scripts/run_neuron_tests.sh +0 -0
  65. {trnsparse-0.9.0 → trnsparse-0.11.0}/scripts/run_simulator_tests.sh +0 -0
  66. {trnsparse-0.9.0 → trnsparse-0.11.0}/setup.cfg +0 -0
  67. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/conftest.py +0 -0
  68. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_attn_gather.py +0 -0
  69. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_bsr.py +0 -0
  70. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_core_split.py +0 -0
  71. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_examples.py +0 -0
  72. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_formats.py +0 -0
  73. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_nki_attn.py +0 -0
  74. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_nki_bsr.py +0 -0
  75. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_nki_native.py +0 -0
  76. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_nki_screened_spmm.py +0 -0
  77. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_nki_sim.py +0 -0
  78. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_nki_spmm.py +0 -0
  79. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_ops.py +0 -0
  80. {trnsparse-0.9.0 → trnsparse-0.11.0}/tests/test_screening.py +0 -0
  81. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse/formats.py +0 -0
  82. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse/nki/__init__.py +0 -0
  83. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse/nki/_native_attn.py +0 -0
  84. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse/screening.py +0 -0
  85. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse.egg-info/dependency_links.txt +0 -0
  86. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse.egg-info/requires.txt +0 -0
  87. {trnsparse-0.9.0 → trnsparse-0.11.0}/trnsparse.egg-info/top_level.txt +0 -0
@@ -7,6 +7,157 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.11.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: 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).
15
+
16
+ ### Fixed
17
+
18
+ - **`block_sparse_attention_tiled` silently returned zero rows for a partial
19
+ last block** (released 0.6.0 through 0.10.0, PyTorch path). With
20
+ `seq_len % block_size != 0` the query rows past the last whole block were
21
+ left at 0 (seq_len 200, block 128: rows 128-199 zero, max error 0.79). It now
22
+ raises `ValueError` on every backend; partial blocks need -inf key masking,
23
+ not zero padding. `ShardedAttention` raises the same error.
24
+ - `ShardedBSR.gather` (0.10.0) raised a `RuntimeError` from `view` when the row
25
+ count was not a multiple of 128. It now gathers at the padded row count and
26
+ slices back.
27
+
28
+ ### Added
29
+
30
+ - `tests/test_nki_tail_audit.py`: every NKI kernel (CSR and BSR SpMM, screened
31
+ SpMM, attention, fused CG and power iteration) at awkward sizes (1, 127, 129,
32
+ 200, 1000, 4097; odd N; free dims not a multiple of 512) against fp64
33
+ references (trnsci/trnsci#35).
34
+
35
+ #### Fused SBUF-resident CG (#22)
36
+
37
+ - `cg_bsr_fused(A, b, ...)` and `prepare_cg_bsr(A, preconditioner=None |
38
+ "block_jacobi", device=...)` (a reusable `FusedCGOperator`): the whole
39
+ CG or block-Jacobi PCG solve runs in one NKI launch
40
+ (`trnsparse::cg_bsr_keyed`). A's blocks are loaded into SBUF once
41
+ (`TRNSPARSE_CG_SBUF_KIB`, default 160 KiB per partition; any overflow
42
+ streams from HBM inside the loop). Vectors stay in SBUF, dot products
43
+ reduce through PSUM, and an `nl.while_loop` checks convergence on the
44
+ device every `check_every` steps, with masked steps so the iteration
45
+ count is exact. At LNC=2 the two physical cores split the block rows
46
+ and exchange partial dots and halves of p with `sendrecv`. `b` may be
47
+ `(n, R)`: R independent solves share each matmul.
48
+ - Host fallback with the same algorithm (fp64 stays fp64), CPU tests,
49
+ MLIR verify and NEFF compile at LNC=1/2, and hardware tests
50
+ (`tests/test_nki_cg_fused.py`).
51
+ - `benchmarks/bench_cg_fused_trn2.py`: time to tolerance against a
52
+ host-driven loop over the BSR SpMM op, `cg_bsr`, dense aten CG on the
53
+ device, scipy and torch on the CPU, on synthetic block-screened
54
+ Gaussian-overlap matrices.
55
+
56
+ #### Fused CG follow-ups (#22): column matvec, bf16 A, fused power iteration
57
+
58
+ - `cg_bsr_fused(..., matvec="auto" | "row" | "column")`: the
59
+ **vector-stationary ("column") matvec** is the new default for up to 32
60
+ right-hand sides. The vector is the TensorE stationary operand, the
61
+ stored block streams through as the moving operand, and four 32-column
62
+ PE tiles work in turn. Each 16 block rows are then transposed back to
63
+ the column layout on TensorE (bit-exact). That is about 50 ns per
64
+ resident fp32 block against 425 ns for the row form, with the same
65
+ fp32 arithmetic in a different summation order. It needs no relayout
66
+ of the stored blocks. More than 32 right-hand sides keep `"row"`.
67
+ - Two `sendrecv` exchanges per CG step at LNC=2 instead of three. The
68
+ cores swap their rows of r (and z) and then compute r.z, r.r and
69
+ p = z + beta p over the full width, bit-identically on both cores.
70
+ This replaces separate exchanges of the partial dots and of p.
71
+ - `precision="bf16" | "bf16x2"` (opt-in, column matvec, R <= 16): bf16 A,
72
+ or bf16 hi + lo A, with fp32 vectors (split into bf16 hi + lo on the
73
+ device) and fp32 accumulation. The host path emulates both.
74
+ - `power_iteration_bsr_fused(A, v0, max_iter, tol, ...)`
75
+ (`trnsparse::power_bsr_keyed`): power iteration in one launch on the
76
+ same kernel (Rayleigh quotient, device-side stop on |Δλ| < tol, LNC=2
77
+ row split).
78
+ - `benchmarks/bench_cg_fused_trn2.py --matvec row,column,column:bf16,...`
79
+ and `benchmarks/bench_power_fused_trn2.py`.
80
+
81
+ #### Fused CG: fixed per-iteration cost (#22)
82
+
83
+ - Plain CG at LNC=2 exchanges **once per step**: the cores swap their rows
84
+ of q = A p and then compute p.q, r, r.r and p over the full width,
85
+ bit-identically. PCG still exchanges twice, but the second exchange
86
+ carries z with the partial r.z and r.r. Full-width vectors use a
87
+ segment layout (each core's rows contiguous), so every exchange is one
88
+ `sendrecv` with no copies, and exchanges up to 1 KiB per partition use
89
+ GpSimd's SBUF-to-SBUF DMA (about 0.9 µs against 2.4 µs).
90
+ - Column matvec: "spread" source vectors (each block column after
91
+ (G - 1) R zero columns) put up to 4 G block rows into one PSUM slot, so
92
+ a chunk takes one PSUM-to-SBUF copy and one TensorE transpose instead of
93
+ one of each per four rows (fp32 A, R in 1, 2, 4, 8).
94
+ - `cg_row_order`: each core's block rows are reordered so the four
95
+ concurrent TensorE column groups carry about the same number of blocks
96
+ (b, x0 and x are permuted by DMA in the kernel).
97
+ - Shorter step-size chain (no `max` before the reciprocal of p.Ap; r.z x
98
+ act formed off the critical path), the x update deferred into the next
99
+ matvec, the all-ones reduction matmul flagged `is_stationary_onezero`.
100
+ - PSUM tiles are allocated once per trip of the device loop and re-zeroed,
101
+ so NKI's allocator no longer falls back to neuronx-cc allocation and
102
+ scheduling.
103
+ - `cg_bsr_fused(..., recurrence="chronopoulos_gear")` (opt-in, plain CG):
104
+ the Chronopoulos–Gear recurrence, one reduction phase per step. The host
105
+ path runs the same recurrence.
106
+ - Measured on Trn2 (#22, `docs/benchmarks.md`): the fixed cost per plain
107
+ CG iteration falls from about 11 µs to about 4 µs at LNC=2 and from about
108
+ 8 µs to about 3.5 µs at LNC=1.
109
+
110
+ ### Fixed
111
+
112
+ - `cg_bsr_fused` / `power_iteration_bsr_fused` with a host `BSRMatrix` and
113
+ `b` (or `v0`) on the `neuron` device raised `ModuleNotFoundError:
114
+ torch_neuronx.pyhlo`: the kernel got host tensors and NKI fell back to
115
+ its torch-xla framework (#42). A `BSRMatrix` is now prepared on b's
116
+ device, and the fused kernel runs only for an operator on a `neuron`
117
+ device (a host operator takes the host path).
118
+
119
+ ## [0.10.0] — 2026-10-31
120
+
121
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
122
+
123
+ Headline: pre-transposed static BSR SpMM beats dense aten up to ~82–98% block density on one core (was 26–49%), plus `ShardedBSR`/`ShardedAttention` across logical NeuronCores (#38).
124
+
125
+ ### Added
126
+
127
+ #### Static BSR SpMM and block-sparse attention across logical NeuronCores (#30)
128
+
129
+ - `trnsparse.multicore`: `ShardedBSR` (block rows split across the logical
130
+ cores of a Trn2 chip, balanced by stored blocks), `ShardedAttention`
131
+ (single-head attention forward split by query block rows),
132
+ `partition_block_rows` and `logical_cores`. Per-core operands are built
133
+ on the host and stay resident; one kernel launch per core, issued
134
+ without waiting.
135
+ - Pre-transposed BSR kernel (`bsr_spmm_t_keyed`, the `ShardedBSR`
136
+ default). The blocks are stored transposed, side by side, so the kernel
137
+ needs no in-kernel `load_transpose2d`. It loads up to 16 of a row's
138
+ blocks per DMA, reads PSUM out with one copy, and shares each B tile
139
+ across groups of up to 8 block rows, one PSUM bank each
140
+ (`TRNSPARSE_ROW_GROUP`). The kernel has autograd.
141
+ - `benchmarks/bench_multicore_trn2.py` (1, 2 and 4 logical cores, against
142
+ dense aten on 1 core and split across cores) and
143
+ `benchmarks/bench_multiproc_trn2.py` (one process per core).
144
+
145
+ ### Changed
146
+
147
+ - The static kernels take their structure as a registered key, a content
148
+ hash (`kernels.register_structure`), instead of int lists. The key
149
+ crosses the custom-op boundary as one int, so the host cost of a launch
150
+ no longer grows with the stored-block count: on Trn2 it was 0.13 ms at
151
+ 41 blocks and 0.67 ms at 2048, and is now about 0.12 ms at any size. The
152
+ public `bsr_spmm` and attention-forward paths use the keyed ops.
153
+ - Native kernels run on the logical core that holds their operands
154
+ (`neuron:k`) instead of always on the default `neuron` device. Operands
155
+ spread over two cores raise an error. TorchNeuron does not copy between
156
+ logical cores: `.to()` returns the tensor still on its old core.
157
+ - Kernel docstrings now give the measured `nl.reciprocal` behaviour:
158
+ about 1.5e-6 relative error in range, but it silently returns 1e7 or 0
159
+ outside roughly |x| in [2^-42, 2^41].
160
+
10
161
  ## [0.9.0] — 2026-10-30
11
162
 
12
163
  Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron; LNC=1 and LNC=2) — see trnsci/trnsci#35.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trnsparse
3
- Version: 0.9.0
3
+ Version: 0.11.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()