trntensor 0.19.0__tar.gz → 0.20.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 (78) hide show
  1. {trntensor-0.19.0 → trntensor-0.20.0}/CHANGELOG.md +52 -0
  2. {trntensor-0.19.0 → trntensor-0.20.0}/PKG-INFO +1 -1
  3. {trntensor-0.19.0 → trntensor-0.20.0}/docs/api/nki.md +90 -1
  4. {trntensor-0.19.0 → trntensor-0.20.0}/docs/api/quantum.md +68 -1
  5. {trntensor-0.19.0 → trntensor-0.20.0}/pyproject.toml +1 -1
  6. trntensor-0.20.0/tests/test_host_output.py +139 -0
  7. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_native_dispatch.py +287 -0
  8. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_nki_compile.py +21 -0
  9. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_nki_native.py +140 -0
  10. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_quantum.py +45 -0
  11. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/__init__.py +4 -2
  12. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/einsum.py +89 -4
  13. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/nki/_kernels.py +113 -31
  14. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/nki/_native.py +14 -0
  15. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/nki/dispatch.py +289 -25
  16. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/plan.py +25 -0
  17. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/quantum.py +158 -16
  18. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor.egg-info/PKG-INFO +1 -1
  19. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor.egg-info/SOURCES.txt +1 -0
  20. {trntensor-0.19.0 → trntensor-0.20.0}/.github/workflows/ci.yml +0 -0
  21. {trntensor-0.19.0 → trntensor-0.20.0}/.github/workflows/notify-umbrella.yml +0 -0
  22. {trntensor-0.19.0 → trntensor-0.20.0}/.github/workflows/publish.yml +0 -0
  23. {trntensor-0.19.0 → trntensor-0.20.0}/.gitignore +0 -0
  24. {trntensor-0.19.0 → trntensor-0.20.0}/.pre-commit-config.yaml +0 -0
  25. {trntensor-0.19.0 → trntensor-0.20.0}/CLAUDE.md +0 -0
  26. {trntensor-0.19.0 → trntensor-0.20.0}/CODE_OF_CONDUCT.md +0 -0
  27. {trntensor-0.19.0 → trntensor-0.20.0}/CONTRIBUTING.md +0 -0
  28. {trntensor-0.19.0 → trntensor-0.20.0}/LICENSE +0 -0
  29. {trntensor-0.19.0 → trntensor-0.20.0}/README.md +0 -0
  30. {trntensor-0.19.0 → trntensor-0.20.0}/benchmarks/__init__.py +0 -0
  31. {trntensor-0.19.0 → trntensor-0.20.0}/benchmarks/bench_einsum.py +0 -0
  32. {trntensor-0.19.0 → trntensor-0.20.0}/docs/api/decompose.md +0 -0
  33. {trntensor-0.19.0 → trntensor-0.20.0}/docs/api/einsum.md +0 -0
  34. {trntensor-0.19.0 → trntensor-0.20.0}/docs/api/index.md +0 -0
  35. {trntensor-0.19.0 → trntensor-0.20.0}/docs/api/plan.md +0 -0
  36. {trntensor-0.19.0 → trntensor-0.20.0}/docs/architecture.md +0 -0
  37. {trntensor-0.19.0 → trntensor-0.20.0}/docs/aws_setup.md +0 -0
  38. {trntensor-0.19.0 → trntensor-0.20.0}/docs/benchmarks.md +0 -0
  39. {trntensor-0.19.0 → trntensor-0.20.0}/docs/contraction_patterns.md +0 -0
  40. {trntensor-0.19.0 → trntensor-0.20.0}/docs/design/matmul_dispatch_findings.md +0 -0
  41. {trntensor-0.19.0 → trntensor-0.20.0}/docs/design/matmul_kernel_profile.md +0 -0
  42. {trntensor-0.19.0 → trntensor-0.20.0}/docs/developing_kernels.md +0 -0
  43. {trntensor-0.19.0 → trntensor-0.20.0}/docs/index.md +0 -0
  44. {trntensor-0.19.0 → trntensor-0.20.0}/docs/installation.md +0 -0
  45. {trntensor-0.19.0 → trntensor-0.20.0}/docs/quickstart.md +0 -0
  46. {trntensor-0.19.0 → trntensor-0.20.0}/docs/tutorial_df_mp2.md +0 -0
  47. {trntensor-0.19.0 → trntensor-0.20.0}/examples/df_mp2_einsum.py +0 -0
  48. {trntensor-0.19.0 → trntensor-0.20.0}/infra/terraform/README.md +0 -0
  49. {trntensor-0.19.0 → trntensor-0.20.0}/infra/terraform/main.tf +0 -0
  50. {trntensor-0.19.0 → trntensor-0.20.0}/mkdocs.yml +0 -0
  51. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/autotune_dispatch.py +0 -0
  52. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/bench_native_einsum.py +0 -0
  53. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/bench_native_kernels.py +0 -0
  54. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/bench_to_md.py +0 -0
  55. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/run_benchmarks.sh +0 -0
  56. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/run_neuron_profile.sh +0 -0
  57. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/run_neuron_tests.sh +0 -0
  58. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/run_reduce_parallel_multirank.py +0 -0
  59. {trntensor-0.19.0 → trntensor-0.20.0}/scripts/run_simulator_tests.sh +0 -0
  60. {trntensor-0.19.0 → trntensor-0.20.0}/setup.cfg +0 -0
  61. {trntensor-0.19.0 → trntensor-0.20.0}/tests/conftest.py +0 -0
  62. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_decompose.py +0 -0
  63. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_einsum.py +0 -0
  64. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_nki.py +0 -0
  65. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_nki_kernels.py +0 -0
  66. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_nki_sim.py +0 -0
  67. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_parallel.py +0 -0
  68. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_plan.py +0 -0
  69. {trntensor-0.19.0 → trntensor-0.20.0}/tests/test_sr_runtime.py +0 -0
  70. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/decompose.py +0 -0
  71. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/nki/__init__.py +0 -0
  72. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/nki/collectives.py +0 -0
  73. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/parallel.py +0 -0
  74. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor/py.typed +0 -0
  75. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor.egg-info/dependency_links.txt +0 -0
  76. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor.egg-info/requires.txt +0 -0
  77. {trntensor-0.19.0 → trntensor-0.20.0}/trntensor.egg-info/top_level.txt +0 -0
  78. {trntensor-0.19.0 → trntensor-0.20.0}/uv.lock +0 -0
