trnsparse 0.16.1__tar.gz → 0.18.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 (107) hide show
  1. trnsparse-0.18.0/.github/ISSUE_TEMPLATE/bug_report.md +31 -0
  2. trnsparse-0.18.0/.github/ISSUE_TEMPLATE/feature_request.md +17 -0
  3. {trnsparse-0.16.1 → trnsparse-0.18.0}/CHANGELOG.md +159 -0
  4. {trnsparse-0.16.1 → trnsparse-0.18.0}/CLAUDE.md +5 -0
  5. {trnsparse-0.16.1/trnsparse.egg-info → trnsparse-0.18.0}/PKG-INFO +2 -1
  6. {trnsparse-0.16.1 → trnsparse-0.18.0}/README.md +1 -0
  7. trnsparse-0.18.0/benchmarks/probe_kmv_entries_trn2.py +95 -0
  8. trnsparse-0.18.0/benchmarks/probe_scalare_sqrt_range_trn2.py +63 -0
  9. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/api.md +40 -0
  10. {trnsparse-0.16.1 → trnsparse-0.18.0}/pyproject.toml +1 -1
  11. trnsparse-0.18.0/scripts/conformance_expect.py +65 -0
  12. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/conftest.py +72 -0
  13. trnsparse-0.18.0/tests/fixtures/mlip_graph_tiny.pt +0 -0
  14. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_conformance.py +152 -3
  15. trnsparse-0.18.0/tests/test_device_known.py +78 -0
  16. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_kernel_dtype_guard.py +49 -0
  17. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_kernel_matmul.py +40 -5
  18. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_kernel_matmul_neuron.py +30 -2
  19. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_native_dispatch.py +148 -1
  20. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_compile.py +114 -0
  21. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_kernel_matmul.py +33 -1
  22. trnsparse-0.18.0/tests/test_nki_segment_sim.py +223 -0
  23. trnsparse-0.18.0/tests/test_psum_accumulate_lint.py +318 -0
  24. trnsparse-0.18.0/tests/test_segment.py +815 -0
  25. trnsparse-0.18.0/tests/test_segment_neuron.py +426 -0
  26. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/__init__.py +6 -1
  27. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/kernel_matmul.py +20 -4
  28. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/nki/_native.py +84 -1
  29. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/nki/dispatch.py +55 -0
  30. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/nki/kernels.py +471 -92
  31. trnsparse-0.18.0/trnsparse/segment.py +622 -0
  32. {trnsparse-0.16.1 → trnsparse-0.18.0/trnsparse.egg-info}/PKG-INFO +2 -1
  33. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse.egg-info/SOURCES.txt +12 -0
  34. {trnsparse-0.16.1 → trnsparse-0.18.0}/.github/workflows/ci.yml +0 -0
  35. {trnsparse-0.16.1 → trnsparse-0.18.0}/.github/workflows/notify-umbrella.yml +0 -0
  36. {trnsparse-0.16.1 → trnsparse-0.18.0}/.github/workflows/publish.yml +0 -0
  37. {trnsparse-0.16.1 → trnsparse-0.18.0}/.gitignore +0 -0
  38. {trnsparse-0.16.1 → trnsparse-0.18.0}/.pre-commit-config.yaml +0 -0
  39. {trnsparse-0.16.1 → trnsparse-0.18.0}/CODE_OF_CONDUCT.md +0 -0
  40. {trnsparse-0.16.1 → trnsparse-0.18.0}/CONTRIBUTING.md +0 -0
  41. {trnsparse-0.16.1 → trnsparse-0.18.0}/LICENSE +0 -0
  42. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_bsr_spmm.py +0 -0
  43. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_cg_fused_trn2.py +0 -0
  44. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_iterative.py +0 -0
  45. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_kernel_matmul_trn2.py +0 -0
  46. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_multicore_trn2.py +0 -0
  47. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_multiproc_trn2.py +0 -0
  48. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_native_trn2.py +0 -0
  49. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_power_fused_trn2.py +0 -0
  50. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_screened_tiles_trn2.py +0 -0
  51. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_screening.py +0 -0
  52. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_spmm.py +0 -0
  53. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/bench_spmv.py +0 -0
  54. {trnsparse-0.16.1 → trnsparse-0.18.0}/benchmarks/conftest.py +0 -0
  55. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/architecture.md +0 -0
  56. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/aws_setup.md +0 -0
  57. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/benchmarks.md +0 -0
  58. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/index.md +0 -0
  59. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/installation.md +0 -0
  60. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/iterative_solvers.md +0 -0
  61. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/migration_scipy.md +0 -0
  62. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/quickstart.md +0 -0
  63. {trnsparse-0.16.1 → trnsparse-0.18.0}/docs/sparse_attention.md +0 -0
  64. {trnsparse-0.16.1 → trnsparse-0.18.0}/examples/block_sparse_attention.py +0 -0
  65. {trnsparse-0.16.1 → trnsparse-0.18.0}/examples/sparse_fock.py +0 -0
  66. {trnsparse-0.16.1 → trnsparse-0.18.0}/infra/terraform/.terraform.lock.hcl +0 -0
  67. {trnsparse-0.16.1 → trnsparse-0.18.0}/infra/terraform/README.md +0 -0
  68. {trnsparse-0.16.1 → trnsparse-0.18.0}/infra/terraform/main.tf +0 -0
  69. {trnsparse-0.16.1 → trnsparse-0.18.0}/mkdocs.yml +0 -0
  70. {trnsparse-0.16.1 → trnsparse-0.18.0}/scripts/bench_eager_handle.py +0 -0
  71. {trnsparse-0.16.1 → trnsparse-0.18.0}/scripts/bench_to_md.py +0 -0
  72. {trnsparse-0.16.1 → trnsparse-0.18.0}/scripts/run_benchmarks.sh +0 -0
  73. {trnsparse-0.16.1 → trnsparse-0.18.0}/scripts/run_neuron_tests.sh +0 -0
  74. {trnsparse-0.16.1 → trnsparse-0.18.0}/scripts/run_simulator_tests.sh +0 -0
  75. {trnsparse-0.16.1 → trnsparse-0.18.0}/setup.cfg +0 -0
  76. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_attention.py +0 -0
  77. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_attn_gather.py +0 -0
  78. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_bsr.py +0 -0
  79. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_cg_bsr_reduction.py +0 -0
  80. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_cg_span.py +0 -0
  81. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_core_split.py +0 -0
  82. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_examples.py +0 -0
  83. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_formats.py +0 -0
  84. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_iterative.py +0 -0
  85. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_multicore.py +0 -0
  86. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_attn.py +0 -0
  87. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_bsr.py +0 -0
  88. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_cg_fused.py +0 -0
  89. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_native.py +0 -0
  90. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_screened_spmm.py +0 -0
  91. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_sim.py +0 -0
  92. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_spmm.py +0 -0
  93. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_nki_tail_audit.py +0 -0
  94. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_ops.py +0 -0
  95. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_screening.py +0 -0
  96. {trnsparse-0.16.1 → trnsparse-0.18.0}/tests/test_trace_cache_safety.py +0 -0
  97. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/_reduce.py +0 -0
  98. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/formats.py +0 -0
  99. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/iterative.py +0 -0
  100. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/multicore.py +0 -0
  101. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/nki/__init__.py +0 -0
  102. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/nki/_native_attn.py +0 -0
  103. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/ops.py +0 -0
  104. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse/screening.py +0 -0
  105. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse.egg-info/dependency_links.txt +0 -0
  106. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse.egg-info/requires.txt +0 -0
  107. {trnsparse-0.16.1 → trnsparse-0.18.0}/trnsparse.egg-info/top_level.txt +0 -0
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: Bug report
3
+ about: Report a bug in trnfft
4
+ labels: bug
5
+ ---
6
+
7
+ ## Environment
8
+
9
+ - trnfft version:
10
+ - Python version:
11
+ - PyTorch version:
12
+ - Hardware: CPU / trn1 / trn2 / inf2
13
+ - OS:
14
+
15
+ ## Description
16
+
17
+ What happened?
18
+
19
+ ## Steps to reproduce
20
+
21
+ ```python
22
+ # Minimal code to reproduce
23
+ ```
24
+
25
+ ## Expected behavior
26
+
27
+ What should have happened?
28
+
29
+ ## Actual behavior
30
+
31
+ What happened instead? Include error messages/tracebacks if applicable.
@@ -0,0 +1,17 @@
1
+ ---
2
+ name: Feature request
3
+ about: Suggest a new feature or enhancement
4
+ labels: enhancement
5
+ ---
6
+
7
+ ## Description
8
+
9
+ What feature would you like?
10
+
11
+ ## Motivation
12
+
13
+ Why is this needed? What problem does it solve?
14
+
15
+ ## Alternatives considered
16
+
17
+ Any other approaches you've thought about?
@@ -7,6 +7,151 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.18.0] — 2026-11-28
11
+
12
+ ### Fixed
13
+
14
+ - **PSUM accumulation groups now open with a matmul write
15
+ (trnsci/trnsci#185).** The kernels zeroed their fp32 PSUM accumulators
16
+ with `nl.zeros(..., buffer=nl.psum)` or a PSUM `memset` and then
17
+ accumulated with `nc_matmul(..., accumulate=True)`. The `nc_matmul`
18
+ documentation calls a matmul accumulating onto PSUM that a non-matmul
19
+ instruction initialised undefined behaviour on NeuronCore-v3 (Trn2): the
20
+ first matmul into a PSUM location must use `accumulate=False`. Device
21
+ results have matched references so far, but the pattern could break with a
22
+ compiler or runtime change. Now the first matmul of each group overwrites
23
+ (`accumulate=False`, or `accumulate=k > 0` over a Python `range`) in the
24
+ dense, BSR, screened and pre-transposed SpMM kernels, the screened-tile and
25
+ row-group kernels, and the gather and static attention kernels (forward and
26
+ backward). An accumulator is zeroed only when no matmul writes it (an
27
+ empty padded group). The fused CG / power-iteration matvec tiles hold many
28
+ groups (one per block row, interleaved, overlapping in the spread layout,
29
+ none for an empty row), so a matmul of bf16 zeros (one partition) now
30
+ zeroes each tile instead of the memset, one extra TensorE instruction per
31
+ matvec PSUM tile; the partition-sum dot products, one matmul each, now
32
+ overwrite instead. The GP kernel-matmul (`kernel_matmul`) tiles and
33
+ `segment_sum` already opened their groups with `accumulate=False` and are
34
+ unchanged. Simulator outputs are bitwise equal to the previous ones at
35
+ every simulator test shape. `tests/test_psum_accumulate_lint.py` fails on
36
+ the pattern.
37
+
38
+ - **`test_feature_chunks_bitwise` no longer depends on the CI host's CPU
39
+ (#146).** The simulator runs `nc_matmul` as `np.matmul`, and OpenBLAS
40
+ picks its sgemm kernel by CPU. On some kernels the fp32 sum order for a
41
+ column changes with the matrix width, so the unaligned 700-column chunks
42
+ (512 + 188-column matmuls) were not bitwise equal to one launch. The test
43
+ then failed on some runners only. The unaligned case now uses integer
44
+ messages, whose fp32 sums are exact in any order. The aligned case still
45
+ uses random messages, since its matmul shapes match one launch's. Library
46
+ code and hardware results are unchanged.
47
+
48
+ ## [0.17.0] — 2026-11-25
49
+
50
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.1, native TorchNeuron) — see trnsci/trnsci#35.
51
+
52
+ Headline: the graph segment sum and row gather, `segment_sum` / `gather` / `segment_plan`, as deterministic TensorEngine kernels with registered backwards for the MLIP exemplar (#139, #140); they stay on the kernel past 2^31 bytes per call, with a padding mask for compile buckets (#141, #144). `kernel_matmul` / `KernelOperator` make the square operator's diagonal exact (#143), and the fused CG normaliser uses GpSimd rsqrt (trnsci/trnsci#173).
53
+
54
+ ### Added
55
+
56
+ - **`segment_sum` / `gather`: the MLIP layer-1 width stays on the kernel
57
+ from 4096 atoms up (#141).** #140 sent any operand above 2^31 bytes to
58
+ device aten `index_add_` / `index_select`, which fail on trn2 at the
59
+ 4096-atom shape (E = 229376, F = 5120: 4.7e9 bytes). On trn2 one kernel
60
+ launch is correct far past 2^31 bytes: bitwise equal to 2^31-byte chunks at
61
+ 4.7e9 bytes, and equal to the fp64 sum at 9.4e9 bytes (8000 atoms). The
62
+ per-launch bound is now 2^34 bytes. Wider calls split the feature axis,
63
+ one launch per chunk (a multiple of the kernel's 2048-column group, or of a
64
+ 512-column PSUM bank, when that wide) over the same plan. Columns are
65
+ independent, so a split call is bitwise equal to one launch. Chunks are cut
66
+ from row blocks of at most 2^31 bytes, because device aten copies a column
67
+ slice of a larger view about 170x slower.
68
+ - **`segment_plan(idx, N, padding=mask)` (#141).** Edges marked in the mask
69
+ (padding to a compile bucket) take no slots and are skipped by every sum
70
+ over the plan. The slot count and the sums are those of the real edges
71
+ alone, bitwise, wherever the padding points; NaN padding messages are never
72
+ read. Before, padding piled on one segment raised every tile's slot count
73
+ (56 to 72 at 1728 atoms, 2.9x at 8000).
74
+
75
+ - **`segment_sum(m, idx, N)` / `gather(h, idx)`: the graph segment sum
76
+ (index-add) and row gather, each registered as the other's backward
77
+ (#139).** This is the graph block of the MLIP exemplar
78
+ (trnsci/trnsci#170), with MACE's `scatter_sum` semantics. Indices are
79
+ int64 (or int32), sorted or not. `segment_plan(idx, N)` sorts the edges by
80
+ segment once on the host (stable, int64) and builds the kernel layout. Pass
81
+ it as `plan=` for every call over that neighbour list.
82
+ - pytorch backend (the reference): `index_add_` / `index_select`, bitwise
83
+ equal to the exemplar's reference blocks on the CPU.
84
+ - NKI: two new kernels, `_segment_sum_kernel` and `_gather_rows_kernel`, as
85
+ the `trnsparse::segment_sum_tiles` / `trnsparse::gather_rows` custom ops
86
+ with `register_autograd`. Each 128-row output tile is a TensorEngine
87
+ reduction: a 0/1 incidence tile (an iota compare) times 128 message rows
88
+ gathered by indirect DMA. Products accumulate in fp32 PSUM over 8-slot
89
+ chunks, and the chunks add in fp32 SBUF in order. No atomics and no
90
+ scatter-add. The order is fixed by the plan, and tiles split between the
91
+ physical cores with one writer each, so results are bitwise identical run
92
+ to run and at LNC=1 / LNC=2 (confirmed on trn2, #140).
93
+ - The gather kernel batches its indirect DMAs (a 2-D `vector_offset`):
94
+ each DMA moves up to 32 × 128 rows, and the plan stores the gather index
95
+ table in that block order. Blocks of 32, 16, 8, 4, 2 and 1 columns of 128
96
+ edges cover the padded edge count, with no extra padding. With one DMA per
97
+ 128 rows, the gather took about 6.5 ms at the 1728-atom shape (F = 1) on
98
+ trn2, 6× slower than aten `index_select`, because descriptor generation
99
+ bounds it at about 7 µs per DMA. Batched, it takes 0.49 ms, against
100
+ 1.07 ms for `index_select` (#140).
101
+ - Index safety (aws-neuron-sdk#1466, #1467, #1468): index arithmetic stays
102
+ on the host in int64. The device sees int32 edge and row ids, moved by
103
+ DMA unconverted, and fp32 row offsets in [-1, 127]. There is no
104
+ flattened E·F or N·F index. Mostly empty tile ranges (such as
105
+ N = 2^24 + 3 with six edges) use a compact layout: only occupied tiles
106
+ are computed, and the rest are zero-filled.
107
+ - Rolled loops: the traced program does not grow with E. The CPU NEFF
108
+ compile takes about 4 s at the 1728-atom shape, the same as at 16 atoms.
109
+ - Not on the host densify path: `spmm` over an incidence matrix densifies
110
+ on the host and is unusable at 1728 atoms.
111
+ - fp64 follows the suite policy (#84). Inputs above 2^31 bytes per launch
112
+ split the feature axis (#141).
113
+ - Tests:
114
+ - CPU (`tests/test_segment.py`): a vendored slice of the exemplar's
115
+ MACE-MP-0b2 capture (`tests/fixtures/mlip_graph_tiny.pt`), fp64
116
+ gradcheck, the plan layout emulated in torch, index values above 2^24
117
+ and E·F above 2^24.
118
+ - Native ops on CPU (`tests/test_native_dispatch.py`).
119
+ - Simulator (`tests/test_nki_segment_sim.py`).
120
+ - MLIR verify and NEFF compile for every exemplar width (trn1, trn2,
121
+ LNC 1 / 2).
122
+ - Conformance cases.
123
+ - Neuron (`tests/test_segment_neuron.py`): the 216- and 1728-atom
124
+ shapes, determinism with an LNC dump / compare, more than 2^24 edges,
125
+ the exemplar checker, and a timing harness against aten `index_add_`
126
+ / `scatter_add_` / `index_select`.
127
+
128
+ ### Fixed
129
+
130
+ - **`kernel_matmul` / `KernelOperator`: the square operator's diagonal is
131
+ exact, K_ii = s, on every path (#143).** The distance expansion leaves
132
+ D_ii = |x|² + |x|² − 2 x·x at about u·2|x|² instead of 0. Matérn-1/2's
133
+ cusp at r = 0 turned that into sqrt(u·a·2|x|²) relative error in K_ii:
134
+ 6.5e-4 relative on the trn2 bench (n = 131072, ℓ = 0.05), and about
135
+ 3e-3 on single entries. The PyTorch path, the float64 reference and
136
+ `KernelOperator.rows` now zero D_ii. The NKI kernel adds
137
+ (s − K̃_ii)·V_i to each output row. It recomputes K̃_ii with the main
138
+ loop's instructions, then takes the diagonal with `affine_select`, so the
139
+ off-diagonal entries are unchanged bit for bit. The Matérn-1/2 bench error
140
+ drops to 1.4e-5, and the cost is under 0.5% of throughput. `params`
141
+ column 3 now carries s. Matérn-1/2 square-operator tolerances are
142
+ fp32-class again (2e-5 on the PyTorch path, 5e-6 in the simulator).
143
+ - **Fused CG power-iteration normaliser: GpSimd rsqrt instead of ScalarE
144
+ sqrt + reciprocal (trnsci/trnsci#173).** ScalarE sqrt is accurate (8.4e-7)
145
+ only for inputs in [2^-52, 2^52], and reaches 6.2e-3 above 2^92. The
146
+ normaliser's input is a squared norm of any size. GpSimd rsqrt is 1.1e-7
147
+ over the whole fp32 range.
148
+ - The Matérn tiles keep ScalarE sqrt (trnsci/trnsci#173, measured on trn2).
149
+ Their arguments sit in its accurate range, so per-entry error is ≤ 8e-6,
150
+ the same as the GpSimd alternatives at the entry level. The alternatives
151
+ cost 12–30% (rsqrt) to 96% (`power`) of the throughput. New probes:
152
+ `benchmarks/probe_kmv_entries_trn2.py` (per-entry kernel accuracy) and
153
+ `benchmarks/probe_scalare_sqrt_range_trn2.py` (sqrt error by input range).
154
+
10
155
  ## [0.16.1] — 2026-11-10
11
156
 
12
157
  Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
@@ -24,6 +169,20 @@ Headline: from_dense on the neuron device returns correct indices and values abo
24
169
  device in row blocks whose flat indices stay below 2^23 (a device
25
170
  `index_select` at indices above 2^24 is rounded as well).
26
171
  `BSRMatrix.from_dense` takes its block indices from the host mask too.
172
+ ### Added
173
+
174
+ - Tests: device conformance runs are signal-only (trnsci/trnsci#35). Under
175
+ `--backend nki --conformance-device neuron`, the four known device
176
+ categories are marked `xfail(strict=False)` at run time by rule, each with
177
+ its tracking issue: complex `aten.mv` unsupported on device (#130, 64
178
+ cases), device float64 at fp32 precision (#137, 12), `test_cg_bsr`
179
+ `dense_inverse` host `M` with a device `b` (#131, 8, test-side) and the fp16
180
+ `screened_spmm` mask ulp flip (#132, 1, test-side). CPU runs are unmarked.
181
+ A case that starts passing shows as XPASS. A device run prints passed,
182
+ xfailed / XPASS by category and NEW failures; `--conformance-json PATH`
183
+ writes the summary, and `scripts/conformance_expect.py` merges chunked
184
+ runs (exit 1 on NEW failures). `tests/test_device_known.py` checks the rules
185
+ on CPU.
27
186
 
28
187
  ## [0.16.0] — 2026-11-10
29
188
 
@@ -25,6 +25,7 @@ trnsparse/
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
27
  │ ├── kernel_matmul.py # kernel_matmul, KernelOperator: fused K(X, Y) @ V, K never formed (#93)
28
+ │ ├── segment.py # segment_sum / gather / SegmentPlan: graph scatter-gather pair (#139)
28
29
  │ └── nki/
29
30
  │ ├── __init__.py
30
31
  │ ├── kernels.py # _bsr_spmm_kernel, _screened_spmm_kernel, attention kernels
@@ -57,6 +58,10 @@ sizes go straight to the PyTorch path (raise under `TRNSPARSE_REQUIRE_NKI`).
57
58
  `seq_len` must be a multiple of the block size.
58
59
  5. `cg_bsr_fused` / `power_iteration_bsr_fused` — whole solve in one launch,
59
60
  A SBUF-resident (#22).
61
+ 6. `segment_sum(m, idx, N)` / `gather(h, idx)` — graph segment sum and gather
62
+ (MLIP exemplar, #139). Host plan (stable sort, int64) per neighbour list;
63
+ one-hot incidence tile x gathered rows on TensorE, fp32 PSUM, fixed order.
64
+ Device sees only int32 ids and fp32 offsets in [-1, 127].
60
65
 
61
66
  **Open gaps:** row-bucketing CSR (#15, NKI capability-gated), sharding
62
67
  across chips (#16; within one chip `ShardedBSR` shipped in 0.10.0).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trnsparse
3
- Version: 0.16.1
3
+ Version: 0.18.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
@@ -185,6 +185,7 @@ stats = trnsparse.sparsity_stats(Q)
185
185
  | `jacobi_preconditioner_bsr` | Diagonal preconditioner for `cg_bsr` |
186
186
  | `ShardedBSR` / `ShardedAttention` | BSR SpMM / attention forward split across logical NeuronCores (`trnsparse.multicore`) |
187
187
  | `bsr_diagonal` | Extract main diagonal from BSR matrix |
188
+ | `segment_sum` / `gather` / `segment_plan` | Graph segment sum (index-add) and row gather, each the other's backward; deterministic, int64 indices, safe above 2^24 (MLIP exemplar, #139) |
188
189
  | `block_sparse_attention_tiled` | Two-pass sparse attention, no O(seq²) intermediate, autograd; `seq_len` must be a multiple of the block size |
189
190
  | `schwarz_bounds` | Schwarz screening bounds |
190
191
  | `screen_quartets` | Shell quartet significance mask |
@@ -149,6 +149,7 @@ stats = trnsparse.sparsity_stats(Q)
149
149
  | `jacobi_preconditioner_bsr` | Diagonal preconditioner for `cg_bsr` |
150
150
  | `ShardedBSR` / `ShardedAttention` | BSR SpMM / attention forward split across logical NeuronCores (`trnsparse.multicore`) |
151
151
  | `bsr_diagonal` | Extract main diagonal from BSR matrix |
152
+ | `segment_sum` / `gather` / `segment_plan` | Graph segment sum (index-add) and row gather, each the other's backward; deterministic, int64 indices, safe above 2^24 (MLIP exemplar, #139) |
152
153
  | `block_sparse_attention_tiled` | Two-pass sparse attention, no O(seq²) intermediate, autograd; `seq_len` must be a multiple of the block size |
153
154
  | `schwarz_bounds` | Schwarz screening bounds |
154
155
  | `screen_quartets` | Shell quartet significance mask |
@@ -0,0 +1,95 @@
1
+ """Per-entry accuracy of the fused kernel-matrix tile on the device (trnsci/trnsci#173).
2
+
3
+ Isolates the kernel-function evaluation (sqrt, exp, polynomial) from the
4
+ distance expansion: X and Y lie on a dyadic grid (coordinates k / 16), so
5
+ every term of |x|^2 + |y|^2 - 2 x.y is exact in fp32 and D is exact, and
6
+ V = I (m = 128 columns), so out = K(X, Y) entry by entry with no
7
+ summation rounding. Each entry is compared with float64 k(D).
8
+
9
+ The host centring of `kernel_matmul` is bypassed (it would round the grid):
10
+ the kernel launch is called directly with the scale coefficient `a` as a
11
+ kernel argument (powers of two, so a * D is exact too).
12
+
13
+ Usage (on the device):
14
+ python benchmarks/probe_kmv_entries_trn2.py [--n 4096] [--a 1,16] [--json out.json]
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+
22
+ import numpy as np
23
+ import torch
24
+
25
+ from trnsparse.kernel_matmul import _params
26
+ from trnsparse.nki import dispatch as _d
27
+ from trnsparse.nki.kernels import _KMV_KINDS, kmv_group
28
+
29
+
30
+ def _grid(rng, n, d):
31
+ return (rng.integers(-16, 17, size=(n, d)) / 16.0).astype(np.float32)
32
+
33
+
34
+ def _ref(kind, D, a):
35
+ if kind == 0:
36
+ return np.exp(a * D)
37
+ t = np.sqrt(a * D)
38
+ e = np.exp(-t)
39
+ return [None, e, (1 + t) * e, (1 + t + t * t / 3) * e][kind]
40
+
41
+
42
+ def main():
43
+ ap = argparse.ArgumentParser()
44
+ ap.add_argument("--n", type=int, default=4096)
45
+ ap.add_argument("--d", type=int, default=3)
46
+ ap.add_argument("--a", default="1,16", help="Matern a values (rbf uses -a / 2)")
47
+ ap.add_argument("--kinds", default=",".join(_KMV_KINDS))
48
+ ap.add_argument("--json", default=None)
49
+ ap.add_argument("--sim", action="store_true", help="NKI simulator on the host")
50
+ args = ap.parse_args()
51
+ rng = np.random.default_rng(0)
52
+ m = 128
53
+ X = _grid(rng, args.n, args.d)
54
+ Y = _grid(rng, m, args.d)
55
+ D = ((X[:, None, :].astype(np.float64) - Y[None, :, :]) ** 2).sum(-1)
56
+ V = torch.eye(m, dtype=torch.float32)
57
+ dev = "cpu" if args.sim else "neuron"
58
+ xd, yd, vd = (torch.from_numpy(X).to(dev), torch.from_numpy(Y).to(dev), V.to(dev))
59
+ rows = []
60
+ print(f"n={args.n} m={m} d={args.d}")
61
+ print(f"{'kernel':>9} {'a':>5} {'max_rel':>9} {'p99.9':>9} {'median':>9} {'k>=1e-3 max':>11}")
62
+ for name in args.kinds.split(","):
63
+ kind = _KMV_KINDS.index(name)
64
+ for a in (float(v) for v in args.a.split(",")):
65
+ aa = -0.5 * a if kind == 0 else a
66
+ prm = _params(aa, 1.0, 0.0, dev)
67
+ out = _d._kmv_launch(xd, yd, vd, None, prm, kind, kmv_group(m), args.sim).cpu()
68
+ got = out.double().numpy()
69
+ ref = _ref(kind, D, aa)
70
+ ok = ref > 1e-30
71
+ rel = np.abs(got - ref)[ok] / ref[ok]
72
+ big = ref >= 1e-3
73
+ rel_big = np.abs(got - ref)[big] / ref[big]
74
+ rec = {
75
+ "kernel": name,
76
+ "a": a,
77
+ "max_rel": float(rel.max()),
78
+ "p999_rel": float(np.quantile(rel, 0.999)),
79
+ "median_rel": float(np.median(rel)),
80
+ "max_rel_k_ge_1e-3": float(rel_big.max()),
81
+ "entries": int(ok.sum()),
82
+ }
83
+ rows.append(rec)
84
+ print(
85
+ f"{name:>9} {a:>5g} {rec['max_rel']:>9.2e} {rec['p999_rel']:>9.2e} "
86
+ f"{rec['median_rel']:>9.2e} {rec['max_rel_k_ge_1e-3']:>11.2e}",
87
+ flush=True,
88
+ )
89
+ if args.json:
90
+ with open(args.json, "w") as f:
91
+ json.dump(rows, f, indent=1)
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main()
@@ -0,0 +1,63 @@
1
+ """Relative error of ScalarE sqrt and GpSimd rsqrt * x by input range, on the device (trnsci/trnsci#173).
2
+
3
+ One 128 x 2048 tile of fp32 inputs, log-uniform over [2^-124, 2^124],
4
+ through `nisa.activation(sqrt)` (ScalarE) and through
5
+ `tensor_scalar(rsqrt)` on GpSimd times x, against float64 sqrt. Prints the
6
+ overall maximum and the maximum per 8 binades. On Trn2 (SDK 2.33.1) ScalarE
7
+ sqrt is 8.4e-7 relative in [2^-52, 2^52], and its 6.2e-3 worst case is
8
+ above 2^92; GpSimd rsqrt * x is 1.1e-7 everywhere.
9
+
10
+ Usage (on the device):
11
+ python benchmarks/probe_scalare_sqrt_range_trn2.py
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import nki
17
+ import nki.isa as nisa
18
+ import nki.language as nl
19
+ import numpy as np
20
+ import torch
21
+
22
+ _P, _F = 128, 2048
23
+ _LO, _HI, _STEP = -124, 124, 8
24
+
25
+
26
+ @nki.jit
27
+ def _scalare_sqrt(x):
28
+ out = nl.ndarray((_P, _F), dtype=nl.float32, buffer=nl.shared_hbm)
29
+ t = nl.load(x)
30
+ r = nl.ndarray((_P, _F), dtype=nl.float32, buffer=nl.sbuf)
31
+ nisa.activation(r, nl.sqrt, t)
32
+ nl.store(out, value=r)
33
+ return out
34
+
35
+
36
+ @nki.jit
37
+ def _gpsimd_rsqrt_x(x):
38
+ out = nl.ndarray((_P, _F), dtype=nl.float32, buffer=nl.shared_hbm)
39
+ t = nl.load(x)
40
+ r = nl.ndarray((_P, _F), dtype=nl.float32, buffer=nl.sbuf)
41
+ nisa.tensor_scalar(r, t, op0=nl.rsqrt, operand0=0.0, engine=nisa.gpsimd_engine)
42
+ nisa.tensor_tensor(r, t, r, op=nl.multiply)
43
+ nl.store(out, value=r)
44
+ return out
45
+
46
+
47
+ def main():
48
+ rng = np.random.default_rng(0)
49
+ x = np.exp2(rng.uniform(_LO, _HI, size=(_P, _F))).astype(np.float32)
50
+ x64 = x.astype(np.float64)
51
+ ref = np.sqrt(x64)
52
+ e = np.floor(np.log2(x64))
53
+ xd = torch.from_numpy(x).to("neuron")
54
+ for name, kern in (("ScalarE sqrt", _scalare_sqrt), ("GpSimd rsqrt * x", _gpsimd_rsqrt_x)):
55
+ rel = np.abs(kern(xd).cpu().double().numpy() - ref) / ref
56
+ print(f"{name}: max {rel.max():.2e} at x = {x.flat[rel.argmax()]:.3e}")
57
+ for b in range(_LO, _HI, _STEP):
58
+ m = (e >= b) & (e < b + _STEP)
59
+ print(f" [2^{b}, 2^{b + _STEP}): max {rel[m].max():.2e}")
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main()
@@ -46,6 +46,46 @@
46
46
  `jacobi_preconditioner_bsr`, `bsr_diagonal`. See
47
47
  [Iterative solvers](iterative_solvers.md).
48
48
 
49
+ ## Graph segment sum and gather (`segment_sum`, `gather`, #139)
50
+
51
+ The graph block of a message-passing interatomic potential (the MLIP
52
+ exemplar, trnsci/trnsci#170), with MACE's `scatter_sum` semantics.
53
+
54
+ - `segment_sum(m, idx, num_segments, *, plan=None)` — `out[i] = Σ m[e]` over
55
+ the edges with `idx[e] == i`; rows with no edge are 0. `m` is `[E, ...]`,
56
+ `idx` is `[E]` int64 / int32, sorted or not. Backward: `gather`.
57
+ - `gather(h, idx, *, plan=None)` — `out[e] = h[idx[e]]`. Backward:
58
+ `segment_sum`.
59
+ - `segment_plan(idx, num_segments, *, padding=None)` → `SegmentPlan` — sorts
60
+ the edges by segment once on the host (stable, int64) and builds the
61
+ kernel's tile layout. Build one per neighbour list (senders and receivers
62
+ each) and pass it as `plan=`; `.to(device)` stages its tables.
63
+ - `padding`: an `[E]` bool mask of the edges that pad E to a compile
64
+ bucket. Padded edges take no slots, and every sum the plan computes skips
65
+ them: `segment_sum` ignores `m` there, and so does the backward of
66
+ `gather`. `gather` and the backward of `segment_sum` still fill padded
67
+ rows (with `h[idx[e]]` / `grad[idx[e]]`). The sums are bitwise those of
68
+ the plan over the real edges alone, wherever the padding points, on
69
+ every backend. Without a mask, padding edges are ordinary edges: give
70
+ them zero messages and spread them over segments 0, 1, 2, …, since
71
+ piling them on one segment raises the slot count of every tile (#141).
72
+
73
+ Backends: `pytorch` is the reference (`index_add_` / `index_select`;
74
+ deterministic on the CPU). On NKI, the `trnsparse::segment_sum_tiles` and
75
+ `trnsparse::gather_rows` ops (each registered as the other's backward)
76
+ reduce each 128-row tile on the TensorEngine: a 0/1 incidence tile times
77
+ 128 gathered message rows per `nc_matmul`, fp32 PSUM accumulation, in an
78
+ order fixed by the plan. Results are bitwise identical run to run and at
79
+ LNC=1 and LNC=2. No index is computed on the device or passes through fp32,
80
+ and there is no flattened `E·F` / `N·F` index (aws-neuron-sdk#1466, #1467,
81
+ #1468). One launch addresses operands up to 2^34 bytes (8000 atoms at
82
+ F = 5120 is 9.4e9 bytes, verified on trn2, #141); a wider call splits the
83
+ feature axis, one launch per chunk over the same plan, bitwise equal to one
84
+ launch. Size alone no longer sends an fp32 call to device aten, whose
85
+ `index_add_` / `index_select` fail at these sizes. fp64 follows the suite policy (host
86
+ torch under `auto`). See the `trnsparse.segment` module
87
+ docstring for the summation order and limits.
88
+
49
89
  ## Kernel-matrix products (`kernel_matmul`, #93)
50
90
 
51
91
  `K(X, Y) @ V` without forming `K`, for stationary kernels of the distance:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "trnsparse"
7
- version = "0.16.1"
7
+ version = "0.18.0"
8
8
  description = "Sparse matrix operations for AWS Trainium via NKI"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env python3
2
+ """Merge device conformance summaries and list the NEW failures.
3
+
4
+ A device conformance run (``pytest tests/test_conformance.py --backend nki
5
+ --conformance-device neuron``) marks known platform limits as
6
+ ``xfail(strict=False)`` with a ``[device-known:<category>]`` reason, and prints
7
+ a summary at the end. Runs on a Trainium box are split into chunks, so pass
8
+ ``--conformance-json PATH`` to each chunk and merge them here::
9
+
10
+ pytest tests/test_conformance.py --backend nki --conformance-device neuron \\
11
+ -k "<chunk>" --conformance-json chunk1.json
12
+ python scripts/conformance_expect.py chunk*.json
13
+
14
+ Prints passed, xfailed by category, XPASS by category (a known category that
15
+ now passes: a signal, not a failure) and the NEW failures. Exits 1 if there
16
+ are NEW failures, else 0.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import sys
24
+
25
+
26
+ def merge(paths):
27
+ out = {"passed": 0, "skipped": 0, "xfailed": {}, "xpassed": {}, "new_failures": []}
28
+ for p in paths:
29
+ with open(p) as fh:
30
+ s = json.load(fh)
31
+ out["passed"] += s["passed"]
32
+ out["skipped"] += s["skipped"]
33
+ for key in ("xfailed", "xpassed"):
34
+ for cat, ids in s[key].items():
35
+ out[key].setdefault(cat, []).extend(ids)
36
+ out["new_failures"].extend(s["new_failures"])
37
+ return out
38
+
39
+
40
+ def report(s, verbose=False):
41
+ lines = ["conformance expectations (device run)"]
42
+ lines.append(f" passed: {s['passed']} skipped: {s['skipped']}")
43
+ for key, label in (("xfailed", "xfailed"), ("xpassed", "XPASS (known category now passes)")):
44
+ lines.append(f" {label}: {sum(len(v) for v in s[key].values())}")
45
+ for cat, ids in sorted(s[key].items()):
46
+ lines.append(f" {cat}: {len(ids)}")
47
+ if verbose or key == "xpassed":
48
+ lines.extend(f" {i}" for i in ids)
49
+ lines.append(f" NEW failures: {len(s['new_failures'])}")
50
+ lines.extend(f" {i}" for i in s["new_failures"])
51
+ return "\n".join(lines)
52
+
53
+
54
+ def main(argv=None):
55
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
56
+ ap.add_argument("json", nargs="+", help="--conformance-json files from device runs")
57
+ ap.add_argument("-v", "--verbose", action="store_true", help="list xfailed IDs too")
58
+ args = ap.parse_args(argv)
59
+ s = merge(args.json)
60
+ print(report(s, args.verbose))
61
+ return 1 if s["new_failures"] else 0
62
+
63
+
64
+ if __name__ == "__main__":
65
+ sys.exit(main())
@@ -49,6 +49,13 @@ def pytest_addoption(parser):
49
49
  default="cpu",
50
50
  help="device for the dense operands in tests/test_conformance.py (default: cpu)",
51
51
  )
52
+ group.addoption(
53
+ "--conformance-json",
54
+ default=None,
55
+ metavar="PATH",
56
+ help="write the device conformance summary (passed, xfailed/XPASS by category, "
57
+ "NEW failures) as JSON",
58
+ )
52
59
 
53
60
 
54
61
  _FP64_POLICY_MARK = "Trainium computes float64 at fp32 precision"
@@ -76,3 +83,68 @@ def pytest_runtest_makereport(item, call):
76
83
  item.location[1] or 0,
77
84
  "Skipped: float64 raises under TRNSPARSE_REQUIRE_NKI by design (#84)",
78
85
  )
86
+
87
+
88
+ # ---------------------------------------------------------------- device conformance summary
89
+ # Device conformance runs (``--backend nki --conformance-device neuron``) mark
90
+ # known platform limits ``xfail(strict=False)`` at run time, with a reason that
91
+ # starts ``[device-known:<category>]`` (see DEVICE_KNOWN in
92
+ # tests/test_conformance.py). On a non-CPU device run this prints passed,
93
+ # xfailed and XPASS by category, and the NEW failures (anything not expected).
94
+ # ``--conformance-json PATH`` also writes it as JSON; merge the JSON from
95
+ # chunked runs with ``python scripts/conformance_expect.py run1.json ...``.
96
+
97
+ _KNOWN_PREFIX = "[device-known:"
98
+
99
+
100
+ def _expect_category(reason):
101
+ reason = reason or ""
102
+ if reason.startswith(_KNOWN_PREFIX):
103
+ return reason[len(_KNOWN_PREFIX) :].split("]", 1)[0]
104
+ return "other xfail"
105
+
106
+
107
+ def _expect_summary(stats):
108
+ def ids(key):
109
+ return [
110
+ r.nodeid for r in stats.get(key, []) if getattr(r, "when", "call") in ("call", "setup")
111
+ ]
112
+
113
+ by_cat = {}
114
+ for key in ("xfailed", "xpassed"):
115
+ for r in stats.get(key, []):
116
+ cat = _expect_category(getattr(r, "wasxfail", ""))
117
+ by_cat.setdefault(key, {}).setdefault(cat, []).append(r.nodeid)
118
+ return {
119
+ "passed": len(ids("passed")),
120
+ "skipped": len(stats.get("skipped", [])),
121
+ "xfailed": by_cat.get("xfailed", {}),
122
+ "xpassed": by_cat.get("xpassed", {}),
123
+ "new_failures": ids("failed") + [r.nodeid for r in stats.get("error", [])],
124
+ }
125
+
126
+
127
+ def _print_expect_summary(write, s):
128
+ write("conformance expectations (device run)")
129
+ write(f" passed: {s['passed']} skipped: {s['skipped']}")
130
+ for key, label in (("xfailed", "xfailed"), ("xpassed", "XPASS (known category now passes)")):
131
+ total = sum(len(v) for v in s[key].values())
132
+ write(f" {label}: {total}")
133
+ for cat, nodeids in sorted(s[key].items()):
134
+ write(f" {cat}: {len(nodeids)}")
135
+ write(f" NEW failures: {len(s['new_failures'])}")
136
+ for nodeid in s["new_failures"]:
137
+ write(f" {nodeid}")
138
+
139
+
140
+ def pytest_terminal_summary(terminalreporter, exitstatus, config):
141
+ path = config.getoption("--conformance-json", None)
142
+ if config.getoption("--conformance-device", "cpu") == "cpu" and not path:
143
+ return
144
+ s = _expect_summary(terminalreporter.stats)
145
+ _print_expect_summary(lambda line: terminalreporter.write_line(line), s)
146
+ if path:
147
+ import json
148
+
149
+ with open(path, "w") as fh:
150
+ json.dump(s, fh, indent=1)