trnsparse 0.16.0__tar.gz → 0.17.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 (106) hide show
  1. trnsparse-0.17.0/.github/ISSUE_TEMPLATE/bug_report.md +31 -0
  2. trnsparse-0.17.0/.github/ISSUE_TEMPLATE/feature_request.md +17 -0
  3. {trnsparse-0.16.0 → trnsparse-0.17.0}/CHANGELOG.md +139 -0
  4. {trnsparse-0.16.0 → trnsparse-0.17.0}/CLAUDE.md +5 -0
  5. {trnsparse-0.16.0/trnsparse.egg-info → trnsparse-0.17.0}/PKG-INFO +2 -1
  6. {trnsparse-0.16.0 → trnsparse-0.17.0}/README.md +1 -0
  7. trnsparse-0.17.0/benchmarks/probe_kmv_entries_trn2.py +95 -0
  8. trnsparse-0.17.0/benchmarks/probe_scalare_sqrt_range_trn2.py +63 -0
  9. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/api.md +40 -0
  10. {trnsparse-0.16.0 → trnsparse-0.17.0}/pyproject.toml +1 -1
  11. trnsparse-0.17.0/scripts/conformance_expect.py +65 -0
  12. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/conftest.py +72 -0
  13. trnsparse-0.17.0/tests/fixtures/mlip_graph_tiny.pt +0 -0
  14. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_conformance.py +152 -3
  15. trnsparse-0.17.0/tests/test_device_known.py +78 -0
  16. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_formats.py +94 -0
  17. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_kernel_dtype_guard.py +49 -0
  18. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_kernel_matmul.py +40 -5
  19. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_kernel_matmul_neuron.py +30 -2
  20. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_native_dispatch.py +148 -1
  21. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_compile.py +114 -0
  22. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_kernel_matmul.py +33 -1
  23. trnsparse-0.17.0/tests/test_nki_segment_sim.py +212 -0
  24. trnsparse-0.17.0/tests/test_segment.py +815 -0
  25. trnsparse-0.17.0/tests/test_segment_neuron.py +426 -0
  26. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/__init__.py +6 -1
  27. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/formats.py +54 -4
  28. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/kernel_matmul.py +20 -4
  29. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/nki/_native.py +84 -1
  30. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/nki/dispatch.py +55 -0
  31. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/nki/kernels.py +353 -9
  32. trnsparse-0.17.0/trnsparse/segment.py +622 -0
  33. {trnsparse-0.16.0 → trnsparse-0.17.0/trnsparse.egg-info}/PKG-INFO +2 -1
  34. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse.egg-info/SOURCES.txt +11 -0
  35. {trnsparse-0.16.0 → trnsparse-0.17.0}/.github/workflows/ci.yml +0 -0
  36. {trnsparse-0.16.0 → trnsparse-0.17.0}/.github/workflows/notify-umbrella.yml +0 -0
  37. {trnsparse-0.16.0 → trnsparse-0.17.0}/.github/workflows/publish.yml +0 -0
  38. {trnsparse-0.16.0 → trnsparse-0.17.0}/.gitignore +0 -0
  39. {trnsparse-0.16.0 → trnsparse-0.17.0}/.pre-commit-config.yaml +0 -0
  40. {trnsparse-0.16.0 → trnsparse-0.17.0}/CODE_OF_CONDUCT.md +0 -0
  41. {trnsparse-0.16.0 → trnsparse-0.17.0}/CONTRIBUTING.md +0 -0
  42. {trnsparse-0.16.0 → trnsparse-0.17.0}/LICENSE +0 -0
  43. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_bsr_spmm.py +0 -0
  44. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_cg_fused_trn2.py +0 -0
  45. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_iterative.py +0 -0
  46. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_kernel_matmul_trn2.py +0 -0
  47. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_multicore_trn2.py +0 -0
  48. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_multiproc_trn2.py +0 -0
  49. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_native_trn2.py +0 -0
  50. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_power_fused_trn2.py +0 -0
  51. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_screened_tiles_trn2.py +0 -0
  52. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_screening.py +0 -0
  53. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_spmm.py +0 -0
  54. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/bench_spmv.py +0 -0
  55. {trnsparse-0.16.0 → trnsparse-0.17.0}/benchmarks/conftest.py +0 -0
  56. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/architecture.md +0 -0
  57. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/aws_setup.md +0 -0
  58. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/benchmarks.md +0 -0
  59. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/index.md +0 -0
  60. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/installation.md +0 -0
  61. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/iterative_solvers.md +0 -0
  62. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/migration_scipy.md +0 -0
  63. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/quickstart.md +0 -0
  64. {trnsparse-0.16.0 → trnsparse-0.17.0}/docs/sparse_attention.md +0 -0
  65. {trnsparse-0.16.0 → trnsparse-0.17.0}/examples/block_sparse_attention.py +0 -0
  66. {trnsparse-0.16.0 → trnsparse-0.17.0}/examples/sparse_fock.py +0 -0
  67. {trnsparse-0.16.0 → trnsparse-0.17.0}/infra/terraform/.terraform.lock.hcl +0 -0
  68. {trnsparse-0.16.0 → trnsparse-0.17.0}/infra/terraform/README.md +0 -0
  69. {trnsparse-0.16.0 → trnsparse-0.17.0}/infra/terraform/main.tf +0 -0
  70. {trnsparse-0.16.0 → trnsparse-0.17.0}/mkdocs.yml +0 -0
  71. {trnsparse-0.16.0 → trnsparse-0.17.0}/scripts/bench_eager_handle.py +0 -0
  72. {trnsparse-0.16.0 → trnsparse-0.17.0}/scripts/bench_to_md.py +0 -0
  73. {trnsparse-0.16.0 → trnsparse-0.17.0}/scripts/run_benchmarks.sh +0 -0
  74. {trnsparse-0.16.0 → trnsparse-0.17.0}/scripts/run_neuron_tests.sh +0 -0
  75. {trnsparse-0.16.0 → trnsparse-0.17.0}/scripts/run_simulator_tests.sh +0 -0
  76. {trnsparse-0.16.0 → trnsparse-0.17.0}/setup.cfg +0 -0
  77. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_attention.py +0 -0
  78. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_attn_gather.py +0 -0
  79. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_bsr.py +0 -0
  80. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_cg_bsr_reduction.py +0 -0
  81. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_cg_span.py +0 -0
  82. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_core_split.py +0 -0
  83. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_examples.py +0 -0
  84. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_iterative.py +0 -0
  85. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_multicore.py +0 -0
  86. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_attn.py +0 -0
  87. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_bsr.py +0 -0
  88. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_cg_fused.py +0 -0
  89. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_native.py +0 -0
  90. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_screened_spmm.py +0 -0
  91. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_sim.py +0 -0
  92. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_spmm.py +0 -0
  93. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_nki_tail_audit.py +0 -0
  94. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_ops.py +0 -0
  95. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_screening.py +0 -0
  96. {trnsparse-0.16.0 → trnsparse-0.17.0}/tests/test_trace_cache_safety.py +0 -0
  97. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/_reduce.py +0 -0
  98. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/iterative.py +0 -0
  99. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/multicore.py +0 -0
  100. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/nki/__init__.py +0 -0
  101. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/nki/_native_attn.py +0 -0
  102. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/ops.py +0 -0
  103. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse/screening.py +0 -0
  104. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse.egg-info/dependency_links.txt +0 -0
  105. {trnsparse-0.16.0 → trnsparse-0.17.0}/trnsparse.egg-info/requires.txt +0 -0
  106. {trnsparse-0.16.0 → trnsparse-0.17.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,145 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.17.0] — 2026-11-25