@@ -7,6 +7,58 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.20.0] — 2026-10-31
11
+
12
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
13
+
14
+ Headline: packed ERI input for `ao_to_mo_transform` (DF-MP2 14–18% faster, #55); pinned-memory downloads (1.6–3.7×, #57); large host-input calls offload to the device above measured thresholds (umbrella DF-MP2 at xxl 29 s → 0.4 s, #58).
15
+
16
+ ### Changed
17
+
18
+ - **Host inputs run on the device when that is faster (#56).** On the
19
+ native TorchNeuron path under `"auto"`, host operands are uploaded, run on
20
+ the device by the device-resident policy and downloaded into cached host
21
+ memory once the work reaches a measured threshold:
22
+ - `mp2_energy`: `nocc²·nvir²·naux` ≥ 1.5e8;
23
+ - `ao_to_mo_transform`: `nocc·nbasis²·naux` ≥ 2e8 for a full `eri`, 3e7 for a packed one;
24
+ - `einsum` generic and multi-operand plans: ≥ 5e8 multiply-adds and at least 0.5 multiply-adds per byte moved. A path uploads once and keeps its intermediates on the device.
25
+ - These thresholds scale with `torch.get_num_threads() / 2`, as in trnblas#65. Matmul/bmm keep `TRNTENSOR_MIN_NKI_FLOPS_NATIVE` (5e8, re-measured).
26
+ - Trn2, 2 host threads, warm: `mp2_energy` 646 -> 16 ms at 32/224/1024 and 15.8 s -> 135 ms at 64/448/1536. `ao_to_mo_transform` at 512/1536/64 went 574 -> 137 ms full and 979 -> 80 ms packed. The umbrella DF-MP2 profile in host-auto mode at 512/1536/64 went 29.9 s -> 0.37 s (fused pipeline) and 28.9 s -> 0.41 s (example pipeline, with trnblas 0.9 routing).
27
+ - `TRNTENSOR_HOST_ROUTE=host|device|auto` overrides the choice. `set_backend("pytorch")` and `set_backend("nki")` keep their routes.
28
+ - If the upload or the device call fails, the call runs on the host.
29
+ - **float64 and complex host matmul/bmm stay on the host** under native
30
+ `"auto"`. Before, they were offloaded from 5e8 multiply-adds, and the
31
+ device computes in at most fp32: a float64 `einsum("ij,jk->ik")` at 1024³
32
+ came back with 1.4e-7 relative error. It is now exact float64.
33
+
34
+ - **Host results at the host-link rate (#56).** On the native TorchNeuron
35
+ path, results of 1 MiB and up that come back to the host (`einsum` /
36
+ `multi_einsum` with host operands on the `aten`-on-device route, kernel
37
+ launches, `from_device`) are copied into memory from the accelerator's
38
+ caching host allocator (`torch.empty(..., pin_memory=True)`), the fix
39
+ trnblas#64 made. A copy into fresh pageable memory runs at about 4 GB/s on
40
+ Trn2 because every page faults; into that memory it runs at 13-14 GB/s.
41
+ Each call still returns a fresh tensor, and results are bit-identical.
42
+ `TRNTENSOR_PINNED_OUTPUT=0` turns it off.
43
+ - **`einsum`'s `alpha` / `beta` / `out` epilogue runs in place** on a fresh
44
+ result (same float ops, same bits). Out of place each step allocated and
45
+ page-faulted another result-sized host tensor.
46
+ - Trn2, host operands, warm medians: `einsum("ij,jk->ik")` 4096³ 32 -> 20 ms,
47
+ 8192×1024×8192 80 -> 29 ms; with `alpha=2, beta=1, out=C` 69 -> 29 ms and
48
+ 230 -> 63 ms; 16×1024³ bmm 30 -> 17 ms; `from_device` of 256 MB 68 -> 19 ms.
49
+ `ao_to_mo_transform` and `mp2_energy` with host inputs run on the host and
50
+ are unchanged.
51
+
52
+ ### Added
53
+
54
+ - **Packed (μ≥ν) three-centre integrals in `ao_to_mo_transform` (#54).**
55
+ - A 2-D `eri` is read as the packed lower triangle: `(npair, naux)` (row `μ(μ+1)/2 + ν`, the `trnblas.parallel.pack_tril` layout), or PySCF's `_cderi` `(naux, npair)` as is. 3-D calls are unchanged.
56
+ - New `trntensor.pack_tril` / `trntensor.unpack_tril`.
57
+ - A host `eri` with device `C_occ` is now uploaded to that device; this used to fail on mixed devices.
58
+ - New native kernel `ao_to_mo_trn2_packed_kernel`. It gathers its stage-1 blocks from the packed rows with batched indirect DMA, so the full square is never written to device memory. Bit-identical to `ao_to_mo_trn2_kernel`, and as fast at LNC=1 and LNC=2.
59
+ - DF-MP2 end to end on Trn2 (umbrella `df_mp2_profile.py`, one LNC=2 core): 342 → 281 ms at ao/aux/occ 512/1536/64, 157 → 135 ms at 384/1152/48, with identical energies. The upload of `eri` halves (119 → 62 ms).
60
+ - Pinned host memory does not speed up the upload (measured), so there is no pinned staging path.
61
+
10
62
  ## [0.19.0] — 2026-10-31
11
63
 
12
64
  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.19.0
3
+ Version: 0.20.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
@@ -119,7 +119,9 @@ supported in maintenance mode."
119
119
  | `TRNSCI_XLA_DEPRECATION=1` | Suite-wide, off by default. Emit the one-time XLA-path and `to_xla` / `from_xla` deprecation warnings. |
120
120
  | `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`; the test suite sets it by default. |
121
121
  | `TRNTENSOR_MP2_ENERGY=auto\|rows\|aten\|legacy` | Native path: force the `mp2_energy` executor (`rows` = the Trn2 row kernel, `legacy` = the original kernel, deprecated there). |
122
- | `TRNTENSOR_AO_TO_MO=auto\|trn2\|aten\|legacy` | Native path: force the `ao_to_mo_transform` executor (`trn2` = the Trn2 kernel, `legacy` = the original kernel, deprecated there). |
122
+ | `TRNTENSOR_AO_TO_MO=auto\|trn2\|aten\|legacy` | Native path: force the `ao_to_mo_transform` executor (`trn2` = the Trn2 kernel, or `ao_to_mo_trn2_packed_kernel` for a packed 2-D `eri`; `legacy` = the original kernel, deprecated there; `aten` and `legacy` unpack a packed `eri` first). |
123
+ | `TRNTENSOR_HOST_ROUTE=auto\|host\|device` | Native path, `"auto"` backend, all operands on the host: where the work runs (#56). `auto` (default) uploads it once it reaches the measured thresholds below; `host` keeps it on the host; `device` always uploads. Covers `mp2_energy`, `ao_to_mo_transform`, `einsum` / `multi_einsum` (matmul, bmm, generic and multi-operand plans). Only float32 / bfloat16 / float16 operands are uploaded. `set_backend("pytorch")` and `set_backend("nki")` ignore it. |
124
+ | `TRNTENSOR_PINNED_OUTPUT=0` | Native path: download results with plain `.to("cpu")` instead of into memory from the caching host allocator (`torch.empty(..., pin_memory=True)`, results of 1 MiB and up; #56). |
123
125
  | `TRNTENSOR_FORCE_BACKEND=pytorch\|nki\|auto` | Override the backend selection at runtime without calling `set_backend()`. Used by benchmarks to sweep both paths on the same machine. |
124
126
  | `TRNTENSOR_USE_SIMULATOR=1` | Route kernel dispatch through `nki.simulate(kernel)(numpy_args)` on CPU instead of XLA → NEFF → hardware. Catches Python-trace-level errors without AWS round-trips. MLIR verifier errors remain hardware-only. |
125
127
 
@@ -148,6 +150,93 @@ NeuronCore and two host threads, with `scripts/bench_native_einsum.py` and
148
150
  The default of 500 M sits between these. A host with more threads moves the
149
151
  crossover up. Re-measure on your host with `scripts/autotune_dispatch.py`.
150
152
 
153
+ ### Host operands: upload or stay (#56)
154
+
155
+ With every operand on the host, native `"auto"` uploads the work, runs it on
156
+ the device by the device-resident policy, and downloads the result into
157
+ memory from the caching host allocator, once the work reaches:
158
+
159
+ | entry point | work | offload from (2 host threads) |
160
+ |---|---|---|
161
+ | `mp2_energy` | `nocc²·nvir²·naux` | 1.5e8 |
162
+ | `ao_to_mo_transform`, full `eri` | `nocc·nbasis²·naux` | 2e8 |
163
+ | `ao_to_mo_transform`, packed `eri` | `nocc·nbasis²·naux` | 3e7 |
164
+ | `einsum`, generic or multi-operand plan | contraction multiply-adds (a path: the sum of its steps) | 5e8, and at least 0.5 multiply-adds per byte moved |
165
+ | `einsum` matmul / bmm | `M·K·N` | `TRNTENSOR_MIN_NKI_FLOPS_NATIVE` (5e8, above) |
166
+
167
+ - The first four scale with `torch.get_num_threads() / 2`, as trnblas#65
168
+ does: the host side is compute-bound and the thresholds were measured with
169
+ 2 threads. The matmul threshold keeps its own override and is not scaled.
170
+ - Einsums with little reuse stay on the host at any size: under 0.5
171
+ multiply-adds per byte moved, such as elementwise (0.08) and outer
172
+ (0.25) products. They measured 1.4-2.9x faster uploaded, but only because
173
+ 2 host threads stream memory slower than the link. Host bandwidth grows
174
+ with threads and the link's does not, and these patterns fill device
175
+ memory.
176
+ - float64 and complex operands stay on the host, matmul included. The
177
+ device computes in at most fp32.
178
+ - If the upload or the device call fails (for example, a full device), the
179
+ call runs on the host. `TRNTENSOR_REQUIRE_NKI=1` raises instead.
180
+ - The first call of each shape on the device pays its compile. These tables
181
+ are warm.
182
+
183
+ Measured on Trn2 (SDK 2.33, one logical core at LNC=2, fp32, warm medians,
184
+ host in to host out). Host threads were pinned to 2 CPUs on two physical
185
+ cores:
186
+
187
+ "Host" is the host route on two physical cores; the column after it is the
188
+ same on one physical core (both hyperthreads). "Device" is upload + the
189
+ device-resident `auto` route + download. **Bold** is what `auto` now picks.
190
+
191
+ `mp2_energy`, ms:
192
+
193
+ | nocc/nvir/naux | work | host | host, 1 core | device |
194
+ |---|---|---|---|---|
195
+ | 8/56/192 | 3.9e7 | **1.4** | 1.7 | 3.1 |
196
+ | 8/80/256 | 1.1e8 | **3.8** | 4.9 | 4.2 |
197
+ | 8/96/256 | 1.5e8 | 5.1 | 6.8 | **4.1** |
198
+ | 16/112/384 | 1.2e9 | 26.0 | 39.0 | **3.7** |
199
+ | 16/240/768 | 1.1e10 | 173 | 253 | **6.5** |
200
+ | 32/224/1024 | 5.3e10 | 646 | 1128 | **16.4** |
201
+ | 48/336/1152 | 3.0e11 | 3697 | 6457 | **47.4** |
202
+ | 64/448/1536 | 1.3e12 | 15849 | 28157 | **135** |
203
+
204
+ `ao_to_mo_transform`, ms (full `eri` / packed `eri`):
205
+
206
+ | nbasis/naux/nocc | work | host | host, 1 core | device |
207
+ |---|---|---|---|---|
208
+ | 64/192/8 | 6.3e6 | **1.0** / **1.3** | 1.1 / 1.7 | 5.7 / 6.7 |
209
+ | 128/384/16 | 1.0e8 | **4.7** / 6.7 | 7.4 / 11.0 | 7.5 / **5.3** |
210
+ | 128/512/16 | 1.3e8 | **6.2** / – | 10.1 / 21.7 | 8.9 / **4.1** |
211
+ | 160/480/20 | 2.5e8 | 9.4 / – | 16.3 / 32.9 | **7.1** / **5.1** |
212
+ | 256/512/8 | 2.7e8 | 16.0 / 54.2 | 26.5 / 71.0 | **13.6** / **13.0** |
213
+ | 256/1024/32 | 2.2e9 | 66.6 / 138 | 111 / 198 | **25.7** / **15.7** |
214
+ | 384/1152/48 | 8.2e9 | 211 / 397 | 355 / 571 | **62.2** / **37.9** |
215
+ | 512/1536/64 | 2.6e10 | 574 / 979 | 959 / 1473 | **137** / **79.9** |
216
+
217
+ `einsum` with host operands, ms:
218
+
219
+ | contraction | work | MACs per byte | host | host, 1 core | device |
220
+ |---|---|---|---|---|---|
221
+ | `mi,mnP->inP` 128/16/384 | 1.0e8 | 3.6 | **3.2** | 5.5 | 4.4 |
222
+ | `mi,mnP->inP` 256/32/768 | 1.6e9 | 7.1 | 30.5 | 52.4 | **19.7** |
223
+ | `mi,mnP->inP` 512/4/1536 | 1.6e9 | 1.0 | – | 252 | **123** |
224
+ | `iap,jbp->ijab` 16/112/384 | 1.2e9 | 67 | 7.5 | 13.3 | **3.8** |
225
+ | `iaP,PQ->iaQ` 64/448/1536 | 6.8e10 | 187 | 386 | 707 | **31.9** |
226
+ | `abc,cd->abd` 256 | 4.3e9 | 32 | 46.9 | 62.7 | **11.7** |
227
+ | `mi,na,mnP->iaP` 256/32/224/768 (path) | 3.0e9 | 13.5 | – | 90.1 | **19.0** |
228
+ | `ij,ij->ij` 8192² | 6.7e7 | 0.08 | – | **85.8** | 60.3 |
229
+ | `ab,cd->abcd` 160 | 6.6e8 | 0.25 | – | **580** | 199 |
230
+ | `ij,jk->ik` 640³ | 2.6e8 | 53 | **2.3** | 3.7 | 2.6 |
231
+ | `ij,jk->ik` 768³ | 4.5e8 | 66 | **3.4** | 5.6 | 2.7 |
232
+ | `ij,jk->ik` 1024³ | 1.1e9 | 85 | 6.5 | 12.1 | **3.2** |
233
+
234
+ - Results match the host route to 5e-7 relative (fp32 summation order).
235
+ - On one physical core the host is about 1.7x slower, so the device wins
236
+ earlier: from 3e7 for the full `eri`, and below 1.3e8 for matmul. The
237
+ thresholds were set on the faster host, so they are on the host's side.
238
+ - The device floor varied between runs, 1.2 to 2.6 ms for a small matmul.
239
+
151
240
  Kernel status on the native path after #51:
152
241
 
153
242
  - **matmul / bmm: retired in favour of aten.** A Trn2 rewrite used both
@@ -79,6 +79,14 @@ print(f"E_MP2 = {E.item():.6f}")
79
79
  plus that staging would leave less than 3 GiB free. A shape whose kernel
80
80
  launch fails anyway falls back to aten and is remembered for the rest of
81
81
  the process.
82
+ - **Host `B` on native TorchNeuron (#56).** Under `"auto"`, a host `B` with
83
+ `nocc²·nvir²·naux` of at least 1.5e8 multiply-adds (scaled by
84
+ `torch.get_num_threads() / 2`) is uploaded with the orbital energies, the
85
+ device route above runs, and the energy comes back as a host scalar.
86
+ Smaller problems stay on the host. On Trn2 with 2 host threads this took
87
+ 646 ms -> 16 ms at 32/224/1024 and 15.8 s -> 135 ms at 64/448/1536. See
88
+ [host operands](nki.md#host-operands-upload-or-stay-56) for the table and
89
+ `TRNTENSOR_HOST_ROUTE`.
82
90
  - **PyTorch/XLA path (Trn1)**: the original single-launch `mp2_energy_kernel`.
83
91
  It accumulates `T` in PSUM, builds `Δ` on the Vector Engine, and writes one
84
92
  partial per `(i, j)` pair.
@@ -93,7 +101,10 @@ B[i, a, P] = Σ_{μ, ν} C_occ[μ, i] · C_vir[ν, a] · eri[μ, ν, P]
93
101
 
94
102
  ### Arguments
95
103
 
96
- - `eri: (nbasis, nbasis, naux) tensor` — density-fitted two-electron integrals in the AO basis
104
+ - `eri` — density-fitted three-centre integrals in the AO basis, one of:
105
+ - `(nbasis, nbasis, naux)`: the full square;
106
+ - `(npair, naux)`, `npair = nbasis(nbasis+1)/2`: the packed lower triangle, row `μ(μ+1)/2 + ν` for `ν ≤ μ` (see [Packed integrals](#packed-integrals));
107
+ - `(naux, npair)`: PySCF's `_cderi`, as is. When `naux == npair` the shape is ambiguous and is read as `(npair, naux)`; pass `cderi.T` then.
97
108
  - `C_occ: (nbasis, nocc) tensor` — occupied molecular orbital coefficients
98
109
  - `C_vir: (nbasis, nvir) tensor` — virtual molecular orbital coefficients
99
110
 
@@ -110,6 +121,52 @@ B = trntensor.ao_to_mo_transform(eri, C_occ, C_vir)
110
121
  E = trntensor.mp2_energy(B, eps_occ, eps_vir)
111
122
  ```
112
123
 
124
+ ### Packed integrals
125
+
126
+ Real three-centre integrals are symmetric in μ↔ν, and drivers store only the
127
+ lower triangle (PySCF `_cderi`, `trnblas.parallel.pack_tril`). Pass it packed
128
+ (#54):
129
+
130
+ ```python
131
+ B = trntensor.ao_to_mo_transform(cderi, C_occ_d, C_vir_d) # cderi: host (naux, npair)
132
+ ```
133
+
134
+ - `trntensor.pack_tril(eri)` and `trntensor.unpack_tril(eri_packed, nbasis)`
135
+ convert between the layouts (one `index_select` each, exact).
136
+ - **A host `eri` with device `C_occ` is uploaded to `C_occ`'s device**, in the
137
+ layout given. The result stays on the device.
138
+ - On the native path, `"auto"` sends packed device integrals to
139
+ `ao_to_mo_trn2_packed_kernel` under the same conditions as the full kernel.
140
+ Its stage 1 fetches each `(128 μ, NUB ν, TP aux)` block from the packed
141
+ rows with one batched indirect DMA. The full square never exists in device
142
+ memory. Its result is bit-identical to the full kernel's.
143
+ - The aten and legacy routes unpack on the tensor's device first.
144
+
145
+ Why: on Trn2 the host link carries about 13.8 GB/s for the whole chip, so the
146
+ upload of `eri` was DF-MP2's largest stage. Packed, it is half the bytes.
147
+
148
+ Upload of `eri` alone (Trn2, one logical core; host threads pinned to 2 CPUs):
149
+
150
+ | nbasis/naux | full | packed | packed, from pinned host memory |
151
+ |---|---|---|---|
152
+ | 384/1152 | 49.2 ms | 25.1 ms | 24.9 ms |
153
+ | 512/1536 | 115.7 ms | 58.5 ms | 58.4 ms |
154
+
155
+ Pinned host memory and `copy_` into a preallocated device tensor upload no
156
+ faster: H2D already runs at the link rate from ordinary host memory.
157
+ Packing a full host tensor costs more than it saves: 180 ms on 2 host
158
+ threads at 512/1536, against a 57 ms saving. Neither does uploading the
159
+ triangle row by row (281 ms). So a 3-D host `eri` is uploaded as is.
160
+ Packing pays only when the integrals already arrive packed.
161
+
162
+ Kernel alone, device-resident, warm (fp32; padded `nvir` included):
163
+
164
+ | nbasis/naux/nocc | LNC=2 full | LNC=2 packed | LNC=1 full | LNC=1 packed | device `unpack_tril` |
165
+ |---|---|---|---|---|---|
166
+ | 256/768/32 | 1.09 ms | 0.91 ms | 1.86 ms | 1.93 ms | — |
167
+ | 384/1152/48 | 5.38 ms | 5.81 ms | 5.72 ms | 5.95 ms | 3.1 ms |
168
+ | 512/1536/64 | 6.28 ms | 6.27 ms | 12.87 ms | 12.75 ms | 5.5 ms |
169
+
113
170
  ### Backend behaviour
114
171
 
115
172
  - **CPU**: two explicit aten steps on the operands' device:
@@ -142,6 +199,16 @@ E = trntensor.mp2_energy(B, eps_occ, eps_vir)
142
199
  nbasis 64 and 128 it measured 0.79 and 0.57 ms with the kernel forced,
143
200
  which is why `"auto"` keeps aten there.
144
201
 
202
+ - **Host inputs on native TorchNeuron (#56).** Under `"auto"`, with `eri`,
203
+ `C_occ` and `C_vir` all on the host, the inputs are uploaded (`eri` in the
204
+ layout given), the device route above runs, and the result is downloaded,
205
+ once `nocc·nbasis²·naux` reaches 2e8 for a full `eri` or 3e7 for a packed
206
+ one (both scaled by `torch.get_num_threads() / 2`). A packed host `eri`
207
+ otherwise pays a host unpack, so its threshold is lower. On Trn2 with 2
208
+ host threads at 512/1536/64 this took 574 -> 137 ms full and 979 -> 80 ms
209
+ packed. PySCF's `(naux, npair)` layout went from 5.2 s to 83 ms on one
210
+ physical core. See [host operands](nki.md#host-operands-upload-or-stay-56)
211
+ for the table and `TRNTENSOR_HOST_ROUTE`.
145
212
  - **PyTorch/XLA path (Trn1)**: the original kernel. It loops over P, with the
146
213
  `(i, ν)` intermediate round-tripping through kernel-scratch HBM. On the
147
214
  native path it is deprecated.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "trntensor"
7
- version = "0.19.0"
7
+ version = "0.20.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,139 @@
1
+ """
2
+ Host results through the caching host allocator (trnblas#61).
3
+
4
+ CPU-only: the pinned allocation is replaced by a recording stand-in (a CPU-only
5
+ host has no accelerator to pin for), and the dispatch path is forced to
6
+ "native" where a test needs the cached-allocator route.
7
+ """
8
+
9
+ import pytest
10
+ import torch
11
+
12
+ from trntensor.nki import dispatch as D
13
+
14
+ MiB = 1 << 20
15
+
16
+
17
+ @pytest.fixture
18
+ def native_host_cache(monkeypatch):
19
+ """Pretend we are on the native path; record pinned allocations."""
20
+ monkeypatch.delenv("TRNTENSOR_PINNED_OUTPUT", raising=False)
21
+ monkeypatch.setattr(D, "_get_dispatch_path", lambda: "native")
22
+ monkeypatch.setattr(D, "_use_simulator", lambda: False)
23
+ calls = []
24
+ real_empty = torch.empty
25
+
26
+ def fake_empty(*args, pin_memory=False, **kw):
27
+ if pin_memory:
28
+ calls.append(args[0])
29
+ return real_empty(*args, **kw)
30
+
31
+ monkeypatch.setattr(D.torch, "empty", fake_empty)
32
+ return calls
33
+
34
+
35
+ class TestUseHostCache:
36
+ def test_off_the_native_path(self, monkeypatch):
37
+ monkeypatch.setattr(D, "_get_dispatch_path", lambda: "xla")
38
+ monkeypatch.setattr(D, "_use_simulator", lambda: False)
39
+ assert not D._use_host_cache("cpu", 64 * MiB)
40
+
41
+ def test_native_large_cpu_destination(self, native_host_cache):
42
+ assert D._use_host_cache("cpu", MiB)
43
+ assert D._use_host_cache(torch.device("cpu"), 64 * MiB)
44
+
45
+ def test_small_results_skip(self, native_host_cache):
46
+ assert not D._use_host_cache("cpu", MiB - 1)
47
+
48
+ def test_device_destination_skips(self, native_host_cache):
49
+ assert not D._use_host_cache("meta", 64 * MiB)
50
+
51
+ @pytest.mark.parametrize("value", ["0", "false", "off", "no"])
52
+ def test_env_disables(self, native_host_cache, monkeypatch, value):
53
+ monkeypatch.setenv("TRNTENSOR_PINNED_OUTPUT", value)
54
+ assert not D._use_host_cache("cpu", 64 * MiB)
55
+
56
+ def test_simulator_skips(self, native_host_cache, monkeypatch):
57
+ monkeypatch.setattr(D, "_use_simulator", lambda: True)
58
+ assert not D._use_host_cache("cpu", 64 * MiB)
59
+
60
+
61
+ class TestToHost:
62
+ def test_large_result_uses_cache_and_is_fresh(self, native_host_cache):
63
+ src = torch.randn(512, 1024) # 2 MiB, standing in for a device result
64
+ out = D._host_empty(src.shape, src.dtype, "cpu").copy_(src)
65
+ assert native_host_cache == [(512, 1024)]
66
+ assert torch.equal(out, src)
67
+ assert out.data_ptr() != src.data_ptr()
68
+
69
+ def test_cpu_tensor_passes_through(self, native_host_cache):
70
+ t = torch.randn(512, 1024)
71
+ assert D._to_host(t, "cpu") is t
72
+ assert D._from_device(t) is t
73
+ assert native_host_cache == []
74
+
75
+ def test_host_empty_small_is_plain(self, native_host_cache):
76
+ t = D._host_empty((4, 4), torch.float32, "cpu")
77
+ assert t.shape == (4, 4) and native_host_cache == []
78
+
79
+ def test_aten_on_device_downloads_through_to_host(self, monkeypatch):
80
+ seen = []
81
+ monkeypatch.setattr(D, "_NEURON_DEVICE", "cpu")
82
+ monkeypatch.setattr(D, "_to_host", lambda t, device: seen.append(device) or t)
83
+ A, B = torch.randn(8, 8), torch.randn(8, 8)
84
+ torch.testing.assert_close(D._aten_on_device(torch.matmul, A, B), A @ B)
85
+ assert seen == [torch.device("cpu")]
86
+
87
+
88
+ class TestScaleAddEpilogue:
89
+ """einsum's alpha/beta epilogue runs in place on a fresh result, same bits."""
90
+
91
+ @pytest.mark.parametrize("alpha", [1.0, 0.5, -2.0])
92
+ @pytest.mark.parametrize("beta", [0.0, 1.0, 0.25])
93
+ @pytest.mark.parametrize("with_out", [True, False])
94
+ def test_matches_out_of_place(self, alpha, beta, with_out):
95
+ import trntensor
96
+
97
+ g = torch.Generator().manual_seed(0)
98
+ A, B, C = (
99
+ torch.randn(17, 23, generator=g),
100
+ torch.randn(23, 9, generator=g),
101
+ torch.randn(17, 9, generator=g),
102
+ )
103
+ out = C if with_out else None
104
+ want = torch.einsum("ij,jk->ik", A, B).mul(alpha)
105
+ if with_out:
106
+ want = want.add(C, alpha=beta)
107
+ C0 = C.clone()
108
+ got = trntensor.einsum("ij,jk->ik", A, B, alpha=alpha, beta=beta, out=out)
109
+ assert torch.equal(got, want)
110
+ assert torch.equal(C, C0) # out is read, never written
111
+
112
+ def test_view_of_operand_is_not_overwritten(self):
113
+ import trntensor
114
+
115
+ A = torch.randn(8, 8)
116
+ A0 = A.clone()
117
+ got = trntensor.einsum("ij->ji", A, alpha=2.0)
118
+ assert torch.equal(got, 2.0 * A0.T) and torch.equal(A, A0)
119
+
120
+ def test_broadcast_out_and_promotion_fall_back(self):
121
+ from trntensor.einsum import _scale_add
122
+
123
+ r = torch.ones(4, 1)
124
+ got = _scale_add(r, 1.0, 1.0, torch.ones(4, 3), ())
125
+ assert got.shape == (4, 3) and r.shape == (4, 1)
126
+ ri = torch.ones(3, dtype=torch.int64)
127
+ assert _scale_add(ri, 0.5, 1.0, None, ()).dtype == torch.float32
128
+ r64 = torch.ones(3, dtype=torch.float32)
129
+ assert _scale_add(r64, 1.0, 1.0, torch.ones(3, dtype=torch.float64), ()).dtype == (
130
+ torch.float64
131
+ )
132
+
133
+ def test_autograd_kept(self):
134
+ import trntensor
135
+
136
+ A = torch.randn(5, 6, requires_grad=True)
137
+ B = torch.randn(6, 4)
138
+ trntensor.einsum("ij,jk->ik", A, B, alpha=3.0).sum().backward()
139
+ torch.testing.assert_close(A.grad, 3.0 * B.sum(1).expand(5, 6))