trntensor 0.20.0__tar.gz → 0.22.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 (79) hide show
  1. {trntensor-0.20.0 → trntensor-0.22.0}/CHANGELOG.md +89 -0
  2. {trntensor-0.20.0 → trntensor-0.22.0}/PKG-INFO +2 -2
  3. {trntensor-0.20.0 → trntensor-0.22.0}/README.md +1 -1
  4. {trntensor-0.20.0 → trntensor-0.22.0}/docs/api/index.md +1 -1
  5. {trntensor-0.20.0 → trntensor-0.22.0}/docs/api/nki.md +13 -0
  6. {trntensor-0.20.0 → trntensor-0.22.0}/docs/api/quantum.md +162 -0
  7. {trntensor-0.20.0 → trntensor-0.22.0}/pyproject.toml +1 -1
  8. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_einsum.py +53 -0
  9. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_native_dispatch.py +210 -0
  10. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_nki_compile.py +45 -0
  11. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_nki_native.py +80 -0
  12. trntensor-0.22.0/tests/test_nki_tail_audit.py +274 -0
  13. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_quantum.py +76 -0
  14. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/__init__.py +11 -2
  15. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/nki/_kernels.py +485 -0
  16. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/nki/_native.py +59 -0
  17. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/nki/dispatch.py +191 -0
  18. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/plan.py +27 -4
  19. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/quantum.py +173 -0
  20. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor.egg-info/PKG-INFO +2 -2
  21. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor.egg-info/SOURCES.txt +1 -0
  22. {trntensor-0.20.0 → trntensor-0.22.0}/.github/workflows/ci.yml +0 -0
  23. {trntensor-0.20.0 → trntensor-0.22.0}/.github/workflows/notify-umbrella.yml +0 -0
  24. {trntensor-0.20.0 → trntensor-0.22.0}/.github/workflows/publish.yml +0 -0
  25. {trntensor-0.20.0 → trntensor-0.22.0}/.gitignore +0 -0
  26. {trntensor-0.20.0 → trntensor-0.22.0}/.pre-commit-config.yaml +0 -0
  27. {trntensor-0.20.0 → trntensor-0.22.0}/CLAUDE.md +0 -0
  28. {trntensor-0.20.0 → trntensor-0.22.0}/CODE_OF_CONDUCT.md +0 -0
  29. {trntensor-0.20.0 → trntensor-0.22.0}/CONTRIBUTING.md +0 -0
  30. {trntensor-0.20.0 → trntensor-0.22.0}/LICENSE +0 -0
  31. {trntensor-0.20.0 → trntensor-0.22.0}/benchmarks/__init__.py +0 -0
  32. {trntensor-0.20.0 → trntensor-0.22.0}/benchmarks/bench_einsum.py +0 -0
  33. {trntensor-0.20.0 → trntensor-0.22.0}/docs/api/decompose.md +0 -0
  34. {trntensor-0.20.0 → trntensor-0.22.0}/docs/api/einsum.md +0 -0
  35. {trntensor-0.20.0 → trntensor-0.22.0}/docs/api/plan.md +0 -0
  36. {trntensor-0.20.0 → trntensor-0.22.0}/docs/architecture.md +0 -0
  37. {trntensor-0.20.0 → trntensor-0.22.0}/docs/aws_setup.md +0 -0
  38. {trntensor-0.20.0 → trntensor-0.22.0}/docs/benchmarks.md +0 -0
  39. {trntensor-0.20.0 → trntensor-0.22.0}/docs/contraction_patterns.md +0 -0
  40. {trntensor-0.20.0 → trntensor-0.22.0}/docs/design/matmul_dispatch_findings.md +0 -0
  41. {trntensor-0.20.0 → trntensor-0.22.0}/docs/design/matmul_kernel_profile.md +0 -0
  42. {trntensor-0.20.0 → trntensor-0.22.0}/docs/developing_kernels.md +0 -0
  43. {trntensor-0.20.0 → trntensor-0.22.0}/docs/index.md +0 -0
  44. {trntensor-0.20.0 → trntensor-0.22.0}/docs/installation.md +0 -0
  45. {trntensor-0.20.0 → trntensor-0.22.0}/docs/quickstart.md +0 -0
  46. {trntensor-0.20.0 → trntensor-0.22.0}/docs/tutorial_df_mp2.md +0 -0
  47. {trntensor-0.20.0 → trntensor-0.22.0}/examples/df_mp2_einsum.py +0 -0
  48. {trntensor-0.20.0 → trntensor-0.22.0}/infra/terraform/README.md +0 -0
  49. {trntensor-0.20.0 → trntensor-0.22.0}/infra/terraform/main.tf +0 -0
  50. {trntensor-0.20.0 → trntensor-0.22.0}/mkdocs.yml +0 -0
  51. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/autotune_dispatch.py +0 -0
  52. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/bench_native_einsum.py +0 -0
  53. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/bench_native_kernels.py +0 -0
  54. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/bench_to_md.py +0 -0
  55. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/run_benchmarks.sh +0 -0
  56. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/run_neuron_profile.sh +0 -0
  57. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/run_neuron_tests.sh +0 -0
  58. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/run_reduce_parallel_multirank.py +0 -0
  59. {trntensor-0.20.0 → trntensor-0.22.0}/scripts/run_simulator_tests.sh +0 -0
  60. {trntensor-0.20.0 → trntensor-0.22.0}/setup.cfg +0 -0
  61. {trntensor-0.20.0 → trntensor-0.22.0}/tests/conftest.py +0 -0
  62. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_decompose.py +0 -0
  63. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_host_output.py +0 -0
  64. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_nki.py +0 -0
  65. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_nki_kernels.py +0 -0
  66. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_nki_sim.py +0 -0
  67. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_parallel.py +0 -0
  68. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_plan.py +0 -0
  69. {trntensor-0.20.0 → trntensor-0.22.0}/tests/test_sr_runtime.py +0 -0
  70. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/decompose.py +0 -0
  71. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/einsum.py +0 -0
  72. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/nki/__init__.py +0 -0
  73. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/nki/collectives.py +0 -0
  74. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/parallel.py +0 -0
  75. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor/py.typed +0 -0
  76. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor.egg-info/dependency_links.txt +0 -0
  77. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor.egg-info/requires.txt +0 -0
  78. {trntensor-0.20.0 → trntensor-0.22.0}/trntensor.egg-info/top_level.txt +0 -0
  79. {trntensor-0.20.0 → trntensor-0.22.0}/uv.lock +0 -0