11
+
12
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.1, native TorchNeuron) — see trnsci/trnsci#35.
13
+
14
+ 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).
15
+
16
+ ### Added
17
+
18
+ - **`segment_sum` / `gather`: the MLIP layer-1 width stays on the kernel
19
+ from 4096 atoms up (#141).** #140 sent any operand above 2^31 bytes to
20
+ device aten `index_add_` / `index_select`, which fail on trn2 at the
21
+ 4096-atom shape (E = 229376, F = 5120: 4.7e9 bytes). On trn2 one kernel
22
+ launch is correct far past 2^31 bytes: bitwise equal to 2^31-byte chunks at
23
+ 4.7e9 bytes, and equal to the fp64 sum at 9.4e9 bytes (8000 atoms). The
24
+ per-launch bound is now 2^34 bytes. Wider calls split the feature axis,
25
+ one launch per chunk (a multiple of the kernel's 2048-column group, or of a
26
+ 512-column PSUM bank, when that wide) over the same plan. Columns are
27
+ independent, so a split call is bitwise equal to one launch. Chunks are cut
28
+ from row blocks of at most 2^31 bytes, because device aten copies a column
29
+ slice of a larger view about 170x slower.
30
+ - **`segment_plan(idx, N, padding=mask)` (#141).** Edges marked in the mask
31
+ (padding to a compile bucket) take no slots and are skipped by every sum
32
+ over the plan. The slot count and the sums are those of the real edges
33
+ alone, bitwise, wherever the padding points; NaN padding messages are never
34
+ read. Before, padding piled on one segment raised every tile's slot count
35
+ (56 to 72 at 1728 atoms, 2.9x at 8000).
36
+
37
+ - **`segment_sum(m, idx, N)` / `gather(h, idx)`: the graph segment sum
38
+ (index-add) and row gather, each registered as the other's backward
39
+ (#139).** This is the graph block of the MLIP exemplar
40
+ (trnsci/trnsci#170), with MACE's `scatter_sum` semantics. Indices are
41
+ int64 (or int32), sorted or not. `segment_plan(idx, N)` sorts the edges by
42
+ segment once on the host (stable, int64) and builds the kernel layout. Pass
43
+ it as `plan=` for every call over that neighbour list.
44
+ - pytorch backend (the reference): `index_add_` / `index_select`, bitwise
45
+ equal to the exemplar's reference blocks on the CPU.
46
+ - NKI: two new kernels, `_segment_sum_kernel` and `_gather_rows_kernel`, as
47
+ the `trnsparse::segment_sum_tiles` / `trnsparse::gather_rows` custom ops
48
+ with `register_autograd`. Each 128-row output tile is a TensorEngine
49
+ reduction: a 0/1 incidence tile (an iota compare) times 128 message rows
50
+ gathered by indirect DMA. Products accumulate in fp32 PSUM over 8-slot
51
+ chunks, and the chunks add in fp32 SBUF in order. No atomics and no
52
+ scatter-add. The order is fixed by the plan, and tiles split between the
53
+ physical cores with one writer each, so results are bitwise identical run
54
+ to run and at LNC=1 / LNC=2 (confirmed on trn2, #140).
55
+ - The gather kernel batches its indirect DMAs (a 2-D `vector_offset`):
56
+ each DMA moves up to 32 × 128 rows, and the plan stores the gather index
57
+ table in that block order. Blocks of 32, 16, 8, 4, 2 and 1 columns of 128
58
+ edges cover the padded edge count, with no extra padding. With one DMA per
59
+ 128 rows, the gather took about 6.5 ms at the 1728-atom shape (F = 1) on
60
+ trn2, 6× slower than aten `index_select`, because descriptor generation
61
+ bounds it at about 7 µs per DMA. Batched, it takes 0.49 ms, against
62
+ 1.07 ms for `index_select` (#140).
63
+ - Index safety (aws-neuron-sdk#1466, #1467, #1468): index arithmetic stays
64
+ on the host in int64. The device sees int32 edge and row ids, moved by
65
+ DMA unconverted, and fp32 row offsets in [-1, 127]. There is no
66
+ flattened E·F or N·F index. Mostly empty tile ranges (such as
67
+ N = 2^24 + 3 with six edges) use a compact layout: only occupied tiles
68
+ are computed, and the rest are zero-filled.
69
+ - Rolled loops: the traced program does not grow with E. The CPU NEFF
70
+ compile takes about 4 s at the 1728-atom shape, the same as at 16 atoms.
71
+ - Not on the host densify path: `spmm` over an incidence matrix densifies
72
+ on the host and is unusable at 1728 atoms.
73
+ - fp64 follows the suite policy (#84). Inputs above 2^31 bytes per launch
74
+ split the feature axis (#141).
75
+ - Tests:
76
+ - CPU (`tests/test_segment.py`): a vendored slice of the exemplar's
77
+ MACE-MP-0b2 capture (`tests/fixtures/mlip_graph_tiny.pt`), fp64
78
+ gradcheck, the plan layout emulated in torch, index values above 2^24
79
+ and E·F above 2^24.
80
+ - Native ops on CPU (`tests/test_native_dispatch.py`).
81
+ - Simulator (`tests/test_nki_segment_sim.py`).
82
+ - MLIR verify and NEFF compile for every exemplar width (trn1, trn2,
83
+ LNC 1 / 2).
84
+ - Conformance cases.
85
+ - Neuron (`tests/test_segment_neuron.py`): the 216- and 1728-atom
86
+ shapes, determinism with an LNC dump / compare, more than 2^24 edges,
87
+ the exemplar checker, and a timing harness against aten `index_add_`
88
+ / `scatter_add_` / `index_select`.
89
+
90
+ ### Fixed
91
+
92
+ - **`kernel_matmul` / `KernelOperator`: the square operator's diagonal is
93
+ exact, K_ii = s, on every path (#143).** The distance expansion leaves
94
+ D_ii = |x|² + |x|² − 2 x·x at about u·2|x|² instead of 0. Matérn-1/2's
95
+ cusp at r = 0 turned that into sqrt(u·a·2|x|²) relative error in K_ii:
96
+ 6.5e-4 relative on the trn2 bench (n = 131072, ℓ = 0.05), and about
97
+ 3e-3 on single entries. The PyTorch path, the float64 reference and
98
+ `KernelOperator.rows` now zero D_ii. The NKI kernel adds
99
+ (s − K̃_ii)·V_i to each output row. It recomputes K̃_ii with the main
100
+ loop's instructions, then takes the diagonal with `affine_select`, so the
101
+ off-diagonal entries are unchanged bit for bit. The Matérn-1/2 bench error
102
+ drops to 1.4e-5, and the cost is under 0.5% of throughput. `params`
103
+ column 3 now carries s. Matérn-1/2 square-operator tolerances are
104
+ fp32-class again (2e-5 on the PyTorch path, 5e-6 in the simulator).
105
+ - **Fused CG power-iteration normaliser: GpSimd rsqrt instead of ScalarE
106
+ sqrt + reciprocal (trnsci/trnsci#173).** ScalarE sqrt is accurate (8.4e-7)
107
+ only for inputs in [2^-52, 2^52], and reaches 6.2e-3 above 2^92. The
108
+ normaliser's input is a squared norm of any size. GpSimd rsqrt is 1.1e-7
109
+ over the whole fp32 range.
110
+ - The Matérn tiles keep ScalarE sqrt (trnsci/trnsci#173, measured on trn2).
111
+ Their arguments sit in its accurate range, so per-entry error is ≤ 8e-6,
112
+ the same as the GpSimd alternatives at the entry level. The alternatives
113
+ cost 12–30% (rsqrt) to 96% (`power`) of the throughput. New probes:
114
+ `benchmarks/probe_kmv_entries_trn2.py` (per-entry kernel accuracy) and
115
+ `benchmarks/probe_scalare_sqrt_range_trn2.py` (sqrt error by input range).
116
+
117
+ ## [0.16.1] — 2026-11-10
118
+
119
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
120
+
121
+ Headline: from_dense on the neuron device returns correct indices and values above 2^24 elements (silent, #134)
122
+
123
+ ### Fixed
124
+
125
+ - **`from_dense` on the neuron device: wrong column indices and values for
126
+ matrices of more than 2^24 elements** (silent, #134, trnsci/trnsci#135).
127
+ The device `nonzero` / `torch.where` / `A[mask]` round the flat index
128
+ `row * n + col` through fp32 above 2^24: on Trn2 a (2100, 8100) matrix
129
+ with 4002 nonzeros came back with 19 wrong column indices. The indices now
130
+ come from a host `nonzero` of the mask, and the values are gathered on the
131
+ device in row blocks whose flat indices stay below 2^23 (a device
132
+ `index_select` at indices above 2^24 is rounded as well).
133
+ `BSRMatrix.from_dense` takes its block indices from the host mask too.
134
+ ### Added
135
+
136
+ - Tests: device conformance runs are signal-only (trnsci/trnsci#35). Under
137
+ `--backend nki --conformance-device neuron`, the four known device
138
+ categories are marked `xfail(strict=False)` at run time by rule, each with
139
+ its tracking issue: complex `aten.mv` unsupported on device (#130, 64
140
+ cases), device float64 at fp32 precision (#137, 12), `test_cg_bsr`
141
+ `dense_inverse` host `M` with a device `b` (#131, 8, test-side) and the fp16
142
+ `screened_spmm` mask ulp flip (#132, 1, test-side). CPU runs are unmarked.
143
+ A case that starts passing shows as XPASS. A device run prints passed,
144
+ xfailed / XPASS by category and NEW failures; `--conformance-json PATH`
145
+ writes the summary, and `scripts/conformance_expect.py` merges chunked
146
+ runs (exit 1 on NEW failures). `tests/test_device_known.py` checks the rules
147
+ on CPU.
148
+
10
149
  ## [0.16.0] — 2026-11-10
11
150
 
12
151
  Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
@@ -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.0
3
+ Version: 0.17.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.0"
7
+ version = "0.17.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)