trntensor 0.21.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.21.0 → trntensor-0.22.0}/CHANGELOG.md +43 -0
  2. {trntensor-0.21.0 → trntensor-0.22.0}/PKG-INFO +1 -1
  3. {trntensor-0.21.0 → trntensor-0.22.0}/docs/api/nki.md +3 -2
  4. {trntensor-0.21.0 → trntensor-0.22.0}/docs/api/quantum.md +30 -9
  5. {trntensor-0.21.0 → trntensor-0.22.0}/pyproject.toml +1 -1
  6. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_einsum.py +53 -0
  7. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_native_dispatch.py +71 -19
  8. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_nki_compile.py +16 -0
  9. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_nki_native.py +15 -5
  10. trntensor-0.22.0/tests/test_nki_tail_audit.py +274 -0
  11. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/__init__.py +1 -1
  12. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/nki/_kernels.py +146 -70
  13. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/nki/_native.py +14 -4
  14. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/nki/dispatch.py +27 -16
  15. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/plan.py +27 -4
  16. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor.egg-info/PKG-INFO +1 -1
  17. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor.egg-info/SOURCES.txt +1 -0
  18. {trntensor-0.21.0 → trntensor-0.22.0}/.github/workflows/ci.yml +0 -0
  19. {trntensor-0.21.0 → trntensor-0.22.0}/.github/workflows/notify-umbrella.yml +0 -0
  20. {trntensor-0.21.0 → trntensor-0.22.0}/.github/workflows/publish.yml +0 -0
  21. {trntensor-0.21.0 → trntensor-0.22.0}/.gitignore +0 -0
  22. {trntensor-0.21.0 → trntensor-0.22.0}/.pre-commit-config.yaml +0 -0
  23. {trntensor-0.21.0 → trntensor-0.22.0}/CLAUDE.md +0 -0
  24. {trntensor-0.21.0 → trntensor-0.22.0}/CODE_OF_CONDUCT.md +0 -0
  25. {trntensor-0.21.0 → trntensor-0.22.0}/CONTRIBUTING.md +0 -0
  26. {trntensor-0.21.0 → trntensor-0.22.0}/LICENSE +0 -0
  27. {trntensor-0.21.0 → trntensor-0.22.0}/README.md +0 -0
  28. {trntensor-0.21.0 → trntensor-0.22.0}/benchmarks/__init__.py +0 -0
  29. {trntensor-0.21.0 → trntensor-0.22.0}/benchmarks/bench_einsum.py +0 -0
  30. {trntensor-0.21.0 → trntensor-0.22.0}/docs/api/decompose.md +0 -0
  31. {trntensor-0.21.0 → trntensor-0.22.0}/docs/api/einsum.md +0 -0
  32. {trntensor-0.21.0 → trntensor-0.22.0}/docs/api/index.md +0 -0
  33. {trntensor-0.21.0 → trntensor-0.22.0}/docs/api/plan.md +0 -0
  34. {trntensor-0.21.0 → trntensor-0.22.0}/docs/architecture.md +0 -0
  35. {trntensor-0.21.0 → trntensor-0.22.0}/docs/aws_setup.md +0 -0
  36. {trntensor-0.21.0 → trntensor-0.22.0}/docs/benchmarks.md +0 -0
  37. {trntensor-0.21.0 → trntensor-0.22.0}/docs/contraction_patterns.md +0 -0
  38. {trntensor-0.21.0 → trntensor-0.22.0}/docs/design/matmul_dispatch_findings.md +0 -0
  39. {trntensor-0.21.0 → trntensor-0.22.0}/docs/design/matmul_kernel_profile.md +0 -0
  40. {trntensor-0.21.0 → trntensor-0.22.0}/docs/developing_kernels.md +0 -0
  41. {trntensor-0.21.0 → trntensor-0.22.0}/docs/index.md +0 -0
  42. {trntensor-0.21.0 → trntensor-0.22.0}/docs/installation.md +0 -0
  43. {trntensor-0.21.0 → trntensor-0.22.0}/docs/quickstart.md +0 -0
  44. {trntensor-0.21.0 → trntensor-0.22.0}/docs/tutorial_df_mp2.md +0 -0
  45. {trntensor-0.21.0 → trntensor-0.22.0}/examples/df_mp2_einsum.py +0 -0
  46. {trntensor-0.21.0 → trntensor-0.22.0}/infra/terraform/README.md +0 -0
  47. {trntensor-0.21.0 → trntensor-0.22.0}/infra/terraform/main.tf +0 -0
  48. {trntensor-0.21.0 → trntensor-0.22.0}/mkdocs.yml +0 -0
  49. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/autotune_dispatch.py +0 -0
  50. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/bench_native_einsum.py +0 -0
  51. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/bench_native_kernels.py +0 -0
  52. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/bench_to_md.py +0 -0
  53. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/run_benchmarks.sh +0 -0
  54. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/run_neuron_profile.sh +0 -0
  55. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/run_neuron_tests.sh +0 -0
  56. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/run_reduce_parallel_multirank.py +0 -0
  57. {trntensor-0.21.0 → trntensor-0.22.0}/scripts/run_simulator_tests.sh +0 -0
  58. {trntensor-0.21.0 → trntensor-0.22.0}/setup.cfg +0 -0
  59. {trntensor-0.21.0 → trntensor-0.22.0}/tests/conftest.py +0 -0
  60. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_decompose.py +0 -0
  61. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_host_output.py +0 -0
  62. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_nki.py +0 -0
  63. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_nki_kernels.py +0 -0
  64. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_nki_sim.py +0 -0
  65. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_parallel.py +0 -0
  66. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_plan.py +0 -0
  67. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_quantum.py +0 -0
  68. {trntensor-0.21.0 → trntensor-0.22.0}/tests/test_sr_runtime.py +0 -0
  69. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/decompose.py +0 -0
  70. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/einsum.py +0 -0
  71. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/nki/__init__.py +0 -0
  72. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/nki/collectives.py +0 -0
  73. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/parallel.py +0 -0
  74. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/py.typed +0 -0
  75. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor/quantum.py +0 -0
  76. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor.egg-info/dependency_links.txt +0 -0
  77. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor.egg-info/requires.txt +0 -0
  78. {trntensor-0.21.0 → trntensor-0.22.0}/trntensor.egg-info/top_level.txt +0 -0
  79. {trntensor-0.21.0 → trntensor-0.22.0}/uv.lock +0 -0