@@ -7,6 +7,95 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.22.0] — 2026-11-01
11
+
12
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
13
+
14
+ Headline: **correctness fix:** in every release through 0.21.0, on every backend, `einsum` planned matmul/bmm without checking index order, so transposed or permuted outputs came back in the wrong layout (`ij,jk->ki` returned `A@B`, silently for square operands) and non-canonical batched operands raised. 228 of 364 two-operand cases were wrong or raised (#65, #64). Also: `df_exchange` tiling minimises partial SYRK tiles, so K at n_ao=970 drops from 118 to 94 ms (#66).
15
+
16
+ ### Fixed
17
+
18
+ - **`einsum` returned the wrong layout for transposed or permuted outputs**
19
+ (silent). Affects **every release through 0.21.0**, on every backend
20
+ (PyTorch included). The planner chose the `matmul` / `bmm` strategy without
21
+ checking index order, so `einsum("ij,jk->ki", A, B)` returned `A @ B`
22
+ (shape `(i, k)`, and for square operands the transpose with no error), the
23
+ permuted batched outputs (`bij,bjk->bki` etc.) returned `(b, i, k)`, and
24
+ non-canonical batched operands (`bji,...`, `...,bkj`, `ibj,...`) raised.
25
+ `matmul` is now planned only for outputs `[A free, B free]` and `bmm` only
26
+ for exactly `bij,bjk->bik`; the rest run through `torch.einsum` (#64).
27
+
28
+ ### Changed
29
+
30
+ - **`df_exchange` tiles naux to minimise the SYRK's partial aux tiles (#66, #60).**
31
+ K at n_ao = 970 takes 93.8 ms instead of 118 ms at LNC=2, and 187 ms
32
+ instead of 230 ms at LNC=1. The error against float64 is 6.2e-7 (was
33
+ 8.1e-7) relative to max |K|.
34
+ - Aux chunks can now be 128 multiples with a short last chunk of
35
+ `naux mod width`. Before, the width had to divide naux.
36
+ `df_half_packed_kernel` takes `tp` and `tail` and gathers from the packed
37
+ rows viewed as `(npair·naux / W, W)`, `W = gcd(naux, tp)`. `B` is still
38
+ not copied.
39
+ - `df_half_tiling` first minimises the 128-row tiles over the SYRK
40
+ launches (`df_syrk_tiles`), because each partial tile there costs a full
41
+ one. Next it prefers a divisor of naux, then the old order.
42
+ - At naux = 4686 that means chunks of 256 with a 78 tail, 37 tiles
43
+ instead of 44.
44
+ - n_ao = 250 and 490 keep their previous tilings, which already reach
45
+ the minimum.
46
+ - `df_groups` folds a lone short last chunk into the previous launch group.
47
+ - The launch-1 SBUF budget is now 176 KiB (was 160 KiB), so that
48
+ TP = 256, NUB = 8, NVC = 16 fits at n_ao = 970. This tiling is 7 ms
49
+ faster than NVC = 8.
50
+ - naux with no divisor in [32, 512] now runs the kernels, not aten.
51
+ - `TRNTENSOR_DF_K_TP` forces the chunk width.
52
+
53
+ ## [0.21.0] — 2026-11-01
54
+
55
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
56
+
57
+ Headline: new fused DF exchange and Coulomb builds, `trntensor.df_exchange` / `df_coulomb`, which read packed integrals in place without building the square: K at n_ao=970 is 2.6× faster (304 → 118 ms) at unchanged error, and DF-RHF SCF at n_ao=970 converges in 4.71 s instead of 9.68 s (#62, #60).
58
+
59
+ ### Added
60
+
61
+ - **`trntensor.df_exchange(B, C_occ, alpha=1.0)`: the DF exchange matrix
62
+ straight from packed three-centre integrals (#60).**
63
+ `K = alpha·Σ_{i,P} X X^T` with `X[i,ν,P] = Σ_λ C_occ[λ,i] B[λν,P]`; for a
64
+ closed-shell SCF, `alpha=2`.
65
+ - On the native TorchNeuron path it is two NKI launches per group of aux
66
+ chunks. `df_half_packed_kernel` gathers the packed rows in place
67
+ (batched indirect DMA, as in `ao_to_mo_trn2_packed_kernel`) and forms
68
+ the half-transformed `Xt[P, i, ν]` with the aux index on partitions.
69
+ `df_exchange_syrk_kernel` accumulates K in PSUM over 128-row aux tiles,
70
+ computes only the upper-triangle strips and mirrors them on the Tensor
71
+ Engine. No `(n, n, naux)` square is built, `B` is not copied or padded,
72
+ and both physical cores work at LNC=2 (`program_id` split, no grids).
73
+ - `"auto"` uses it for device-resident packed `B` from
74
+ `nocc·nbasis²·naux` = 1e7; `TRNTENSOR_DF_EXCHANGE=auto|trn2|aten`
75
+ overrides. Elsewhere it is a row gather, one einsum and one GEMM.
76
+ - Trn2, one logical core, PySCF C_kH_2k+2 cc-pVDZ / cc-pvdz-jkfit, fp32,
77
+ against the unpack + einsum + `trnblas.syrk` K of trnsolver's DF-RHF
78
+ example: n_ao = 250 / 490 / 970 went 3.17 → 2.18, 15.5 → 9.33 and
79
+ 304 → 118 ms at LNC=2 (1.5x / 1.7x / 2.6x), and 4.71 → 3.46, 25.9 →
80
+ 16.9 and 424 → 230 ms at LNC=1. K error against float64 is unchanged
81
+ (8.1e-7 vs 8.3e-7 relative to max |K| at 970).
82
+ - In that example (with `df_coulomb` below, LNC=2, time to convergence)
83
+ the SCF went 352 → 229 ms at n_ao = 250, 756 → 587 ms at 490 and
84
+ 9.68 → 4.71 s at 970 (J/K stage 365 → 163 ms per iteration).
85
+ - **`trntensor.df_coulomb(B, D)`: the DF Coulomb matrix from the same packed
86
+ integrals (#60).** Two NKI launches each stream `B` once in contiguous
87
+ 128-row tiles with one fused Vector Engine instruction per tile (`d = Bᵀp`,
88
+ then `J = B d`). `TRNTENSOR_DF_COULOMB=auto|trn2|aten`. Against the two
89
+ GEMVs per aux block it replaces: 3.81 → 2.90, 12.6 → 8.83 and 86.7 →
90
+ 46.0 ms at n_ao = 250 / 490 / 970 (LNC=2), 126 → 81.7 ms at 970 (LNC=1),
91
+ error 2.8e-7 vs 1.9e-7 relative to max |J|. It also runs on a single
92
+ 8.8 GB block, where the aten GEMV needed a 26.7 GB graph. A packed
93
+ `(npair,)` density gives a packed J, so blocked callers pack once.
94
+ - Kernels: `df_half_packed_kernel`, `df_exchange_syrk_kernel`,
95
+ `df_coulomb_d_kernel`, `df_coulomb_j_kernel` (gridless, `num_programs()`
96
+ split, MLIR-verified at lnc=1 and lnc=2). Tiling helpers
97
+ `df_half_tiling`, `df_group_chunks`, `df_exchange_blocks`.
98
+
10
99
  ## [0.20.0] — 2026-10-31
11
100
 
12
101
  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.20.0
3
+ Version: 0.22.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
@@ -133,7 +133,7 @@ core, factors = trntensor.tucker_decompose(tensor, ranks=(5, 5, 5))
133
133
  - [x] CP decomposition (ALS)
134
134
  - [x] Tucker decomposition (HOSVD)
135
135
  - [x] DF-MP2 einsum example
136
- - [x] NKI fused contraction kernels (`mp2_energy`, `ao_to_mo_transform`)
136
+ - [x] NKI fused contraction kernels (`mp2_energy`, `ao_to_mo_transform`, `df_exchange`, `df_coulomb`)
137
137
  - [x] Device operand residency (`to_device` / `from_device`; `to_xla` / `from_xla` kept)
138
138
  - [x] Native TorchNeuron dispatch (Trn2/Trn3, `torch.ops.trntensor.*`) alongside PyTorch/XLA (Trn1)
139
139
  - [x] NKI CPU simulator + `nki-simulator` CI gate
@@ -95,7 +95,7 @@ core, factors = trntensor.tucker_decompose(tensor, ranks=(5, 5, 5))
95
95
  - [x] CP decomposition (ALS)
96
96
  - [x] Tucker decomposition (HOSVD)
97
97
  - [x] DF-MP2 einsum example
98
- - [x] NKI fused contraction kernels (`mp2_energy`, `ao_to_mo_transform`)
98
+ - [x] NKI fused contraction kernels (`mp2_energy`, `ao_to_mo_transform`, `df_exchange`, `df_coulomb`)
99
99
  - [x] Device operand residency (`to_device` / `from_device`; `to_xla` / `from_xla` kept)
100
100
  - [x] Native TorchNeuron dispatch (Trn2/Trn3, `torch.ops.trntensor.*`) alongside PyTorch/XLA (Trn1)
101
101
  - [x] NKI CPU simulator + `nki-simulator` CI gate
@@ -5,5 +5,5 @@ trntensor's public API is organized into four modules:
5
5
  - **[einsum](einsum.md)** — `einsum`, `multi_einsum`
6
6
  - **[plan](plan.md)** — `plan_contraction`, `ContractionPlan`, `estimate_flops`
7
7
  - **[decompose](decompose.md)** — `cp_decompose`, `tucker_decompose`, and reconstructors
8
- - **[quantum](quantum.md)** — fused chemistry primitives (`mp2_energy`)
8
+ - **[quantum](quantum.md)** — fused chemistry primitives (`mp2_energy`, `ao_to_mo_transform`, `df_exchange`, `df_coulomb`)
9
9
  - **[nki](nki.md)** — backend dispatch (`set_backend`, `get_backend`, `HAS_NKI`)
@@ -120,6 +120,8 @@ supported in maintenance mode."
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
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_DF_EXCHANGE=auto\|trn2\|aten` | Native path: force the `df_exchange` executor (`trn2` = `df_half_packed_kernel` + `df_exchange_syrk_kernel` on packed integrals; `aten` = row gather + einsum + one GEMM). `auto` uses the kernels for device-resident packed `B` from `nocc·nbasis²·naux` = 1e7 (#60). |
124
+ | `TRNTENSOR_DF_COULOMB=auto\|trn2\|aten` | Native path: force the `df_coulomb` executor (`trn2` = `df_coulomb_d_kernel` + `df_coulomb_j_kernel`; `aten` = two GEMVs). `auto` uses the kernels for device-resident packed `B` from `npair·naux` = 1e7 (#60). |
123
125
  | `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
126
  | `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). |
125
127
  | `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. |
@@ -265,6 +267,17 @@ The original AO→MO and MP2 kernels remain the XLA-path (Trn1) kernels. See
265
267
  - `batched_matmul_kernel(a, b)` — per-batch-slice matmul. Batch dim
266
268
  iterated via `nl.affine_range`; each slice reuses the stationary-A
267
269
  tile layout.
270
+ - `df_half_packed_kernel(eri_v, img, C_occ, nub, tp, tail)` and
271
+ `df_exchange_syrk_kernel(xt, kin, banks)` — the fused DF exchange build
272
+ behind `trntensor.df_exchange` (#60): packed-row gather and half transform
273
+ into `Xt[P, i, ν]` (aux on partitions), then the PSUM SYRK over aux tiles
274
+ with upper-triangle strips mirrored on the Tensor Engine. Tilings from
275
+ `df_half_tiling`, `df_group_chunks`, `df_groups`, `df_syrk_tiles` and
276
+ `df_exchange_blocks`.
277
+ - `df_coulomb_d_kernel(B, pw)` and `df_coulomb_j_kernel(B, d_b)` — the DF
278
+ Coulomb build behind `trntensor.df_coulomb` (#60): `d = Bᵀ pw` and
279
+ `J = B d`, each streaming packed `B` once in 128-row tiles on the Vector
280
+ Engine.
268
281
 
269
282
  The DF-MP2 pair pattern `einsum("ap,bp->ab")` is served by
270
283
  `matmul_kernel` through the planner's `transB=True` route — no
@@ -217,3 +217,165 @@ Kernel alone, device-resident, warm (fp32; padded `nvir` included):
217
217
 
218
218
  - Both NKI kernels need `nocc ≤ 128`; larger `nocc` runs the aten steps (native) or raises `NotImplementedError` (XLA).
219
219
  - The `(nocc, nbasis, naux)` intermediate goes through kernel-scratch HBM between the two stages, as it does between the two aten einsums. Stage 1 leaves `i` on the partition axis, and stage 2 needs `ν` there.
220
+
221
+ ## `trntensor.df_exchange(B, C_occ, alpha=1.0) -> Tensor`
222
+
223
+ Density-fitted exchange matrix straight from packed three-centre integrals (#60).
224
+
225
+ ```
226
+ K[μ, ν] = alpha · Σ_{i, P} X[i, μ, P] X[i, ν, P], X[i, ν, P] = Σ_λ C_occ[λ, i] B[λν, P]
227
+ ```
228
+
229
+ For a closed-shell density `D = 2 C_occ C_occᵀ`, the SCF exchange matrix is
230
+ `df_exchange(B, C_occ, alpha=2.0)`.
231
+
232
+ ### Arguments
233
+
234
+ - `B` — the packed lower triangle `(npair, naux)` (row `μ(μ+1)/2 + ν`,
235
+ `pack_tril` order), PySCF's `_cderi` `(naux, npair)`, or the full
236
+ `(nbasis, nbasis, naux)` square (aten route).
237
+ - `C_occ: (nbasis, nocc)` — occupied orbital coefficients.
238
+ - `alpha` — scale factor.
239
+
240
+ ### Returns
241
+
242
+ The symmetric `(nbasis, nbasis)` matrix, on `B`'s device.
243
+
244
+ ### Example — the K build of a DF-RHF iteration
245
+
246
+ ```python
247
+ B_d = B_packed.to("neuron") # once: (npair, naux), never unpacked
248
+ K = trntensor.df_exchange(B_d, C_occ_d, alpha=2.0)
249
+ ```
250
+
251
+ ### Backend behaviour
252
+
253
+ - **Native TorchNeuron (Trn2/Trn3): two NKI launches per group of aux chunks.**
254
+ - `df_half_packed_kernel` gathers the packed rows in place with batched
255
+ indirect DMA (the gather of `ao_to_mo_transform`'s packed kernel, #54)
256
+ and forms the half-transformed `Xt[P, i, ν]` with the aux index on the
257
+ partition axis: each gathered `(128 λ, aux)` block is the stationary
258
+ operand and the resident `C_occ` λ-tile the moving one. The full
259
+ `(n, n, naux)` square never exists.
260
+ - `df_exchange_syrk_kernel` accumulates `K` in PSUM over 128-row aux
261
+ tiles, computes only the upper-triangle 128-row strips, and mirrors them
262
+ on the Tensor Engine on the way out. Two running partial Ks are chained
263
+ through the launches, so there are no extra adds per group.
264
+ - Both launches split across the programs of the logical core: the first
265
+ by aux chunks (or ν groups), the second by occupied orbitals (padded to
266
+ an even count). At LNC=2 both physical cores work.
267
+ - `B` is never copied or padded. The aux chunk width is a divisor of
268
+ naux, or a multiple of 128 with a short last chunk of `naux mod width`
269
+ (#60). Traced NKI loops unroll, so the dispatcher runs the pair
270
+ over groups of chunks to bound the compile time (about a minute per
271
+ shape at n_ao = 970) and the `Xt` scratch.
272
+ - The tiling minimises the 128-row aux tiles of the SYRK launches: a
273
+ partial tile there costs a full one, and each group of chunks can end
274
+ in one. At n_ao = 970 (naux = 4686 = 2·3·11·71) the divisor 213 in
275
+ pairs gave 44 tiles for 4686 rows; chunks of 256 in pairs, with the
276
+ 78-wide last chunk in the last group, give the minimum, 37. Where a
277
+ divisor already reaches the minimum (n_ao = 250 and 490) it is kept.
278
+ - `"auto"` uses the kernels for device-resident `B` with `nocc ≤ 512`
279
+ once `nocc·nbasis²·naux` reaches 1e7 multiply-adds.
280
+ `TRNTENSOR_DF_EXCHANGE=auto|trn2|aten` overrides the choice.
281
+ - **Otherwise (CPU, small problems)**: aten on `B`'s device. Blocks of rows
282
+ of the square are gathered (1 GiB at a time), half-transformed with one
283
+ einsum into `(ν, i, P)` order, and `K` is one GEMM.
284
+
285
+ ### Measured on Trn2
286
+
287
+ PySCF cc-pVDZ / cc-pvdz-jkfit integrals, fp32, warm medians, device-resident
288
+ inputs, one logical core. *Unpack path* is the K build of
289
+ `trnsolver/examples/scf_df_rhf.py` before this change: `unpack_tril` of
290
+ aux blocks (the square kept resident when it fits in 4 GB), the
291
+ half-transform `einsum`, and `trnblas.syrk`. Error is the max-abs error over
292
+ max |K| against float64.
293
+
294
+ | system | n_ao / naux / nocc | LNC | unpack path | `df_exchange` | speedup | error, unpack | error, `df_exchange` |
295
+ |---|---|---|---|---|---|---|---|
296
+ | water | 24 / 116 / 5 | 2 | 0.82 ms | 1.32 ms (kernels; `"auto"` runs aten, 1.16 ms) | — | 7.5e-8 | 1.9e-7 |
297
+ | benzene | 114 / 558 / 21 | 2 | 1.43 ms | 1.35 ms | 1.06x | 5.8e-7 | 2.6e-7 |
298
+ | C10H22 | 250 / 1206 / 41 | 2 | 3.17 ms | 2.18 ms | 1.46x | 3.6e-7 | 4.8e-7 |
299
+ | C20H42 | 490 / 2366 / 81 | 2 | 15.5 ms | 9.33 ms | 1.66x | 6.1e-7 | 6.6e-7 |
300
+ | C40H82 | 970 / 4686 / 161 | 2 | 304 ms | 118 ms | 2.58x | 8.3e-7 | 8.1e-7 |
301
+ | C10H22 | 250 / 1206 / 41 | 1 | 4.71 ms | 3.46 ms | 1.36x | 3.6e-7 | 8.1e-7 |
302
+ | C20H42 | 490 / 2366 / 81 | 1 | 25.9 ms | 16.9 ms | 1.53x | 6.1e-7 | 1.1e-6 |
303
+ | C40H82 | 970 / 4686 / 161 | 1 | 424 ms | 230 ms | 1.84x | 8.3e-7 | 1.5e-6 |
304
+
305
+ - Up to n_ao = 490 the unpack path keeps its square resident (it fits in
306
+ 4 GB), so it pays no gather per call; at 970 it unpacks 9 aux blocks per
307
+ call. `df_exchange` never builds the square.
308
+ - `df_exchange` scales 1.59x / 1.81x / 1.95x from LNC=1 to LNC=2 at
309
+ n_ao = 250 / 490 / 970.
310
+ - At n_ao = 970 the table's 118 ms used 11 launch pairs of 2 aux chunks of
311
+ 213. Chunks of 256 (NUB = 8, NVC = 16) take 9 pairs, the last one holding
312
+ the 78-wide chunk. K then takes 93.8 ms at LNC=2 and 187 ms at LNC=1
313
+ (from 118 and 230 ms), with error 6.2e-7 and 1.1e-6 (from 8.1e-7 and
314
+ 1.5e-6).
315
+ - The gain is in the SYRK: 3.1 ms per 512-row group against 3.7 ms per
316
+ 426-row group. The half transform takes about as long per aux row
317
+ either way.
318
+ - Summed per-launch times of other tilings: groups of 3 chunks of 213
319
+ (5 tiles per 639 rows) 117 ms; 256 with NVC = 8 (the earlier 160 KiB
320
+ SBUF budget) 103 ms; 256 with NUB = 4 115 ms.
321
+ - At n_ao = 490 the 128-multiple widths 256 and 384 were slower in the half
322
+ transform than 338: 8.9 and 9.1 ms against 6.1 ms per 6–8-chunk launch.
323
+ Widths whose last 128-row tile is partial (320–352) ran as fast as 338.
324
+ So the divisor tiling stays where it already gives the fewest SYRK tiles.
325
+ - Padding naux to 4736 (chunks of 128, so no partial tiles) measured
326
+ 126 ms. Eight PSUM banks per SYRK pass instead of six made no difference.
327
+ - Without the `Xt[P, g, i, v]` store layout (ν innermost, 64-byte DMA
328
+ writes) the same call took 488 ms.
329
+
330
+ ### Current limitations
331
+
332
+ - `nocc ≤ 512` (one PSUM bank of the stage-1 output).
333
+ - The gather indices are 32-bit: `npair·naux / gcd(naux, width)` must stay
334
+ below 2^31, which limits the chunk widths for very large `B`.
335
+ - The kernels run the Tensor Engine in fp32, which is what bounds them now.
336
+ At n_ao = 970 the half transform runs at about 17 TFLOP/s and the SYRK at
337
+ about 26 TFLOP/s per LNC=2 core (each counts the padded tiles).
338
+ - Host `B` runs the aten route on the host; upload it once and keep it on
339
+ the device.
340
+
341
+ ## `trntensor.df_coulomb(B, D) -> Tensor`
342
+
343
+ The density-fitted Coulomb matrix from the same packed integrals (#60).
344
+
345
+ ```
346
+ J[μ, ν] = Σ_P B[μν, P] d[P], d[P] = Σ_{λσ} D[λ, σ] B[λσ, P]
347
+ ```
348
+
349
+ `D` is a symmetric `(nbasis, nbasis)` density, or its weighted packed form
350
+ `(npair,)` (`w·D[μ, ν]` for `ν ≤ μ`, `w` = 1 on the diagonal and 2 off
351
+ it), in which case the packed `(npair,)` J comes back. A caller that keeps
352
+ the aux index in blocks then packs and unpacks once per call instead of per
353
+ block; on the device those are element gathers.
354
+
355
+ - **Native TorchNeuron**: two launches, `df_coulomb_d_kernel` and
356
+ `df_coulomb_j_kernel`. Each streams `B` once in contiguous 128-row tiles
357
+ (DMAs up to 4096 columns wide), rows split across the programs, with fused
358
+ Vector Engine instructions: a multiply-add per tile for `d`, a
359
+ multiply-reduce per 128 columns for `J`. The partial sums are kept short:
360
+ `d` in groups of 32 tiles, `J` in 128-column chunks. At n_ao = 970 one
361
+ fp32 chain over all 4686 columns gave J 2.4e-6 off float64 and
362
+ 512-column chunks 5.7e-7; 128-column chunks give 2.8e-7. The < 256
363
+ leftover rows run as aten GEMVs. `"auto"` uses the kernels for
364
+ device-resident `B` from `npair·naux` = 1e7.
365
+ `TRNTENSOR_DF_COULOMB=auto|trn2|aten` overrides.
366
+ - **Otherwise**: two GEMVs.
367
+
368
+ Measured on Trn2 (fp32, warm; the J of `scf_df_rhf.py`'s `DFJK` on the
369
+ core-guess density, error vs float64 relative to max |J|):
370
+
371
+ | n_ao / naux | LNC | two GEMVs per aux block (before) | `df_coulomb`, one block | speedup |
372
+ |---|---|---|---|---|
373
+ | 250 / 1206 | 2 | 3.81 ms, 2.1e-7 | 2.90 ms, 2.4e-7 | 1.31x |
374
+ | 490 / 2366 | 2 | 12.6 ms, 1.9e-7 | 8.83 ms, 2.7e-7 | 1.43x |
375
+ | 970 / 4686 | 2 | 86.7 ms (9 blocks), 1.9e-7 | 46.0 ms, 2.8e-7 | 1.89x |
376
+ | 970 / 4686 | 1 | 126 ms (9 blocks), 2.4e-7 | 81.7 ms, 2.6e-7 | 1.55x |
377
+
378
+ It also allows a single block: at n_ao = 970 the aten GEMV on one 8.8 GB
379
+ block compiled to a 26.7 GB graph and did not fit in HBM. With the DMA as
380
+ narrow as the 128-column reduce, the kernel was descriptor-bound (76 ms at
381
+ 970).
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "trntensor"
7
- version = "0.20.0"
7
+ version = "0.22.0"
8
8
  description = "Tensor contractions for AWS Trainium via NKI"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -786,3 +786,56 @@ class TestPrecisionPromises:
786
786
  assert calls == [[("cpu", torch.float64), ("cpu", torch.float64)]]
787
787
  assert C.dtype == torch.float32 and C.device.type == "cpu"
788
788
  torch.testing.assert_close(C, (A.double() @ B.double()).float())
789
+
790
+
791
+ def _two_operand_subscripts():
792
+ import itertools
793
+
794
+ subs = set()
795
+ for out in ("ik", "ki"):
796
+ for a in ("ij", "ji"):
797
+ for b in ("jk", "kj"):
798
+ subs.add(f"{a},{b}->{out}")
799
+ for out in itertools.permutations("bik"):
800
+ for a in ("bij", "bji", "ibj"):
801
+ for b in ("bjk", "bkj", "jbk"):
802
+ subs.add(f"{a},{b}->{''.join(out)}")
803
+ subs |= {"ij,jk->i", "ij,jk->k", "ij,jk->", "bij,bjk->bi", "ij,j->i", "i,j->ji"}
804
+ return sorted(subs)
805
+
806
+
807
+ class TestOutputOrder:
808
+ """The matmul/bmm plans return op(A) @ op(B); a transposed or permuted output,
809
+ or non-canonical batched operands, must not take them (#64)."""
810
+
811
+ @pytest.mark.parametrize("subscripts", _two_operand_subscripts())
812
+ @pytest.mark.parametrize("square", [False, True])
813
+ def test_matches_torch_einsum(self, subscripts, square):
814
+ sizes = dict(zip("bijk", (2, 5, 5, 5) if square else (2, 6, 5, 7), strict=True))
815
+ g = torch.Generator().manual_seed(0)
816
+ ins = subscripts.split("->")[0].split(",")
817
+ ops = [torch.randn(*[sizes[c] for c in t], generator=g, dtype=torch.float64) for t in ins]
818
+ want = torch.einsum(subscripts, *ops)
819
+ torch.testing.assert_close(trntensor.einsum(subscripts, *ops), want)
820
+ out = torch.randn(want.shape, generator=g, dtype=torch.float64)
821
+ got = trntensor.einsum(subscripts, *ops, alpha=0.7, beta=0.5, out=out.clone())
822
+ torch.testing.assert_close(got, 0.7 * want + 0.5 * out)
823
+
824
+ @pytest.mark.parametrize(
825
+ "subscripts,strategy",
826
+ [
827
+ ("ij,jk->ik", "matmul"),
828
+ ("ji,kj->ik", "matmul"),
829
+ ("ij,jk->ki", "torch"),
830
+ ("ij,jk->i", "torch"),
831
+ ("bij,bjk->bik", "bmm"),
832
+ ("bij,bjk->bki", "torch"),
833
+ ("bji,bjk->bik", "torch"),
834
+ ("ibj,bjk->bik", "torch"),
835
+ ],
836
+ )
837
+ def test_strategy(self, subscripts, strategy):
838
+ sizes = dict(zip("bijk", (2, 6, 5, 7), strict=True))
839
+ ins = subscripts.split("->")[0].split(",")
840
+ ops = [torch.randn(*[sizes[c] for c in t]) for t in ins]
841
+ assert trntensor.plan_contraction(subscripts, *ops).strategy == strategy
@@ -9,6 +9,7 @@ CPU-only: ``torch_neuronx`` and ``torch_xla`` are replaced with stand-ins via
9
9
  """
10
10
 
11
11
  import importlib.util
12
+ import math
12
13
  import subprocess
13
14
  import sys
14
15
  import types
@@ -31,6 +32,10 @@ EXPECTED_OPS = {
31
32
  "mp2_energy_row",
32
33
  "ao_to_mo_trn2",
33
34
  "ao_to_mo_trn2_packed",
35
+ "df_half_packed",
36
+ "df_exchange_syrk",
37
+ "df_coulomb_d",
38
+ "df_coulomb_j",
34
39
  }
35
40
 
36
41
 
@@ -133,6 +138,10 @@ def native_host(monkeypatch):
133
138
  "mp2_energy_row_kernel",
134
139
  "ao_to_mo_trn2_kernel",
135
140
  "ao_to_mo_trn2_packed_kernel",
141
+ "df_half_packed_kernel",
142
+ "df_exchange_syrk_kernel",
143
+ "df_coulomb_d_kernel",
144
+ "df_coulomb_j_kernel",
136
145
  ):
137
146
  monkeypatch.setattr(_kernels, kname, no_raw_kernel, raising=False)
138
147
  # Force NKI: under "auto" the native path runs the fused quantum
@@ -437,6 +446,195 @@ class TestPublicApiOnNativePath:
437
446
  torch.testing.assert_close(out, trntensor.ao_to_mo_transform(eri, C_occ, C_vir))
438
447
  assert native_host == []
439
448
 
449
+ @pytest.mark.parametrize(
450
+ "nbasis,naux,nocc,group,tp",
451
+ [
452
+ (40, 6, 5, 0, 0),
453
+ (130, 30, 7, 0, 0),
454
+ (40, 600, 6, 1, 0),
455
+ (40, 600, 6, 1, 256), # 256 + 256 + 88
456
+ (40, 600, 6, 0, 512), # 512 + 88 in one launch
457
+ (40, 1100, 6, 2, 256), # groups (0, 2), (2, 5): the 76 tail joins
458
+ ],
459
+ )
460
+ def test_df_exchange_routes_to_the_two_ops(
461
+ self, native_host, monkeypatch, nbasis, naux, nocc, group, tp
462
+ ):
463
+ """#60: replaying the half kernel's batched gather from the index
464
+ images on CPU rebuilds Xt, and the SYRK stand-in's two partials add
465
+ up to K, with chunks dividing naux or 128-multiple chunks and a
466
+ short last one."""
467
+ if tp:
468
+ monkeypatch.setenv("TRNTENSOR_DF_K_TP", str(tp))
469
+
470
+ def half_op(eri_v, img, C_occ, nub=8, tp=0, tail=0):
471
+ npc, nvg = img.shape[0], img.shape[1]
472
+ w0, nbp = eri_v.shape[1], C_occ.shape[0]
473
+ tp = tp or w0
474
+ widths = [tp] * (npc - 1) + [tail or tp]
475
+ nvc, nkb = nbp // nvg, nbp // 128
476
+ assert img.dtype == torch.uint32 and img.shape == (npc, nvg, 128, nkb * nvc)
477
+ idx = img.view(torch.int32).long()
478
+ flat = eri_v.reshape(-1)
479
+ full = torch.empty(nbp, nbp, sum(widths))
480
+ for c, w in enumerate(widths):
481
+ for g in range(nvg):
482
+ for k in range(nkb):
483
+ for b in range(nvc // nub):
484
+ blk = idx[c, g, :, k * nvc + b * nub : k * nvc + (b + 1) * nub]
485
+ starts = blk.T.flatten() * w0
486
+ rows = flat[starts[:, None] + torch.arange(w)].reshape(128, nub, w)
487
+ v0 = g * nvc + b * nub
488
+ full[k * 128 : (k + 1) * 128, v0 : v0 + nub, c * tp : c * tp + w] = rows
489
+ x = torch.einsum("li,lnP->Pin", C_occ, full) # (P, i, ν)
490
+ return x.reshape(sum(widths), -1, nvg, nvc).permute(0, 2, 1, 3).contiguous()
491
+
492
+ def syrk_op(xt, kin, banks=6):
493
+ nr, nvg, nop, nvc = xt.shape
494
+ assert nop % 2 == 0 # nocc padded even for the program split
495
+ xm = xt.permute(1, 3, 0, 2).reshape(nvg * nvc, -1)
496
+ k = xm @ xm.T
497
+ return kin + torch.stack([0.25 * k, 0.75 * k])
498
+
499
+ _install_ops(monkeypatch, native_host, df_half_packed=half_op, df_exchange_syrk=syrk_op)
500
+ if group: # one aux chunk per launch pair
501
+ monkeypatch.setattr(dispatch, "df_group_chunks", lambda *a: group)
502
+ g = torch.Generator().manual_seed(nbasis)
503
+ eri = torch.randn(nbasis, nbasis, naux, generator=g)
504
+ eri = 0.5 * (eri + eri.transpose(0, 1))
505
+ C = torch.randn(nbasis, nocc, generator=g)
506
+ out = trntensor.df_exchange(trntensor.pack_tril(eri), C, alpha=2.0)
507
+ X = torch.einsum("li,lnP->inP", C, eri)
508
+ ref = 2.0 * torch.einsum("imP,inP->mn", X, X)
509
+ # fp32 sums of up to 600·nocc terms: compare against max |K|.
510
+ assert float((out - ref).abs().max()) <= 1e-5 * float(ref.abs().max())
511
+ tp_, nub, _nvc = _kernels.df_half_tiling(naux, -(-nbasis // 128) * 128, nocc + nocc % 2)
512
+ assert tp_ == tp or not tp
513
+ tp = tp_
514
+ launches = len(_kernels.df_groups(naux, tp, group)) if group else 1
515
+ assert [c[0] for c in native_host] == ["df_half_packed", "df_exchange_syrk"] * launches
516
+ assert native_host[0][1]["nub"] == nub and native_host[0][1]["tp"] == tp
517
+ assert native_host[-2][1]["tail"] == naux % tp
518
+
519
+ @pytest.mark.parametrize("nbasis", [30, 40])
520
+ def test_df_coulomb_routes_to_the_two_ops(self, native_host, monkeypatch, nbasis):
521
+ """The kernels take 2·(npair // 256) full row tiles; the leftover rows
522
+ go through aten, and the result matches the reference J."""
523
+
524
+ def d_op(B, pw):
525
+ rows = (B.shape[0] // 256) * 256
526
+ d = B[:rows].T @ pw[:rows, 0]
527
+ return torch.stack([0.5 * d, 0.5 * d])[:, None, :]
528
+
529
+ def j_op(B, d_b):
530
+ rows = (B.shape[0] // 256) * 256
531
+ assert d_b.shape == (128, B.shape[1])
532
+ return (B[:rows] @ d_b[0]).reshape(-1, 128).T
533
+
534
+ _install_ops(monkeypatch, native_host, df_coulomb_d=d_op, df_coulomb_j=j_op)
535
+ g = torch.Generator().manual_seed(nbasis)
536
+ eri = torch.randn(nbasis, nbasis, 9, generator=g)
537
+ eri = 0.5 * (eri + eri.transpose(0, 1))
538
+ D = torch.randn(nbasis, nbasis, generator=g)
539
+ D = D + D.T
540
+ J = trntensor.df_coulomb(trntensor.pack_tril(eri), D)
541
+ ref = torch.einsum("mnP,P->mn", eri, torch.einsum("lsP,ls->P", eri, D))
542
+ torch.testing.assert_close(J, ref, atol=1e-3, rtol=1e-4)
543
+ assert [c[0] for c in native_host] == ["df_coulomb_d", "df_coulomb_j"]
544
+
545
+ def test_df_coulomb_route(self, monkeypatch):
546
+ monkeypatch.setattr(dispatch, "HAS_NKI", True)
547
+ monkeypatch.setattr(dispatch, "_use_simulator", lambda: False)
548
+ monkeypatch.setattr(dispatch, "_use_nki", lambda: True)
549
+ monkeypatch.setattr(dispatch, "_dispatch_path", "native")
550
+ monkeypatch.setattr(dispatch, "_NEURON_DEVICE", "meta")
551
+ big = torch.empty(31375, 1206, device="meta")
552
+ assert dispatch._df_coulomb_route(big) == "trn2"
553
+ assert dispatch._df_coulomb_route(torch.empty(31375, 1206)) == "aten"
554
+ assert dispatch._df_coulomb_route(torch.empty(300, 116, device="meta")) == "aten"
555
+ assert dispatch._df_coulomb_route(torch.empty(200, 116, device="meta")) == "aten"
556
+ monkeypatch.setenv("TRNTENSOR_DF_COULOMB", "trn2")
557
+ assert dispatch._df_coulomb_route(torch.empty(300, 116, device="meta")) == "trn2"
558
+
559
+ def test_df_exchange_aten_route_skips_the_kernels(self, native_host, monkeypatch):
560
+ monkeypatch.setenv("TRNTENSOR_DF_EXCHANGE", "aten")
561
+ _install_ops(monkeypatch, native_host)
562
+ eri = torch.randn(12, 12, 5)
563
+ eri = 0.5 * (eri + eri.transpose(0, 1))
564
+ C = torch.randn(12, 3)
565
+ X = torch.einsum("li,lnP->inP", C, eri)
566
+ out = trntensor.df_exchange(trntensor.pack_tril(eri), C)
567
+ torch.testing.assert_close(out, torch.einsum("imP,inP->mn", X, X), atol=1e-4, rtol=1e-4)
568
+ assert native_host == []
569
+
570
+ def test_df_exchange_route(self, monkeypatch):
571
+ monkeypatch.setattr(dispatch, "HAS_NKI", True)
572
+ monkeypatch.setattr(dispatch, "_use_simulator", lambda: False)
573
+ monkeypatch.setattr(dispatch, "_use_nki", lambda: True)
574
+ monkeypatch.setattr(dispatch, "_dispatch_path", "native")
575
+ monkeypatch.setattr(dispatch, "_NEURON_DEVICE", "meta")
576
+ npair = 256 * 257 // 2
577
+ dev = torch.empty(npair, 1206, device="meta")
578
+ assert dispatch._df_exchange_route(dev, 41, 256) == "trn2"
579
+ assert dispatch._df_exchange_route(torch.empty(npair, 1206), 41, 256) == "aten"
580
+ assert dispatch._df_exchange_route(dev, 513, 256) == "aten"
581
+ monkeypatch.setenv("TRNTENSOR_DF_EXCHANGE", "aten")
582
+ assert dispatch._df_exchange_route(dev, 41, 256) == "aten"
583
+ monkeypatch.setenv("TRNTENSOR_DF_EXCHANGE", "bogus")
584
+ with pytest.raises(ValueError):
585
+ dispatch._df_exchange_route(dev, 41, 256)
586
+
587
+ @pytest.mark.parametrize(
588
+ "naux,nb,nocc", [(1206, 256, 41), (2366, 512, 81), (4686, 1024, 161), (768, 256, 32)]
589
+ )
590
+ def test_df_half_tiling_fits_with_fewest_aux_tiles(self, naux, nb, nocc):
591
+ tp, nub, nvc = _kernels.df_half_tiling(naux, nb, nocc)
592
+ assert tp <= 512 and nb % nvc == 0 and nvc % nub == 0
593
+ assert naux % tp == 0 or tp % 128 == 0
594
+ assert _kernels.df_half_sbuf_bytes(nb, nocc, tp, nub, nvc) <= _kernels.DF_K_SBUF_BUDGET
595
+ npc = -(-naux // tp)
596
+ g = _kernels.df_group_chunks(npc, nb, tp, nub, nvc)
597
+ assert 1 <= g <= npc
598
+ # These shapes reach the fewest possible SYRK aux tiles.
599
+ assert _kernels.df_syrk_tiles(naux, tp, g) == -(-naux // 128)
600
+
601
+ def test_df_half_tiling_index_range_and_override(self, monkeypatch):
602
+ # 4686 = 2·3·11·71: 256 chunks with a 78 tail give the minimum 37
603
+ # SYRK aux tiles; the divisor 213 (2 chunks per group) needs 44.
604
+ assert _kernels.df_half_tiling(4686, 1024, 162) == (256, 8, 16)
605
+ assert _kernels.df_syrk_tiles(4686, 213, 2) == 44
606
+ assert _kernels.df_syrk_tiles(4686, 256, 2) == 37
607
+ # 2366 = 6·338 + 338: the divisor already reaches 19, so no tail.
608
+ assert _kernels.df_half_tiling(2366, 512, 82) == (338, 8, 32)
609
+ # Gather indices npair·naux / gcd(naux, tp) must fit 31 bits.
610
+ tp = _kernels.df_half_tiling(4686, 1024, 162, npair=10**6)[0]
611
+ assert 10**6 * 4686 // math.gcd(4686, tp) < 2**31
612
+ monkeypatch.setenv("TRNTENSOR_DF_K_TP", "213")
613
+ assert _kernels.df_half_tiling(4686, 1024, 162)[0] == 213
614
+
615
+ def test_df_groups_cover_the_chunks_and_absorb_a_lone_tail(self):
616
+ # 4686 = 18·256 + 78: groups of 2, the short chunk joins the last.
617
+ groups = _kernels.df_groups(4686, 256, 2)
618
+ assert groups[0] == (0, 2) and groups[-1] == (16, 19) and len(groups) == 9
619
+ assert _kernels.df_groups(2366, 338, 6) == [(0, 6), (6, 7)] # full last chunk
620
+ assert _kernels.df_groups(1100, 512, 2) == [(0, 3)]
621
+ assert _kernels.df_groups(600, 512, 1) == [(0, 2)]
622
+ for naux, tp, grp in ((4686, 256, 2), (1206, 201, 6), (700, 128, 3)):
623
+ groups = _kernels.df_groups(naux, tp, grp)
624
+ assert groups[0][0] == 0 and groups[-1][1] == -(-naux // tp)
625
+ assert all(a[1] == b[0] for a, b in zip(groups[:-1], groups[1:], strict=True))
626
+
627
+ @pytest.mark.parametrize("nb,banks", [(128, 6), (512, 6), (1024, 6), (1024, 2), (2048, 8)])
628
+ def test_df_exchange_blocks_cover_the_upper_triangle(self, nb, banks):
629
+ passes = _kernels.df_exchange_blocks(nb, banks)
630
+ cover = torch.zeros(nb // 128, nb // 128, dtype=torch.int64)
631
+ for blocks in passes:
632
+ assert 1 <= len(blocks) <= banks
633
+ for m, v0, w in blocks:
634
+ assert v0 >= 128 * m and w <= 512 and v0 + w <= nb
635
+ cover[m, v0 // 128 : (v0 + w) // 128] += 1
636
+ assert torch.equal(cover, torch.triu(torch.ones_like(cover)))
637
+
440
638
  def test_ao_to_mo_transform_legacy_routes_and_slices(self, native_host, monkeypatch):
441
639
  monkeypatch.setenv("TRNTENSOR_AO_TO_MO", "legacy")
442
640
  monkeypatch.setattr(dispatch, "_native_kernel_deprecations_emitted", set())
@@ -1231,3 +1429,15 @@ class TestLazyRegistration:
1231
1429
  m(32896 * 3, 256), m(3, 128, 512, dtype=torch.int32), m(256, 16), m(256, 512)
1232
1430
  )
1233
1431
  assert bp.shape == (16, 512, 768)
1432
+ xt = fake("df_half_packed")(
1433
+ m(32896 * 6, 201), m(2, 4, 128, 128, dtype=torch.int32), m(256, 42)
1434
+ )
1435
+ assert xt.shape == (402, 4, 42, 64)
1436
+ # 1206 = 512 + 512 + 182: rows (npair·1206 / 2, 2), a short last chunk.
1437
+ xs = fake("df_half_packed")(
1438
+ m(32896 * 603, 2), m(3, 4, 128, 128, dtype=torch.int32), m(256, 42), 8, 512, 182
1439
+ )
1440
+ assert xs.shape == (1206, 4, 42, 64)
1441
+ assert fake("df_exchange_syrk")(xt, m(2, 256, 256)).shape == (2, 256, 256)
1442
+ assert fake("df_coulomb_d")(m(31375, 1206), m(31375, 1)).shape == (2, 1, 1206)
1443
+ assert fake("df_coulomb_j")(m(31375, 1206), m(128, 1206)).shape == (128, 244)