trntensor 0.23.0__tar.gz → 0.24.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. {trntensor-0.23.0 → trntensor-0.24.0}/CHANGELOG.md +228 -0
  2. {trntensor-0.23.0/trntensor.egg-info → trntensor-0.24.0}/PKG-INFO +16 -1
  3. {trntensor-0.23.0 → trntensor-0.24.0}/README.md +15 -0
  4. {trntensor-0.23.0 → trntensor-0.24.0}/docs/api/einsum.md +10 -3
  5. {trntensor-0.23.0 → trntensor-0.24.0}/docs/api/nki.md +61 -1
  6. {trntensor-0.23.0 → trntensor-0.24.0}/docs/api/plan.md +1 -1
  7. trntensor-0.24.0/docs/api/stream.md +63 -0
  8. {trntensor-0.23.0 → trntensor-0.24.0}/mkdocs.yml +1 -0
  9. {trntensor-0.23.0 → trntensor-0.24.0}/pyproject.toml +1 -1
  10. trntensor-0.24.0/scripts/bench_eager_handle.py +129 -0
  11. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_conformance.py +55 -20
  12. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_decompose.py +179 -0
  13. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_einsum.py +53 -3
  14. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_host_output.py +2 -2
  15. trntensor-0.24.0/tests/test_kernel_dtype_guard.py +1171 -0
  16. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_native_dispatch.py +337 -16
  17. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_nki_native.py +87 -0
  18. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_plan.py +72 -0
  19. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_quantum.py +90 -0
  20. trntensor-0.24.0/tests/test_stream.py +211 -0
  21. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/__init__.py +15 -1
  22. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/decompose.py +60 -13
  23. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/einsum.py +73 -15
  24. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/nki/_native.py +18 -1
  25. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/nki/collectives.py +5 -0
  26. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/nki/dispatch.py +594 -29
  27. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/parallel.py +13 -0
  28. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/plan.py +7 -1
  29. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/quantum.py +88 -26
  30. trntensor-0.24.0/trntensor/stream.py +552 -0
  31. {trntensor-0.23.0 → trntensor-0.24.0/trntensor.egg-info}/PKG-INFO +16 -1
  32. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor.egg-info/SOURCES.txt +5 -0
  33. {trntensor-0.23.0 → trntensor-0.24.0}/.github/workflows/ci.yml +0 -0
  34. {trntensor-0.23.0 → trntensor-0.24.0}/.github/workflows/notify-umbrella.yml +0 -0
  35. {trntensor-0.23.0 → trntensor-0.24.0}/.github/workflows/publish.yml +0 -0
  36. {trntensor-0.23.0 → trntensor-0.24.0}/.gitignore +0 -0
  37. {trntensor-0.23.0 → trntensor-0.24.0}/.pre-commit-config.yaml +0 -0
  38. {trntensor-0.23.0 → trntensor-0.24.0}/CLAUDE.md +0 -0
  39. {trntensor-0.23.0 → trntensor-0.24.0}/CODE_OF_CONDUCT.md +0 -0
  40. {trntensor-0.23.0 → trntensor-0.24.0}/CONTRIBUTING.md +0 -0
  41. {trntensor-0.23.0 → trntensor-0.24.0}/LICENSE +0 -0
  42. {trntensor-0.23.0 → trntensor-0.24.0}/benchmarks/__init__.py +0 -0
  43. {trntensor-0.23.0 → trntensor-0.24.0}/benchmarks/bench_einsum.py +0 -0
  44. {trntensor-0.23.0 → trntensor-0.24.0}/docs/api/decompose.md +0 -0
  45. {trntensor-0.23.0 → trntensor-0.24.0}/docs/api/index.md +0 -0
  46. {trntensor-0.23.0 → trntensor-0.24.0}/docs/api/quantum.md +0 -0
  47. {trntensor-0.23.0 → trntensor-0.24.0}/docs/architecture.md +0 -0
  48. {trntensor-0.23.0 → trntensor-0.24.0}/docs/aws_setup.md +0 -0
  49. {trntensor-0.23.0 → trntensor-0.24.0}/docs/benchmarks.md +0 -0
  50. {trntensor-0.23.0 → trntensor-0.24.0}/docs/contraction_patterns.md +0 -0
  51. {trntensor-0.23.0 → trntensor-0.24.0}/docs/design/matmul_dispatch_findings.md +0 -0
  52. {trntensor-0.23.0 → trntensor-0.24.0}/docs/design/matmul_kernel_profile.md +0 -0
  53. {trntensor-0.23.0 → trntensor-0.24.0}/docs/developing_kernels.md +0 -0
  54. {trntensor-0.23.0 → trntensor-0.24.0}/docs/index.md +0 -0
  55. {trntensor-0.23.0 → trntensor-0.24.0}/docs/installation.md +0 -0
  56. {trntensor-0.23.0 → trntensor-0.24.0}/docs/quickstart.md +0 -0
  57. {trntensor-0.23.0 → trntensor-0.24.0}/docs/tutorial_df_mp2.md +0 -0
  58. {trntensor-0.23.0 → trntensor-0.24.0}/examples/df_mp2_einsum.py +0 -0
  59. {trntensor-0.23.0 → trntensor-0.24.0}/infra/terraform/README.md +0 -0
  60. {trntensor-0.23.0 → trntensor-0.24.0}/infra/terraform/main.tf +0 -0
  61. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/autotune_dispatch.py +0 -0
  62. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/bench_ao2mo_nocc.py +0 -0
  63. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/bench_native_einsum.py +0 -0
  64. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/bench_native_kernels.py +0 -0
  65. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/bench_to_md.py +0 -0
  66. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/run_benchmarks.sh +0 -0
  67. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/run_neuron_profile.sh +0 -0
  68. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/run_neuron_tests.sh +0 -0
  69. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/run_reduce_parallel_multirank.py +0 -0
  70. {trntensor-0.23.0 → trntensor-0.24.0}/scripts/run_simulator_tests.sh +0 -0
  71. {trntensor-0.23.0 → trntensor-0.24.0}/setup.cfg +0 -0
  72. {trntensor-0.23.0 → trntensor-0.24.0}/tests/conftest.py +0 -0
  73. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_nki.py +0 -0
  74. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_nki_compile.py +0 -0
  75. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_nki_kernels.py +0 -0
  76. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_nki_sim.py +0 -0
  77. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_nki_tail_audit.py +0 -0
  78. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_parallel.py +0 -0
  79. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_sr_runtime.py +0 -0
  80. {trntensor-0.23.0 → trntensor-0.24.0}/tests/test_trace_cache_safety.py +0 -0
  81. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/nki/__init__.py +0 -0
  82. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/nki/_kernels.py +0 -0
  83. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor/py.typed +0 -0
  84. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor.egg-info/dependency_links.txt +0 -0
  85. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor.egg-info/requires.txt +0 -0
  86. {trntensor-0.23.0 → trntensor-0.24.0}/trntensor.egg-info/top_level.txt +0 -0
  87. {trntensor-0.23.0 → trntensor-0.24.0}/uv.lock +0 -0