@@ -7,6 +7,49 @@ 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
+
10
53
  ## [0.21.0] — 2026-11-01
11
54
 
12
55
  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.21.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
@@ -267,12 +267,13 @@ The original AO→MO and MP2 kernels remain the XLA-path (Trn1) kernels. See
267
267
  - `batched_matmul_kernel(a, b)` — per-batch-slice matmul. Batch dim
268
268
  iterated via `nl.affine_range`; each slice reuses the stationary-A
269
269
  tile layout.
270
- - `df_half_packed_kernel(eri_v, img, C_occ, nub)` and
270
+ - `df_half_packed_kernel(eri_v, img, C_occ, nub, tp, tail)` and
271
271
  `df_exchange_syrk_kernel(xt, kin, banks)` — the fused DF exchange build
272
272
  behind `trntensor.df_exchange` (#60): packed-row gather and half transform
273
273
  into `Xt[P, i, ν]` (aux on partitions), then the PSUM SYRK over aux tiles
274
274
  with upper-triangle strips mirrored on the Tensor Engine. Tilings from
275
- `df_half_tiling`, `df_group_chunks` and `df_exchange_blocks`.
275
+ `df_half_tiling`, `df_group_chunks`, `df_groups`, `df_syrk_tiles` and
276
+ `df_exchange_blocks`.
276
277
  - `df_coulomb_d_kernel(B, pw)` and `df_coulomb_j_kernel(B, d_b)` — the DF
277
278
  Coulomb build behind `trntensor.df_coulomb` (#60): `d = Bᵀ pw` and
278
279
  `J = B d`, each streaming packed `B` once in 128-row tiles on the Vector
@@ -264,10 +264,17 @@ K = trntensor.df_exchange(B_d, C_occ_d, alpha=2.0)
264
264
  - Both launches split across the programs of the logical core: the first
265
265
  by aux chunks (or ν groups), the second by occupied orbitals (padded to
266
266
  an even count). At LNC=2 both physical cores work.
267
- - The aux chunk width is a divisor of naux, so `B` is never copied or
268
- padded. Traced NKI loops unroll, so the dispatcher runs the pair over
269
- groups of chunks to bound the compile time (about a minute per shape at
270
- n_ao = 970) and the `Xt` scratch.
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.
271
278
  - `"auto"` uses the kernels for device-resident `B` with `nocc ≤ 512`
272
279
  once `nocc·nbasis²·naux` reaches 1e7 multiply-adds.
273
280
  `TRNTENSOR_DF_EXCHANGE=auto|trn2|aten` overrides the choice.
@@ -300,17 +307,31 @@ max |K| against float64.
300
307
  call. `df_exchange` never builds the square.
301
308
  - `df_exchange` scales 1.59x / 1.81x / 1.95x from LNC=1 to LNC=2 at
302
309
  n_ao = 250 / 490 / 970.
303
- - At n_ao = 970 each launch pair takes 2 aux chunks of 213; there are 11
304
- pairs. Padding naux to 4736 (chunks of 128, so no partial tiles) measured
305
- 126 ms, not faster: the narrower gathered rows cost more than the partial
306
- tiles. Eight PSUM banks per SYRK pass instead of six made no difference.
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.
307
327
  - Without the `Xt[P, g, i, v]` store layout (ν innermost, 64-byte DMA
308
328
  writes) the same call took 488 ms.
309
329
 
310
330
  ### Current limitations
311
331
 
312
332
  - `nocc ≤ 512` (one PSUM bank of the stage-1 output).
313
- - `naux` needs a divisor in [32, 512] (else the aten route runs).
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`.
314
335
  - The kernels run the Tensor Engine in fp32, which is what bounds them now.
315
336
  At n_ao = 970 the half transform runs at about 17 TFLOP/s and the SYRK at
316
337
  about 26 TFLOP/s per LNC=2 core (each counts the padded tiles).
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "trntensor"
7
- version = "0.21.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
@@ -446,34 +447,47 @@ class TestPublicApiOnNativePath:
446
447
  assert native_host == []
447
448
 
448
449
  @pytest.mark.parametrize(
449
- "nbasis,naux,nocc,group", [(40, 6, 5, 0), (130, 30, 7, 0), (40, 600, 6, 1)]
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
+ ],
450
459
  )
451
460
  def test_df_exchange_routes_to_the_two_ops(
452
- self, native_host, monkeypatch, nbasis, naux, nocc, group
461
+ self, native_host, monkeypatch, nbasis, naux, nocc, group, tp
453
462
  ):
454
463
  """#60: replaying the half kernel's batched gather from the index
455
464
  images on CPU rebuilds Xt, and the SYRK stand-in's two partials add
456
- up to K."""
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))
457
469
 
458
- def half_op(eri_v, img, C_occ, nub=8):
470
+ def half_op(eri_v, img, C_occ, nub=8, tp=0, tail=0):
459
471
  npc, nvg = img.shape[0], img.shape[1]
460
- tp, nbp = eri_v.shape[1], C_occ.shape[0]
472
+ w0, nbp = eri_v.shape[1], C_occ.shape[0]
473
+ tp = tp or w0
474
+ widths = [tp] * (npc - 1) + [tail or tp]
461
475
  nvc, nkb = nbp // nvg, nbp // 128
462
476
  assert img.dtype == torch.uint32 and img.shape == (npc, nvg, 128, nkb * nvc)
463
477
  idx = img.view(torch.int32).long()
464
- full = torch.empty(nbp, nbp, npc * tp)
465
- for c in range(npc):
478
+ flat = eri_v.reshape(-1)
479
+ full = torch.empty(nbp, nbp, sum(widths))
480
+ for c, w in enumerate(widths):
466
481
  for g in range(nvg):
467
482
  for k in range(nkb):
468
483
  for b in range(nvc // nub):
469
484
  blk = idx[c, g, :, k * nvc + b * nub : k * nvc + (b + 1) * nub]
470
- rows = eri_v[blk.T.flatten()].reshape(128, nub, tp)
485
+ starts = blk.T.flatten() * w0
486
+ rows = flat[starts[:, None] + torch.arange(w)].reshape(128, nub, w)
471
487
  v0 = g * nvc + b * nub
472
- full[k * 128 : (k + 1) * 128, v0 : v0 + nub, c * tp : (c + 1) * tp] = (
473
- rows
474
- )
488
+ full[k * 128 : (k + 1) * 128, v0 : v0 + nub, c * tp : c * tp + w] = rows
475
489
  x = torch.einsum("li,lnP->Pin", C_occ, full) # (P, i, ν)
476
- return x.reshape(npc * tp, -1, nvg, nvc).permute(0, 2, 1, 3).contiguous()
490
+ return x.reshape(sum(widths), -1, nvg, nvc).permute(0, 2, 1, 3).contiguous()
477
491
 
478
492
  def syrk_op(xt, kin, banks=6):
479
493
  nr, nvg, nop, nvc = xt.shape
@@ -494,10 +508,13 @@ class TestPublicApiOnNativePath:
494
508
  ref = 2.0 * torch.einsum("imP,inP->mn", X, X)
495
509
  # fp32 sums of up to 600·nocc terms: compare against max |K|.
496
510
  assert float((out - ref).abs().max()) <= 1e-5 * float(ref.abs().max())
497
- tp, nub, _nvc = _kernels.df_half_tiling(naux, -(-nbasis // 128) * 128, nocc + nocc % 2)
498
- launches = naux // tp if group else 1
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
499
515
  assert [c[0] for c in native_host] == ["df_half_packed", "df_exchange_syrk"] * launches
500
- assert native_host[0][1] == {"nub": nub} and naux % tp == 0
516
+ assert native_host[0][1]["nub"] == nub and native_host[0][1]["tp"] == tp
517
+ assert native_host[-2][1]["tail"] == naux % tp
501
518
 
502
519
  @pytest.mark.parametrize("nbasis", [30, 40])
503
520
  def test_df_coulomb_routes_to_the_two_ops(self, native_host, monkeypatch, nbasis):
@@ -570,12 +587,42 @@ class TestPublicApiOnNativePath:
570
587
  @pytest.mark.parametrize(
571
588
  "naux,nb,nocc", [(1206, 256, 41), (2366, 512, 81), (4686, 1024, 161), (768, 256, 32)]
572
589
  )
573
- def test_df_half_tiling_divides_and_fits(self, naux, nb, nocc):
590
+ def test_df_half_tiling_fits_with_fewest_aux_tiles(self, naux, nb, nocc):
574
591
  tp, nub, nvc = _kernels.df_half_tiling(naux, nb, nocc)
575
- assert naux % tp == 0 and tp <= 512 and nb % nvc == 0 and nvc % nub == 0
592
+ assert tp <= 512 and nb % nvc == 0 and nvc % nub == 0
593
+ assert naux % tp == 0 or tp % 128 == 0
576
594
  assert _kernels.df_half_sbuf_bytes(nb, nocc, tp, nub, nvc) <= _kernels.DF_K_SBUF_BUDGET
577
- g = _kernels.df_group_chunks(naux // tp, nb, tp, nub, nvc)
578
- assert 1 <= g <= naux // tp
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))
579
626
 
580
627
  @pytest.mark.parametrize("nb,banks", [(128, 6), (512, 6), (1024, 6), (1024, 2), (2048, 8)])
581
628
  def test_df_exchange_blocks_cover_the_upper_triangle(self, nb, banks):
@@ -1386,6 +1433,11 @@ class TestLazyRegistration:
1386
1433
  m(32896 * 6, 201), m(2, 4, 128, 128, dtype=torch.int32), m(256, 42)
1387
1434
  )
1388
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)
1389
1441
  assert fake("df_exchange_syrk")(xt, m(2, 256, 256)).shape == (2, 256, 256)
1390
1442
  assert fake("df_coulomb_d")(m(31375, 1206), m(31375, 1)).shape == (2, 1, 1206)
1391
1443
  assert fake("df_coulomb_j")(m(31375, 1206), m(128, 1206)).shape == (128, 244)
@@ -107,6 +107,22 @@ KERNEL_INPUTS = {
107
107
  "nb256_nocc20_naux390_split_chunks",
108
108
  lambda: ((_r(32896 * 2, 195), _u32(2, 2, 128, 256), _r(256, 20)), {"nub": 4}),
109
109
  ),
110
+ # (npair·naux / W, W) rows, 128-multiple chunks and a short last one;
111
+ # naux 1206 = 512 + 512 + 182 (npair cut to 1000: shapes only)
112
+ (
113
+ "nb256_nocc42_naux1206_tail",
114
+ lambda: (
115
+ (_r(1000 * 603, 2), _u32(3, 4, 128, 128), _r(256, 42)),
116
+ {"nub": 8, "tp": 512, "tail": 182},
117
+ ),
118
+ ),
119
+ (
120
+ "nb256_nocc20_tail_only",
121
+ lambda: (
122
+ (_r(1000 * 603, 2), _u32(1, 2, 128, 256), _r(256, 20)),
123
+ {"nub": 4, "tp": 512, "tail": 182},
124
+ ),
125
+ ),
110
126
  ],
111
127
  "df_exchange_syrk_kernel": [
112
128
  # (Xt (rows, NVG, nocc, NVC), running partial Ks (2, NB, NB)); partial last tile
@@ -228,16 +228,26 @@ class TestNativeTrn2Kernels:
228
228
  torch.testing.assert_close(out.cpu(), ref, atol=1e-3, rtol=1e-4)
229
229
 
230
230
  @pytest.mark.parametrize(
231
- "nbasis,nocc,naux,group",
232
- [(128, 8, 128, 0), (200, 21, 558, 0), (256, 41, 1206, 0), (300, 33, 600, 1)],
231
+ "nbasis,nocc,naux,group,tp",
232
+ [
233
+ (128, 8, 128, 0, 0),
234
+ (200, 21, 558, 0, 0),
235
+ (256, 41, 1206, 0, 0),
236
+ (300, 33, 600, 1, 0),
237
+ (256, 41, 1206, 0, 512), # 512 + 512 + 182, one launch
238
+ (300, 33, 600, 1, 256), # 256 + (256 + 88): the tail joins
239
+ (200, 21, 1100, 2, 256), # (256 + 256) + (256 + 256 + 76)
240
+ ],
233
241
  )
234
- def test_df_exchange_kernels_match_reference(self, monkeypatch, nbasis, nocc, naux, group):
242
+ def test_df_exchange_kernels_match_reference(self, monkeypatch, nbasis, nocc, naux, group, tp):
235
243
  """#60: gather + half transform + PSUM SYRK against the fp64 K,
236
- including odd nocc (padded), non-128 nbasis, partial aux tiles and
237
- several launch groups."""
244
+ including odd nocc (padded), non-128 nbasis, partial aux tiles,
245
+ several launch groups and 128-multiple chunks with a short last one."""
238
246
  import trntensor
239
247
  from trntensor.nki import dispatch
240
248
 
249
+ if tp:
250
+ monkeypatch.setenv("TRNTENSOR_DF_K_TP", str(tp))
241
251
  if group:
242
252
  monkeypatch.setattr(dispatch, "df_group_chunks", lambda *a: group)
243
253
  g = torch.Generator().manual_seed(nbasis + naux)