@@ -7,6 +7,234 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.24.0] — 2026-11-04
11
+
12
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
13
+
14
+ Headline: trntensor.stream.AuxStream for DF integrals streamed over the aux index (#102), cached eager NKI handles, and the trnsci float64 policy with a dtype guard at the kernel boundary.
15
+
16
+ ### Fixed
17
+
18
+ - **`mp2_energy`'s aten route chunks j as well as i (trnsci/trnsci#115).** It
19
+ chunked only the occupied index i. Once one i row of `T` (`nocc · nvir²`)
20
+ exceeded `_MP2_CHUNK_ELEMS`, every step held that whole row, 1.37 GB at
21
+ nocc 161 / nvir 1461 / naux 6064 (C40H82 / aug-cc-pVDZ), plus its temporaries.
22
+ On a 24 GiB Trn2 core, with only the 5.7 GB of `B` resident, the step ran out
23
+ of device memory. Blocks are now at most `_MP2_CHUNK_ELEMS` elements, and the
24
+ same case ran on one core in 222 s.
25
+ ### Changed
26
+
27
+ - **`AuxStream` uploads a memory-mapped chunk to a device straight from the
28
+ mapping (trnsci/trnsci#115).** The sequential read into RAM, added so that
29
+ host row gathers stop faulting pages at random, now runs only for chunks
30
+ computed on the host. On Trn2, a page-cached 1.6 GB chunk went from 2.9 GB/s
31
+ (copy, then upload) to 12–14 GB/s (upload from the mapping). For water61 /
32
+ aug-cc-pVDZ (114.6 GB of B, 49.7 GB streamed per SCF iteration over 4
33
+ cores), the per-iteration upload wait went from 12.5 s to 4.3 s.
34
+ ### Performance
35
+
36
+ - **Eager NKI kernel calls skip the per-call handle rebuild and the custom-op
37
+ layer (same fix as trnblas#92).** On the native path a `trntensor::`
38
+ custom-op call cost about 0.1 ms of host time before the kernel was queued,
39
+ against 0.016 ms for aten. Most of it went to nki's `Kernel.__call__`,
40
+ which rebuilds the torch handle on every call, plus the `torch.library`
41
+ layer. `dispatch._launch` and the `mp2_energy_row` loop now call a
42
+ `torch_neuronx.wrap_nki` handle built once per kernel; compile-time keyword
43
+ arguments (`use_sr`, `nub`, `tp`, `tail`, `banks`) pass through unchanged.
44
+ On trn2 (LNC=2), a 256x128x512 `matmul` launch drops from 0.143 to
45
+ 0.036 ms of issue time (e2e 0.222 to 0.128 ms), `_nki_mp2_energy_rows` with
46
+ nocc=8 from 2.94 to 2.34 ms, and the `df_exchange` kernel pair's issue time
47
+ from 0.78 to 0.36 ms. Results are bit-identical. `torch.compile`,
48
+ requires-grad, int64 and tensor-subclass inputs keep the custom op.
49
+ `TRNTENSOR_NKI_EAGER_HANDLE=0` turns this off;
50
+ `scripts/bench_eager_handle.py` measures it.
51
+
52
+ ### Added
53
+
54
+ - **`trntensor.stream`: DF integrals streamed over the aux index**
55
+ (trnsolver#15). At nbasis 1658 the packed fp32 integrals were 33.4 GB and
56
+ only fit split over a Trn2 chip's 4 logical cores; at nbasis ≈ 3300 they
57
+ are about 270 GB.
58
+ - `AuxStream(chunks, nbasis, devices=..., resident_bytes=..., prefetch=...)`
59
+ holds `B` as `(npair, nq)` aux chunks (tensors, numpy memmaps or lazy
60
+ loaders), keeps chunks resident up to a per-device budget and uploads the
61
+ rest on every call from a loader thread, one chunk ahead per device, so
62
+ uploads overlap compute. `jk()` builds packed J and K in one pass
63
+ (`df_coulomb` / `df_exchange` per chunk, summed per device, then on the
64
+ host); `ao_to_mo()` writes `B_ia^P` chunk by chunk into a host tensor or
65
+ memmap. Chunks are dealt round-robin over `devices` (`neuron:0..3`).
66
+ - `aux_chunk_width` / `split_aux`: 128-multiple chunks under 2 GiB by
67
+ default, below the 4 GiB transposed-LHS limit (aws-neuron-sdk#1457, #97).
68
+ - `pack_density` / `unpack_packed`: the packed-density helpers, for use on
69
+ host tensors at large nbasis (the device gathers compile for > 40 min at
70
+ nbasis 1658, trnsolver#87).
71
+ - `mp2_energy_blocked`: DF-MP2 over occupied blocks of a host `B_ia^P`,
72
+ for `B` larger than one device.
73
+ - Memory-mapped chunks are read into RAM with one sequential read when
74
+ loaded. Left mapped, the row gathers of `df_exchange` fault pages in at
75
+ random, which was disk-bound on a disk-backed store.
76
+ - CPU-validated against dense references; device overlap and scaling are
77
+ still to be measured.
78
+
79
+ ### Changed
80
+
81
+ - **float64 follows the trnsci float64 policy (#92, trnsci/trnsci#35).**
82
+ Trainium computes float64 at fp32 precision, so a float64 operand on a
83
+ kernel route cannot get float64 accuracy there. This applies to the matmul /
84
+ batched-matmul kernels (`einsum`, `multi_einsum`) and to the chemistry
85
+ kernels (`mp2_energy`, `ao_to_mo_transform`, `df_exchange`, `df_coulomb`):
86
+ - **`"auto"`:** float64 under `auto` now computes in torch at float64
87
+ accuracy (previously cast to fp32 on the NKI path). For the chemistry
88
+ kernels the cast came in with #88 and was in 0.23.0. Through 0.22.0
89
+ float64 reached them unchanged and returned inf. torch runs on the
90
+ operands' own device; float64 host operands stay on the host.
91
+ - **Explicit `set_backend("nki")` (or `TRNTENSOR_FORCE_BACKEND=nki`):**
92
+ float64 is cast to fp32, the kernel runs, and the result comes back as
93
+ float64. A one-time `UserWarning` per op says the precision is fp32.
94
+ Through 0.23.0 the chemistry kernels cast without a warning; the matmul
95
+ kernels got float64 operands unchanged.
96
+ - **`TRNTENSOR_REQUIRE_NKI=1`:** float64 on a kernel route raises
97
+ `NotImplementedError` (trnblas#69's convention), under explicit `"nki"`
98
+ and `"auto"` alike. **Callers who ran float64 chemistry inputs under
99
+ `TRNTENSOR_REQUIRE_NKI=1` (0.23.0: the kernel ran in fp32) now get an
100
+ error.** Pass float32 operands to run the kernels, or unset the variable.
101
+ - **Result dtype:** always the pytorch backend's dtype for the same inputs,
102
+ including bf16 / fp16 and mixed-dtype promotion (`torch.promote_types`
103
+ of the operands).
104
+
105
+ - **float64 already on the `neuron` device:** under `"auto"`, "torch on
106
+ the operands' device" would be device aten, which computes float64 at
107
+ fp32 precision (measured on Trn2). float64 / complex128 operands on the
108
+ `neuron` device are now copied to the host, computed in host torch at
109
+ float64 accuracy, and the result is returned on the original device in
110
+ float64 / complex128. This covers `einsum`, `multi_einsum` (which returns
111
+ host tensors, as before), `gather` (device `torch.cat` rounds float64 to
112
+ fp32), `einsum(dtype=float64)` on fp32 / bf16 device operands, the
113
+ chemistry calls and the CP / Tucker / TT
114
+ decompositions and reconstructions. One `UserWarning` per op per process:
115
+ "float64 on the neuron device is computed on the host for float64
116
+ accuracy (device arithmetic is fp32); pass float32 to stay on device".
117
+ **New: `TRNTENSOR_FP64_ON_DEVICE=1`** keeps device aten (fp32 precision,
118
+ no warning) for callers who prefer speed. **Under
119
+ `TRNTENSOR_REQUIRE_NKI=1`, float64 / complex128 on the `neuron` device
120
+ now raises `NotImplementedError` at every guarded entry point** (backends
121
+ `"auto"` and `"nki"`, no host copy, ahead of `TRNTENSOR_FP64_ON_DEVICE`);
122
+ before, only the kernel routes raised, and an `einsum` with no kernel
123
+ route (below the size thresholds, or not a matmul) or a decomposition
124
+ ran device aten at fp32 precision with no error. Host-resident float64 is
125
+ unchanged, and `multi_einsum` no longer pins host float64 / complex128
126
+ operands to the device under `"auto"`; through 0.23.0 shared operands
127
+ were pinned, so device aten computed them at fp32 precision.
128
+ `--backend auto --conformance-device neuron` now holds float64 and
129
+ complex128 to the float64 tolerance.
130
+ The routes that place their own compute follow the same rule:
131
+ `trntensor.stream.AuxStream(..., dtype=float64)` and
132
+ `mp2_energy_blocked` with a `neuron` device in `devices` keep the chunks
133
+ and the arithmetic on the host (results still default to the first
134
+ device given), and `pack_tril` / `unpack_tril` / `pack_density` /
135
+ `unpack_packed` gather float64 / complex128 on the host, because on the
136
+ neuron device both the gather (`index_select`, fancy indexing) and
137
+ `torch.cat` round float64 to fp32 (measured on Trn2, rel err ~4e-8).
138
+
139
+ Affected versions: the old behaviour is 0.23.0 for the chemistry kernels
140
+ (the silent fp32 cast) and 0.23.0 and earlier for the matmul kernels
141
+ (float64 unchanged). The new behaviour lands in the next release (0.24.0).
142
+ Docs: "Precision and dtypes" in `docs/api/nki.md`.
143
+ `tests/test_conformance.py` now holds float64 to the float64 tolerance
144
+ for host inputs under `--backend auto`, as under `pytorch`.
145
+
146
+ ### Fixed
147
+
148
+ - **One dtype guard at the NKI kernel boundary: float64, integer, bool and
149
+ complex operands no longer reach a kernel that does not take them**
150
+ (silent, trnsci/trnsci#35; the class of #87). `nki.dispatch` now has a
151
+ per-kernel operand-dtype table (`KERNEL_OPERAND_DTYPES`). Every launch
152
+ checks it and raises `TypeError` if a dtype is not listed: the native op
153
+ and the eager-handle fast path (`_native_call`), the XLA call, the
154
+ simulator, the `mp2_energy` row loop and the reduce-parallel all-reduce. A native op without an entry cannot be loaded.
155
+ The host wrappers decide first:
156
+ - `einsum` / `multi_einsum` (matmul and batched-matmul kernels; fp32, bf16,
157
+ fp16, one shared dtype): integer, bool, complex and mixed dtypes run
158
+ torch, as the pytorch backend does; float64 follows the policy above.
159
+ Through 0.23.0 they reached the kernels under `set_backend("nki")`, or
160
+ under `"auto"` above the size thresholds.
161
+ - `mp2_energy`, `ao_to_mo_transform` (fp32 / bf16 kernels) and
162
+ `df_exchange`, `df_coulomb` (fp32 kernels): float16 operands, and
163
+ bfloat16 operands of `df_*`, are computed in fp32 (a lossless upcast).
164
+ The result is returned in the aten route's dtype. float64 follows the
165
+ policy above. Integer, bool and complex operands take aten. On the kernel
166
+ route, bf16 `df_coulomb` raised in the host tail whenever `npair` was not
167
+ a multiple of 256, then fell back to aten. Re-allowing bf16 on the `df_*`
168
+ kernels waits on a Trn2 bf16 run (#92).
169
+ - reduce-parallel all-reduce: partials other than fp32 / bf16 / fp16 are
170
+ summed by `torch.distributed` instead of the NKI collective kernel.
171
+ float64 partials are summed there at full precision.
172
+ - Under `TRNTENSOR_REQUIRE_NKI=1`, a dtype that would run torch instead of
173
+ the kernel raises `NotImplementedError` (trnblas's convention).
174
+ The `df_half_packed` op's fake (meta) output is now float32, like the
175
+ kernel's. Test: `tests/test_kernel_dtype_guard.py`.
176
+
177
+ - **`unpack_tril` / `pack_tril` on the neuron device at LNC=1 returned
178
+ wrong data once the gathered output reached 4 GiB (#97).** Affected
179
+ 0.20.0–0.23.0: `unpack_tril`, `pack_tril`, and the packed-`eri` aten /
180
+ legacy routes of `ao_to_mo_transform`, which unpack with `unpack_tril`: on
181
+ the neuron device at LNC=1, one `index_select` along dim 0 whose output
182
+ reaches 2^32 bytes can be silently wrong (about half the elements, at
183
+ times NaN) or hit the runtime's 30 s execution timeout. Measured on Trn2:
184
+ exact at 2^32 − 16 KiB, wrong at exactly 2^32, and 154 M mismatched
185
+ elements for `unpack_tril` at nbasis 736 / naux 2304 (4.99e9 bytes). It
186
+ is exact at LNC=2 and on the host. Device gathers are now split into row blocks of at most
187
+ 2 GiB of output and concatenated in order (exact). Host gathers are one
188
+ `index_select` as before.
189
+ - **Complex `tucker_decompose` on the neuron device used `U^T`, not `U^H`
190
+ (#89).** Affected 0.23.0 (the release that switched the core to
191
+ `factors[mode].mH`, #73): `.mH` of a complex tensor is a lazy conj view,
192
+ and device matmul ignores the conj bit (aws-neuron/aws-neuron-sdk#1455),
193
+ so the core of a device-resident complex tensor was silently computed
194
+ with the unconjugated factors. CPU results were correct. The conjugate
195
+ transpose is now materialized with `resolve_conj()` before the mode
196
+ product, as trnsolver's `factor._mH` does; real input is unchanged (no
197
+ copy). The complex `cp_decompose` added in this release (#103) had the
198
+ same pattern (`V.mH @ V`, `T_mode @ V.conj()`) and is fixed the same way.
199
+ A CPU `TorchFunctionMode` test fails if any lazy conj view reaches a
200
+ matmul, einsum, solve or pinv in either decomposition.
201
+
202
+ - **`cp_decompose` works in the input dtype, including float64 and complex
203
+ (#103).** Affected 0.1.1–0.23.0: the random init and the Khatri-Rao buffer
204
+ were float32 on the host, so float64 or complex input raised `expected m1
205
+ and m2 to have the same dtype` on every backend (and a float64 warm start
206
+ was truncated to float32 inside the Khatri-Rao product). The init, the
207
+ Khatri-Rao buffer and the weights now follow `tensor.dtype` and
208
+ `tensor.device`, warm-start factors are cast to them, and complex input
209
+ uses the conjugated normal equations `(V^H V) A^T = (T_(k) conj(V))^T`.
210
+ Weights are real (`tensor.real.dtype`). `nonneg=True` with complex input
211
+ raises `ValueError`. Real float32 results are bit-identical.
212
+ - **`cp_reconstruct` returns the factors' dtype on the factors' device
213
+ (#78).** Affected 0.1.1–0.23.0: it accumulated into a float32 host buffer
214
+ (`torch.zeros(shape)`), so bf16 or fp16 factors came back as float32 and
215
+ device factors raised a device mismatch. The buffer now has the promoted
216
+ dtype of `factors` and `weights` and the factors' device. float32 and
217
+ float64 results are unchanged.
218
+ - **`plan_contraction` fills `ContractionPlan.estimated_flops` (#83).**
219
+ Affected 0.1.1–0.23.0: the documented multiply-add estimate was never set
220
+ and always read 0. `matmul`, `bmm` and `torch` plans now carry
221
+ `estimate_flops(subscripts, *operands)` (the product of all index sizes);
222
+ `path` plans carry the multiply-adds of the planned binary steps, which is
223
+ what runs and is less than the dense all-index product. Plans are cached by
224
+ shape, so the field is exact for the cached shapes.
225
+ - **`einsum(..., out=)` now writes the result into `out` and returns it
226
+ (#77).** Affected 0.3.0–0.23.0: `out` was only read as the `beta` addend
227
+ and never written, so the documented in-place accumulation example
228
+ `einsum(..., beta=1.0, out=acc)` silently left `acc` unchanged. `out` now
229
+ behaves as in `torch.einsum` and cuTENSOR: it receives
230
+ `alpha * contract + beta * out` (old contents not read when `beta == 0`),
231
+ must have the result's shape (`ValueError` otherwise), must accept the
232
+ result dtype under `torch.can_cast` (`RuntimeError` otherwise), and may
233
+ alias an operand. Like `torch.einsum(out=)`, it raises `RuntimeError` when
234
+ grad mode is on and an operand or `out` requires grad. Callers that reused
235
+ `C` after passing it as `out=C` now see it overwritten; pass `out=C.clone()`
236
+ to keep the old behaviour.
237
+
10
238
  ## [0.23.0] — 2026-11-02
11
239
 
12
240
  Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trntensor
3
- Version: 0.23.0
3
+ Version: 0.24.0
4
4
  Summary: Tensor contractions for AWS Trainium via NKI
5
5
  Author-email: Scott Friedman <scttfrdmn@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -167,6 +167,21 @@ core, factors = trntensor.tucker_decompose(tensor, ranks=(5, 5, 5))
167
167
  - [x] Mixed precision / `dtype` override for bf16/fp16
168
168
  - [x] `precision=` kwarg (`"fast"` / `"kahan"` fp64 promotion / `"sr"` / `"dd"`: CPU emulation only, raises on Trainium until trnblas#22)
169
169
 
170
+ ## Known issues in earlier releases
171
+
172
+ Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details are in the [CHANGELOG](CHANGELOG.md).
173
+
174
+ | Bug | Affected | Fixed in |
175
+ |-----|----------|----------|
176
+ | `einsum` returned the wrong layout for transposed or permuted outputs (e.g. `ij,jk->ki` gave `A@B`), every backend (#64) | through 0.21.0 | 0.22.0 |
177
+ | `einsum(..., out=C)` with `beta=0` read `C`, so NaN/inf in it made the result NaN (#71) | 0.3.0–0.22.0 | 0.23.0 |
178
+ | `tucker_decompose` used `Uᵀ` instead of `Uᴴ` for complex tensors, giving a wrong core (#73) | through 0.22.0 | 0.23.0 |
179
+ | `precision="kahan"` / `"dd"` / `target_forward_error` dropped the imaginary part of complex operands and rounded large integers (#69) | `"kahan"` 0.4.0–0.22.0; `"dd"`, `target_forward_error` 0.17.0–0.22.0 | 0.23.0 |
180
+ | `einsum(precision="dd")` on float32/float64 was less accurate than `"fast"` (CPU emulation, #84) | 0.17.0–0.22.0 | 0.23.0 |
181
+ | `multi_einsum` returned float32 results as float64 in mixed-dtype batches (#75) | 0.17.0–0.22.0 | 0.23.0 |
182
+ | NKI chemistry kernels returned inf for float64 operands, and some kernel routes changed the result dtype (#87) | `df_*` 0.21.0–0.22.0; `ao_to_mo_transform` every release with its kernels | 0.23.0 |
183
+ | `ao_to_mo_transform` aten route on the TorchNeuron device was wrong once `eri` exceeded 4 GiB (#97; one LNC=1 case is still open) | through 0.22.0 | 0.23.0 |
184
+
170
185
  ## Related Projects
171
186
 
172
187
  | Project | What |
@@ -129,6 +129,21 @@ core, factors = trntensor.tucker_decompose(tensor, ranks=(5, 5, 5))
129
129
  - [x] Mixed precision / `dtype` override for bf16/fp16
130
130
  - [x] `precision=` kwarg (`"fast"` / `"kahan"` fp64 promotion / `"sr"` / `"dd"`: CPU emulation only, raises on Trainium until trnblas#22)
131
131
 
132
+ ## Known issues in earlier releases
133
+
134
+ Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details are in the [CHANGELOG](CHANGELOG.md).
135
+
136
+ | Bug | Affected | Fixed in |
137
+ |-----|----------|----------|
138
+ | `einsum` returned the wrong layout for transposed or permuted outputs (e.g. `ij,jk->ki` gave `A@B`), every backend (#64) | through 0.21.0 | 0.22.0 |
139
+ | `einsum(..., out=C)` with `beta=0` read `C`, so NaN/inf in it made the result NaN (#71) | 0.3.0–0.22.0 | 0.23.0 |
140
+ | `tucker_decompose` used `Uᵀ` instead of `Uᴴ` for complex tensors, giving a wrong core (#73) | through 0.22.0 | 0.23.0 |
141
+ | `precision="kahan"` / `"dd"` / `target_forward_error` dropped the imaginary part of complex operands and rounded large integers (#69) | `"kahan"` 0.4.0–0.22.0; `"dd"`, `target_forward_error` 0.17.0–0.22.0 | 0.23.0 |
142
+ | `einsum(precision="dd")` on float32/float64 was less accurate than `"fast"` (CPU emulation, #84) | 0.17.0–0.22.0 | 0.23.0 |
143
+ | `multi_einsum` returned float32 results as float64 in mixed-dtype batches (#75) | 0.17.0–0.22.0 | 0.23.0 |
144
+ | NKI chemistry kernels returned inf for float64 operands, and some kernel routes changed the result dtype (#87) | `df_*` 0.21.0–0.22.0; `ao_to_mo_transform` every release with its kernels | 0.23.0 |
145
+ | `ao_to_mo_transform` aten route on the TorchNeuron device was wrong once `eri` exceeded 4 GiB (#97; one LNC=1 case is still open) | through 0.22.0 | 0.23.0 |
146
+
132
147
  ## Related Projects
133
148
 
134
149
  | Project | What |
@@ -66,13 +66,20 @@ Matches cuTENSOR's GEMM-style interface:
66
66
  `alpha·contract(A, B) + beta·C`.
67
67
 
68
68
  ```python
69
- # Scaled GEMM: 2·A@B + 0.5·C
70
- result = trntensor.einsum("ij,jk->ik", A, B, alpha=2.0, beta=0.5, out=C)
69
+ # Scaled GEMM, written into C: C = 2·A@B + 0.5·C
70
+ trntensor.einsum("ij,jk->ik", A, B, alpha=2.0, beta=0.5, out=C)
71
71
 
72
- # In-place accumulation (beta=1, alpha=1): result += A@B
72
+ # In-place accumulation (beta=1, alpha=1): acc += A@B
73
73
  trntensor.einsum("ij,jk->ik", A, B, beta=1.0, out=acc)
74
74
  ```
75
75
 
76
+ As in `torch.einsum` and cuTENSOR, `out=` is the output operand: the result
77
+ is written into it and `out` is returned. `out` must have the result's shape,
78
+ and the result dtype must be castable to `out.dtype`. With `beta=0` the old
79
+ contents of `out` are not read. `out=` raises `RuntimeError` when grad mode is
80
+ on and an operand or `out` requires grad, as `torch.einsum(out=)` does.
81
+ Releases 0.3.0–0.23.0 returned the result without writing `out` (#77).
82
+
76
83
  ### `dtype` — mixed-precision compute
77
84
 
78
85
  Cast operands to a lower dtype to compute in bf16/fp16 (aten on the native
@@ -22,6 +22,64 @@ Return the current backend selection.
22
22
  Module-level flag set at import time. `True` when `nki` (0.3.0+) is
23
23
  importable, otherwise `False`.
24
24
 
25
+ ## Precision and dtypes
26
+
27
+ Trainium has no fp64 datapath: the NKI kernels compute in fp32 (bf16 / fp16
28
+ where a kernel takes them). The trntensor kernels are the matmul and
29
+ batched-matmul kernels behind `einsum` / `multi_einsum`, and the chemistry
30
+ kernels behind `mp2_energy`, `ao_to_mo_transform`, `df_exchange` and
31
+ `df_coulomb`. float64 operands that would reach one of them follow the
32
+ trnsci suite's float64 policy (#92):
33
+
34
+ | setting | float64 on a kernel route |
35
+ |---|---|
36
+ | `set_backend("auto")` (default) | runs torch on the operands' own device, the pytorch backend's computation, at float64 accuracy on the host. No kernel is launched |
37
+ | `set_backend("nki")` / `TRNTENSOR_FORCE_BACKEND=nki` | cast to fp32, the kernel runs, and the result is returned as float64 with fp32 accuracy. A `UserWarning` is emitted once per op per process |
38
+ | `TRNTENSOR_REQUIRE_NKI=1` (takes precedence over both) | raises `NotImplementedError`, so a downcast never happens silently |
39
+
40
+ - **Result dtype.** The result dtype always matches what the pytorch backend
41
+ returns for the same inputs, including bf16 / fp16 and mixed-dtype
42
+ promotion (`torch.promote_types` of the operands). Where a kernel computes
43
+ in fp32, the result is cast back.
44
+ - **Other dtypes.** Integer, bool and complex operands run torch on every
45
+ backend (trntensor has no complex kernels), and raise `NotImplementedError`
46
+ under `TRNTENSOR_REQUIRE_NKI=1` when the call would otherwise have run a
47
+ kernel. float16 chemistry operands, and bf16 on the fp32-only `df_*`
48
+ kernels, are upcast to fp32 without loss.
49
+ - **On the device.** Device aten computes float64 at fp32 precision
50
+ (measured on Trn2), so under `"auto"` float64 / complex128 operands that
51
+ already live on the `neuron` device are copied to the host, computed in host
52
+ torch at float64 accuracy, and the result is returned on the operands'
53
+ device in float64 / complex128. This covers every public compute entry
54
+ point: `einsum`, `multi_einsum`, `mp2_energy`, `ao_to_mo_transform`,
55
+ `df_exchange`, `df_coulomb`, the CP / Tucker / TT decompositions and
56
+ reconstructions, `gather` (device `torch.cat` also rounds float64 to
57
+ fp32), and the gathers `pack_tril` / `unpack_tril` / `pack_density` /
58
+ `unpack_packed` (device `index_select` and fancy indexing round float64 to
59
+ fp32 too; plain copies such as `.to`, `clone` and `.contiguous` are exact). `einsum(dtype=float64)` (or `"f64"`) on fp32 / bf16 device operands
60
+ asks for a float64 computation and takes the same host path. One `UserWarning` per op per process says: "float64 on the
61
+ neuron device is computed on the host for float64 accuracy (device
62
+ arithmetic is fp32); pass float32 to stay on device". `multi_einsum`
63
+ returns host tensors, as it always has. An `einsum(out=)` tensor on the
64
+ device is written in place. `einsum(dtype=...)` with a non-float64 compute
65
+ dtype stays on the device.
66
+ - `TRNTENSOR_FP64_ON_DEVICE=1` keeps device aten (fp32 precision, no
67
+ transfer, no warning), for callers who prefer speed to float64 accuracy.
68
+ - Host-resident float64 is unchanged: it stays in host torch (and
69
+ `multi_einsum` no longer pins host float64 operands to the device).
70
+ - Explicit `set_backend("nki")` / `"pytorch"` are unaffected: their rows
71
+ in the table above apply.
72
+ - `TRNTENSOR_REQUIRE_NKI=1` (backends `"auto"` and `"nki"`): a float64 /
73
+ complex128 computation on the `neuron` device raises
74
+ `NotImplementedError` at every guarded entry point (and in
75
+ `trntensor.stream` with a `neuron` device), with no host copy, ahead of
76
+ `TRNTENSOR_FP64_ON_DEVICE=1`. Before, only kernel routes raised; the
77
+ routes without a kernel (an `einsum` below the kernel size thresholds or
78
+ not a matmul, the decompositions, `precision="kahan"`) ran device aten
79
+ at fp32 precision, or the host, with no error.
80
+ - `precision="kahan"` always contracts in fp64 on the host. `precision="dd"`
81
+ still raises `NotImplementedError` with NKI installed (trnblas#22).
82
+
25
83
  ## Dispatch path
26
84
 
27
85
  On Neuron hardware, kernels run on one of two `torch-neuronx` lineages,
@@ -116,11 +174,13 @@ supported in maintenance mode."
116
174
 
117
175
  | Variable | Effect |
118
176
  |---|---|
119
- | `TRNTENSOR_REQUIRE_NKI=1` | Re-raise kernel exceptions instead of falling back to PyTorch. Useful in the validation loop to surface silent kernel breakage. |
177
+ | `TRNTENSOR_REQUIRE_NKI=1` | Re-raise kernel exceptions instead of falling back to PyTorch. Useful in the validation loop to surface silent kernel breakage. A dtype the kernel does not take (float64 included) raises `NotImplementedError` instead of running torch or downcasting; see [Precision and dtypes](#precision-and-dtypes). |
178
+ | `TRNTENSOR_FP64_ON_DEVICE=1` | Under `"auto"`, compute float64 / complex128 operands that are already on the `neuron` device in device aten at fp32 precision, instead of on the host at float64 accuracy (the default); see [Precision and dtypes](#precision-and-dtypes). |
120
179
  | `TRNTENSOR_MIN_NKI_FLOPS=<int>` | XLA path: override the FLOP threshold (M·K·N) below which dispatch skips NKI and uses `torch.matmul` / `torch.bmm` directly. Default: `2_000_000_000`. Set to `0` to force NKI for kernel validation. |
121
180
  | `TRNTENSOR_MIN_NKI_FLOPS_PINNED=<int>` | XLA path, operands already on the device. Default: `1_000_000_000`. |
122
181
  | `TRNTENSOR_MIN_NKI_FLOPS_NATIVE=<int>` | Native (TorchNeuron) path, operands on CPU: M·K·N at which the work leaves the host for the `neuron` device. Below it, `torch.matmul` / `torch.bmm` run on the host. Above it, the operands are offloaded. The offload runs aten unless the pinned threshold below selects NKI. Default: `500_000_000` (measured on Trn2, see below). |
123
182
  | `TRNTENSOR_MIN_NKI_FLOPS_NATIVE_PINNED=<int>\|never` | Native path: M·K·N at which the NKI kernel replaces aten on the device. Below it, device-resident operands run `torch.matmul` / `torch.bmm` (aten) on `neuron`. Default: `never`, because on Trn2 aten beat the NKI kernels at every measured size. |
183
+ | `TRNTENSOR_NKI_EAGER_HANDLE=1\|0` | Native path only. `1` (default): eager NKI kernel calls on plain `neuron` tensors go through a `torch_neuronx.wrap_nki` handle built once per kernel instead of the `trntensor::` custom op, which cuts host time per call from about 0.1 ms to 0.02-0.03 ms on trn2 (trnblas#92). Compile-time keyword arguments (`use_sr`, `nub`, `tp`, `tail`, `banks`) pass through unchanged. Under `torch.compile`, and for tensors that require grad, int64 tensors and tensor subclasses, the custom op runs as before; so do ops whose body is more than one kernel call. `0` always uses the custom op. |
124
184
  | `TRNSCI_NKI_DISPATCH=auto\|native\|xla` | Suite-wide. Force the native or XLA dispatch path; `auto` (default) detects. Forcing an unavailable path raises. |
125
185
  | `TRNSCI_XLA_DEPRECATION=1` | Suite-wide, off by default. Emit the one-time XLA-path and `to_xla` / `from_xla` deprecation warnings. |
126
186
  | `NKI_ENABLE_TRACE_CACHE=0` | TorchNeuron setting (not trntensor's). Turns off the cross-process NKI kernel cache, which cannot version editable installs and may serve a stale kernel after a source edit. Set it with `pip install -e`, or if you write your own NKI kernel factories ([aws-neuron/aws-neuron-sdk#1454](https://github.com/aws-neuron/aws-neuron-sdk/issues/1454)). The test suite keeps the cache on, with a fresh cache directory per session. |
@@ -52,7 +52,7 @@ the planner returns.
52
52
  | `contraction_indices` | `list[str]` | Indices summed over |
53
53
  | `batch_indices` | `list[str]` | Shared batch indices |
54
54
  | `output_indices` | `list[str]` | Output index order |
55
- | `estimated_flops` | `int` | Multiply-add estimate |
55
+ | `estimated_flops` | `int` | Multiply-adds of the plan: `estimate_flops(...)` for `"matmul"` / `"bmm"` / `"torch"`, the sum over binary steps for `"path"` (always 0 through 0.23.0, #83) |
56
56
  | `contraction_path` | `list[tuple[int,int]]` | Greedy pair order for `"path"` strategy (opt_einsum convention) |
57
57
  | `precision` | `str` | `"fast"` \| `"kahan"` \| `"dd"` \| `"sr"` |
58
58
 
@@ -0,0 +1,63 @@
1
+ # Streaming DF integrals over the aux index
2
+
3
+ `trntensor.stream` holds the packed three-centre integrals `B[μν, P]`
4
+ (`(npair, naux)`, `pack_tril` order) as a list of aux-column chunks and runs
5
+ the DF builds chunk by chunk. The integrals grow as `nbasis² · naux`: 33 GB in
6
+ fp32 at nbasis 1658 / naux 6064 and about 270 GB at nbasis ≈ 3300, against
7
+ 24 GiB per Trn2 logical core and 96 GB per chip. Every DF quantity used by
8
+ an SCF or DF-MP2 is a sum or a concatenation over `P`, so the problem size is
9
+ bounded by host memory (or disk), not device memory.
10
+
11
+ | quantity | over chunks `B_c` |
12
+ |---|---|
13
+ | `J = B (Bᵀ D)` | sum of `df_coulomb(B_c, D)` |
14
+ | `K = α Σ X Xᵀ` | sum of `df_exchange(B_c, C_occ, α)` |
15
+ | `B_ia^P` | concatenation of `ao_to_mo_transform(B_c, C_occ, C_vir)` |
16
+
17
+ ## `trntensor.AuxStream(chunks, nbasis, *, devices=None, dtype=float32, resident_bytes=0, prefetch=1)`
18
+
19
+ - `chunks`: `(npair, nq)` tensors, numpy arrays / memmaps, or zero-argument
20
+ loaders returning one (e.g. `lambda: np.load(path, mmap_mode="c")`).
21
+ - `devices`: chunks are dealt round-robin (`neuron:0..3` for one Trn2 chip).
22
+ Each device accumulates partial J and K; partials are summed on the host
23
+ once per call. Inputs reach each core through the host.
24
+ - `resident_bytes`: per-device budget for chunks kept on the device between
25
+ calls (first come, first kept). The rest are uploaded on every call by a
26
+ loader thread, `prefetch` per device ahead of the compute, so the upload of
27
+ chunk `k + 1` overlaps the kernels on chunk `k`.
28
+ - `stats` (after each pass): resident / streamed chunk counts, bytes
29
+ streamed, main-thread wait and loader time.
30
+
31
+ Methods: `jk(pw, C_occ, alpha=2.0)` → `(Jp, K)` in one pass (each streamed
32
+ chunk uploaded once for both), `coulomb(pw)`, `exchange(C_occ, alpha)`,
33
+ `ao_to_mo(C_occ, C_vir, out=None)` (writes into a host tensor or a numpy
34
+ memmap).
35
+
36
+ ## Helpers
37
+
38
+ - `aux_chunk_width(npair, naux, max_bytes=2 GiB, itemsize=4, multiple=128)`:
39
+ the widest 128-multiple chunk under `max_bytes`. The default keeps every
40
+ chunk under the 4 GiB transposed-LHS limit of the device matmul
41
+ (aws-neuron-sdk#1457, #97), and equal widths keep compiled shapes to two.
42
+ - `split_aux(B, max_bytes, multiple, dtype)`: contiguous chunk copies of an
43
+ in-memory `B`.
44
+ - `pack_density(D)` / `unpack_packed(jp, nbasis)`: the weighted packed
45
+ density `df_coulomb` takes and the inverse for J. On a NeuronCore these
46
+ gathers compile as single ops with `npair` / `nbasis²` indices (over 40 min
47
+ each at nbasis 1658, trnsolver#87): call them on host tensors there.
48
+ - `mp2_energy_blocked(B, eps_occ, eps_vir, *, devices, occ_block, max_bytes)`:
49
+ DF-MP2 from a host `B[i, a, P]` larger than one device, as
50
+ `Σ_I e(I, I) + 2 Σ_{I<J} e(I, J)` over occupied blocks; pairs dealt
51
+ round-robin over devices, partial energies summed in float64.
52
+
53
+ ## On-disk layout
54
+
55
+ Store one C-contiguous `(npair, nq)` `.npy` file per chunk and pass memmap
56
+ loaders: each upload is one contiguous read, from the page cache when host
57
+ RAM holds the integrals. Column slices of one `(npair, naux)` file are
58
+ strided reads.
59
+
60
+ ## Status
61
+
62
+ CPU-validated (`tests/test_stream.py`). The overlap of uploads with compute
63
+ and the multi-core scaling are to be measured on Trn2.
@@ -26,6 +26,7 @@ nav:
26
26
  - Planning: api/plan.md
27
27
  - Decompositions: api/decompose.md
28
28
  - Quantum primitives: api/quantum.md
29
+ - Streaming DF integrals: api/stream.md
29
30
  - NKI dispatch: api/nki.md
30
31
  - Architecture: architecture.md
31
32
  - Benchmarks: benchmarks.md
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "trntensor"
7
- version = "0.23.0"
7
+ version = "0.24.0"
8
8
  description = "Tensor contractions for AWS Trainium via NKI"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -0,0 +1,129 @@
1
+ """Host cost of one native kernel call: the `trntensor::` custom op against the
2
+ cached eager handle (`TRNTENSOR_NKI_EAGER_HANDLE`, trnblas#92), with aten for
3
+ scale, on device-resident inputs.
4
+
5
+ ``issue`` is the host time per call of n back-to-back calls; ``e2e`` the
6
+ median of one call plus a synchronize; ms. ``same_as_op`` compares the
7
+ handle's result with the op's bit for bit. Inputs are created on the host
8
+ and copied to the device (aws-neuron/aws-neuron-sdk#1439).
9
+
10
+ python scripts/bench_eager_handle.py
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import statistics
16
+ import time
17
+
18
+ import torch
19
+
20
+
21
+ def _sync():
22
+ import torch_neuronx
23
+
24
+ sync = getattr(torch_neuronx, "synchronize", None)
25
+ if sync is None:
26
+ sync = torch_neuronx.neuron.synchronize
27
+ sync()
28
+
29
+
30
+ def _issue_e2e(fn, n=200, e2e_reps=100):
31
+ for _ in range(10):
32
+ fn()
33
+ _sync()
34
+ issue = []
35
+ for _ in range(5):
36
+ t0 = time.perf_counter()
37
+ rs = [fn() for _ in range(n)]
38
+ issue.append((time.perf_counter() - t0) / n * 1e3)
39
+ _sync()
40
+ del rs
41
+ e2e = []
42
+ for _ in range(e2e_reps):
43
+ t0 = time.perf_counter()
44
+ fn()
45
+ _sync()
46
+ e2e.append((time.perf_counter() - t0) * 1e3)
47
+ return statistics.median(issue), statistics.median(e2e)
48
+
49
+
50
+ def _host(out):
51
+ if isinstance(out, tuple | list):
52
+ return tuple(_host(o) for o in out)
53
+ return out.detach().cpu() if isinstance(out, torch.Tensor) else out
54
+
55
+
56
+ def _same(a, b):
57
+ if isinstance(a, tuple):
58
+ return all(_same(x, y) for x, y in zip(a, b, strict=True))
59
+ return torch.equal(a, b) if isinstance(a, torch.Tensor) else a == b
60
+
61
+
62
+ def run(D, cases, n=200):
63
+ """cases: (name, fn, aten) — aten=True runs once (no op/handle toggle)."""
64
+ print(f"{'case':44s} {'path':7s} {'issue':>8s} {'e2e':>8s} same_as_op", flush=True)
65
+ for name, fn, aten, *kw in cases:
66
+ reps = kw[0] if kw else n
67
+ paths = ("aten",) if aten else ("op", "handle")
68
+ ref = None
69
+ for path in paths:
70
+ D._EAGER_HANDLE_ENABLED = path != "op"
71
+ out = _host(fn())
72
+ same = ""
73
+ if path == "op":
74
+ ref = out
75
+ elif path == "handle":
76
+ same = "yes" if _same(out, ref) else "NO"
77
+ del out
78
+ issue, e2e = _issue_e2e(fn, n=reps, e2e_reps=min(100, 5 * reps))
79
+ print(f"{name:44s} {path:7s} {issue:8.4f} {e2e:8.4f} {same}", flush=True)
80
+ D._EAGER_HANDLE_ENABLED = True
81
+
82
+
83
+ def main():
84
+ import trntensor
85
+ from trntensor.nki import dispatch as D
86
+
87
+ g = torch.Generator().manual_seed(0)
88
+ A, B = torch.randn(256, 128, generator=g), torch.randn(128, 512, generator=g)
89
+ a, b = A.to("neuron"), B.to("neuron")
90
+ Bm = (torch.randn(8, 128, 256, generator=g) * 0.05).to("neuron")
91
+ eo = (-torch.rand(8, generator=g) - 1.0).to("neuron")
92
+ ev = (torch.rand(128, generator=g) + 0.5).to("neuron")
93
+ eri = torch.randn(300, 300, 600, generator=g) * 0.1
94
+ eri = 0.5 * (eri + eri.transpose(0, 1))
95
+ pk = trntensor.pack_tril(eri).to("neuron")
96
+ C = (torch.randn(300, 33, generator=g) / 300**0.5).to("neuron")
97
+ del eri
98
+ run(
99
+ D,
100
+ [
101
+ ("aten a@b 256x128x512", lambda: a @ b, True),
102
+ (
103
+ "matmul 256x128x512 (use_sr=False)",
104
+ lambda: D._launch(None, "matmul", a, b, use_sr=False),
105
+ False,
106
+ ),
107
+ (
108
+ "matmul 256x128x512 (use_sr=True)",
109
+ lambda: D._launch(None, "matmul", a, b, use_sr=True),
110
+ False,
111
+ ),
112
+ (
113
+ "_nki_mp2_energy_rows nocc=8 (8 launches)",
114
+ lambda: D._nki_mp2_energy_rows(Bm, eo, ev),
115
+ False,
116
+ 20,
117
+ ),
118
+ (
119
+ "_nki_df_exchange 300/33/600 (nub/tp/tail, banks)",
120
+ lambda: D._nki_df_exchange(pk, C),
121
+ False,
122
+ 20,
123
+ ),
124
+ ],
125
+ )
126
+
127
+
128
+ if __name__ == "__main__":
129
+ main()