trntensor 0.25.0__tar.gz → 0.25.1__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 (89) hide show
  1. {trntensor-0.25.0 → trntensor-0.25.1}/.github/workflows/ci.yml +2 -2
  2. {trntensor-0.25.0 → trntensor-0.25.1}/.pre-commit-config.yaml +4 -2
  3. {trntensor-0.25.0 → trntensor-0.25.1}/CHANGELOG.md +28 -0
  4. {trntensor-0.25.0/trntensor.egg-info → trntensor-0.25.1}/PKG-INFO +11 -4
  5. {trntensor-0.25.0 → trntensor-0.25.1}/README.md +9 -2
  6. {trntensor-0.25.0 → trntensor-0.25.1}/pyproject.toml +2 -2
  7. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_native_dispatch.py +1 -1
  8. trntensor-0.25.1/tests/test_neuron_span.py +119 -0
  9. trntensor-0.25.1/tests/test_neuron_span_device.py +99 -0
  10. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/__init__.py +1 -1
  11. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/nki/dispatch.py +221 -12
  12. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/quantum.py +7 -2
  13. {trntensor-0.25.0 → trntensor-0.25.1/trntensor.egg-info}/PKG-INFO +11 -4
  14. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor.egg-info/SOURCES.txt +2 -0
  15. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor.egg-info/requires.txt +1 -1
  16. {trntensor-0.25.0 → trntensor-0.25.1}/.github/workflows/notify-umbrella.yml +0 -0
  17. {trntensor-0.25.0 → trntensor-0.25.1}/.github/workflows/publish.yml +0 -0
  18. {trntensor-0.25.0 → trntensor-0.25.1}/.gitignore +0 -0
  19. {trntensor-0.25.0 → trntensor-0.25.1}/CLAUDE.md +0 -0
  20. {trntensor-0.25.0 → trntensor-0.25.1}/CODE_OF_CONDUCT.md +0 -0
  21. {trntensor-0.25.0 → trntensor-0.25.1}/CONTRIBUTING.md +0 -0
  22. {trntensor-0.25.0 → trntensor-0.25.1}/LICENSE +0 -0
  23. {trntensor-0.25.0 → trntensor-0.25.1}/benchmarks/__init__.py +0 -0
  24. {trntensor-0.25.0 → trntensor-0.25.1}/benchmarks/bench_einsum.py +0 -0
  25. {trntensor-0.25.0 → trntensor-0.25.1}/docs/api/decompose.md +0 -0
  26. {trntensor-0.25.0 → trntensor-0.25.1}/docs/api/einsum.md +0 -0
  27. {trntensor-0.25.0 → trntensor-0.25.1}/docs/api/index.md +0 -0
  28. {trntensor-0.25.0 → trntensor-0.25.1}/docs/api/nki.md +0 -0
  29. {trntensor-0.25.0 → trntensor-0.25.1}/docs/api/plan.md +0 -0
  30. {trntensor-0.25.0 → trntensor-0.25.1}/docs/api/quantum.md +0 -0
  31. {trntensor-0.25.0 → trntensor-0.25.1}/docs/api/stream.md +0 -0
  32. {trntensor-0.25.0 → trntensor-0.25.1}/docs/architecture.md +0 -0
  33. {trntensor-0.25.0 → trntensor-0.25.1}/docs/aws_setup.md +0 -0
  34. {trntensor-0.25.0 → trntensor-0.25.1}/docs/benchmarks.md +0 -0
  35. {trntensor-0.25.0 → trntensor-0.25.1}/docs/contraction_patterns.md +0 -0
  36. {trntensor-0.25.0 → trntensor-0.25.1}/docs/design/matmul_dispatch_findings.md +0 -0
  37. {trntensor-0.25.0 → trntensor-0.25.1}/docs/design/matmul_kernel_profile.md +0 -0
  38. {trntensor-0.25.0 → trntensor-0.25.1}/docs/developing_kernels.md +0 -0
  39. {trntensor-0.25.0 → trntensor-0.25.1}/docs/index.md +0 -0
  40. {trntensor-0.25.0 → trntensor-0.25.1}/docs/installation.md +0 -0
  41. {trntensor-0.25.0 → trntensor-0.25.1}/docs/quickstart.md +0 -0
  42. {trntensor-0.25.0 → trntensor-0.25.1}/docs/tutorial_df_mp2.md +0 -0
  43. {trntensor-0.25.0 → trntensor-0.25.1}/examples/df_mp2_einsum.py +0 -0
  44. {trntensor-0.25.0 → trntensor-0.25.1}/infra/terraform/README.md +0 -0
  45. {trntensor-0.25.0 → trntensor-0.25.1}/infra/terraform/main.tf +0 -0
  46. {trntensor-0.25.0 → trntensor-0.25.1}/mkdocs.yml +0 -0
  47. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/autotune_dispatch.py +0 -0
  48. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/bench_ao2mo_nocc.py +0 -0
  49. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/bench_eager_handle.py +0 -0
  50. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/bench_native_einsum.py +0 -0
  51. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/bench_native_kernels.py +0 -0
  52. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/bench_to_md.py +0 -0
  53. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/run_benchmarks.sh +0 -0
  54. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/run_neuron_profile.sh +0 -0
  55. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/run_neuron_tests.sh +0 -0
  56. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/run_reduce_parallel_multirank.py +0 -0
  57. {trntensor-0.25.0 → trntensor-0.25.1}/scripts/run_simulator_tests.sh +0 -0
  58. {trntensor-0.25.0 → trntensor-0.25.1}/setup.cfg +0 -0
  59. {trntensor-0.25.0 → trntensor-0.25.1}/tests/conftest.py +0 -0
  60. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_conformance.py +0 -0
  61. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_decompose.py +0 -0
  62. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_einsum.py +0 -0
  63. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_host_output.py +0 -0
  64. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_kernel_dtype_guard.py +0 -0
  65. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_nki.py +0 -0
  66. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_nki_compile.py +0 -0
  67. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_nki_kernels.py +0 -0
  68. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_nki_native.py +0 -0
  69. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_nki_sim.py +0 -0
  70. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_nki_tail_audit.py +0 -0
  71. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_parallel.py +0 -0
  72. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_plan.py +0 -0
  73. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_quantum.py +0 -0
  74. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_sr_runtime.py +0 -0
  75. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_stream.py +0 -0
  76. {trntensor-0.25.0 → trntensor-0.25.1}/tests/test_trace_cache_safety.py +0 -0
  77. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/decompose.py +0 -0
  78. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/einsum.py +0 -0
  79. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/nki/__init__.py +0 -0
  80. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/nki/_kernels.py +0 -0
  81. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/nki/_native.py +0 -0
  82. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/nki/collectives.py +0 -0
  83. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/parallel.py +0 -0
  84. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/plan.py +0 -0
  85. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/py.typed +0 -0
  86. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor/stream.py +0 -0
  87. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor.egg-info/dependency_links.txt +0 -0
  88. {trntensor-0.25.0 → trntensor-0.25.1}/trntensor.egg-info/top_level.txt +0 -0
  89. {trntensor-0.25.0 → trntensor-0.25.1}/uv.lock +0 -0
@@ -17,8 +17,8 @@ jobs:
17
17
  steps:
18
18
  - uses: actions/checkout@v6
19
19
  - uses: astral-sh/setup-uv@v6
20
- - run: uvx ruff check .
21
- - run: uvx ruff format --check .
20
+ - run: uvx ruff@0.17.3 check .
21
+ - run: uvx ruff@0.17.3 format --check .
22
22
 
23
23
  test:
24
24
  runs-on: ubuntu-latest
@@ -3,9 +3,11 @@
3
3
  # CI re-checks the same rules in the lint job — pre-commit keeps CI green.
4
4
 
5
5
  repos:
6
+ # Keep rev in lockstep with the ruff pin in .github/workflows/ci.yml
7
+ # (and the [dev] extra in pyproject.toml) so local and CI agree.
6
8
  - repo: https://github.com/astral-sh/ruff-pre-commit
7
- rev: v0.6.9
9
+ rev: v0.17.3
8
10
  hooks:
9
- - id: ruff
11
+ - id: ruff-check
10
12
  args: [--fix]
11
13
  - id: ruff-format
@@ -7,6 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.25.1] — 2026-11-07
11
+
12
+ Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
13
+
14
+ Headline: device matmuls with 32 MiB or longer rows (an operand's 128 partitions spanning 4 GiB) are no longer silently wrong (#123, aws-neuron-sdk#1457).
15
+
16
+ ### Fixed
17
+
18
+ - **Device matmuls with 32 MiB or longer rows were silently wrong (#123,
19
+ trnblas#112, aws-neuron-sdk#1457).** On the native TorchNeuron path (Trn2,
20
+ SDK 2.33), a device matmul returns wrong values with no error (or aborts
21
+ with NRT status 1203) once an operand's 128 DMA partitions span 4 GiB or
22
+ more, i.e. `min(rows, 128) * row_bytes >= 2**32`, and that includes a
23
+ contiguous left operand. Example: fp32 `(96, 128) @ (128, 8,389,632)` gave
24
+ rel err 0.8. Affected: the contiguous-LHS `ao_to_mo_transform` aten route
25
+ of #98 (0.23.0–0.25.0) when `nbasis * naux >= 8,388,608` (fp32), and
26
+ device `einsum` matmul / bmm plans (`nki_matmul`, `nki_batched_matmul`)
27
+ with such operands (0.17.0–0.25.0). These products are now cut into
28
+ contiguous row blocks of the long operand, each block spanning at most 2 GiB:
29
+ K is split (partial sums), or M / N (concatenated results). No operand is
30
+ copied. Splitting K changes the fp32 summation order of the affected products
31
+ only. Every other product is the same aten call as before (bitwise
32
+ unchanged). Standard DF ratios (naux about 3 × nbasis) on one core do not
33
+ reach it. The `_ATEN_TRANSPOSED_LHS_MAX_BYTES` comment said exactly 2**32
34
+ bytes was correct. That was a lucky measurement (the operand sat above an
35
+ identical copy), and the comment is corrected; the guard already started
36
+ at 2**32.
37
+
10
38
  ## [0.25.0] — 2026-11-04
11
39
 
12
40
  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.25.0
3
+ Version: 0.25.1
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
@@ -29,7 +29,7 @@ Provides-Extra: dev
29
29
  Requires-Dist: pytest<9,>=7.0; extra == "dev"
30
30
  Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
31
31
  Requires-Dist: pytest-cov>=4.0; extra == "dev"
32
- Requires-Dist: ruff>=0.6; extra == "dev"
32
+ Requires-Dist: ruff==0.17.3; extra == "dev"
33
33
  Requires-Dist: pre-commit>=3.7; extra == "dev"
34
34
  Requires-Dist: scipy>=1.11; extra == "dev"
35
35
  Requires-Dist: mkdocs>=1.5; extra == "dev"
@@ -169,7 +169,7 @@ core, factors = trntensor.tucker_decompose(tensor, ranks=(5, 5, 5))
169
169
 
170
170
  ## Known issues in earlier releases
171
171
 
172
- Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details are in the [CHANGELOG](CHANGELOG.md).
172
+ Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-04 releases. Details are in the [CHANGELOG](CHANGELOG.md).
173
173
 
174
174
  | Bug | Affected | Fixed in |
175
175
  |-----|----------|----------|
@@ -180,7 +180,14 @@ Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details
180
180
  | `einsum(precision="dd")` on float32/float64 was less accurate than `"fast"` (CPU emulation, #84) | 0.17.0–0.22.0 | 0.23.0 |
181
181
  | `multi_einsum` returned float32 results as float64 in mixed-dtype batches (#75) | 0.17.0–0.22.0 | 0.23.0 |
182
182
  | NKI chemistry kernels returned inf for float64 operands, and some kernel routes changed the result dtype (#87) | `df_*` 0.21.0–0.22.0; `ao_to_mo_transform` every release with its kernels | 0.23.0 |
183
- | `ao_to_mo_transform` aten route on the TorchNeuron device was wrong once `eri` exceeded 4 GiB (#97; one LNC=1 case is still open) | through 0.22.0 | 0.23.0 |
183
+ | `ao_to_mo_transform` aten route on the TorchNeuron device was wrong once `eri` exceeded 4 GiB (#97; the LNC=1 gather case is the 0.24.0 row below) | through 0.22.0 | 0.23.0 |
184
+ | `unpack_tril` / `pack_tril` (and the packed-`eri` aten / legacy routes of `ao_to_mo_transform`) on the neuron device at LNC=1 returned wrong data, at times NaN, once one gathered output reached 4 GiB (154 M mismatched elements at 4.99e9 bytes) (#97) | 0.20.0–0.23.0 | 0.24.0 |
185
+ | Complex `tucker_decompose` on the neuron device used `Uᵀ`, not `Uᴴ`: device matmul ignores the lazy conj bit of `.mH` (#89) | 0.23.0 | 0.24.0 |
186
+ | float64 on the neuron device rounded to fp32 in `gather` (device `torch.cat`) and in `pack_tril` / `unpack_tril` / `pack_density` / `unpack_packed` (device `index_select` / fancy indexing), rel. err ~4e-8 (#92) | through 0.23.0 | 0.24.0 |
187
+ | `multi_einsum` under `"auto"` pinned shared host float64 / complex128 operands to the device, where device aten computed them at fp32 precision (#92) | through 0.23.0 | 0.24.0 |
188
+ | Integer, bool, complex and mixed-dtype operands of `einsum` / `multi_einsum` reached the fp32/bf16/fp16 matmul kernels under `set_backend("nki")`, or under `"auto"` above the size thresholds (trnsci/trnsci#35) | through 0.23.0 | 0.24.0 |
189
+ | `einsum(..., out=)` never wrote `out`, so the documented `einsum(..., beta=1.0, out=acc)` accumulation left `acc` unchanged (#77) | 0.3.0–0.23.0 | 0.24.0 |
190
+ | `cp_reconstruct` returned float32 for bf16 / fp16 factors (#78) | 0.1.1–0.23.0 | 0.24.0 |
184
191
 
185
192
  ## Related Projects
186
193
 
@@ -131,7 +131,7 @@ core, factors = trntensor.tucker_decompose(tensor, ranks=(5, 5, 5))
131
131
 
132
132
  ## Known issues in earlier releases
133
133
 
134
- Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details are in the [CHANGELOG](CHANGELOG.md).
134
+ Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-04 releases. Details are in the [CHANGELOG](CHANGELOG.md).
135
135
 
136
136
  | Bug | Affected | Fixed in |
137
137
  |-----|----------|----------|
@@ -142,7 +142,14 @@ Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details
142
142
  | `einsum(precision="dd")` on float32/float64 was less accurate than `"fast"` (CPU emulation, #84) | 0.17.0–0.22.0 | 0.23.0 |
143
143
  | `multi_einsum` returned float32 results as float64 in mixed-dtype batches (#75) | 0.17.0–0.22.0 | 0.23.0 |
144
144
  | NKI chemistry kernels returned inf for float64 operands, and some kernel routes changed the result dtype (#87) | `df_*` 0.21.0–0.22.0; `ao_to_mo_transform` every release with its kernels | 0.23.0 |
145
- | `ao_to_mo_transform` aten route on the TorchNeuron device was wrong once `eri` exceeded 4 GiB (#97; one LNC=1 case is still open) | through 0.22.0 | 0.23.0 |
145
+ | `ao_to_mo_transform` aten route on the TorchNeuron device was wrong once `eri` exceeded 4 GiB (#97; the LNC=1 gather case is the 0.24.0 row below) | through 0.22.0 | 0.23.0 |
146
+ | `unpack_tril` / `pack_tril` (and the packed-`eri` aten / legacy routes of `ao_to_mo_transform`) on the neuron device at LNC=1 returned wrong data, at times NaN, once one gathered output reached 4 GiB (154 M mismatched elements at 4.99e9 bytes) (#97) | 0.20.0–0.23.0 | 0.24.0 |
147
+ | Complex `tucker_decompose` on the neuron device used `Uᵀ`, not `Uᴴ`: device matmul ignores the lazy conj bit of `.mH` (#89) | 0.23.0 | 0.24.0 |
148
+ | float64 on the neuron device rounded to fp32 in `gather` (device `torch.cat`) and in `pack_tril` / `unpack_tril` / `pack_density` / `unpack_packed` (device `index_select` / fancy indexing), rel. err ~4e-8 (#92) | through 0.23.0 | 0.24.0 |
149
+ | `multi_einsum` under `"auto"` pinned shared host float64 / complex128 operands to the device, where device aten computed them at fp32 precision (#92) | through 0.23.0 | 0.24.0 |
150
+ | Integer, bool, complex and mixed-dtype operands of `einsum` / `multi_einsum` reached the fp32/bf16/fp16 matmul kernels under `set_backend("nki")`, or under `"auto"` above the size thresholds (trnsci/trnsci#35) | through 0.23.0 | 0.24.0 |
151
+ | `einsum(..., out=)` never wrote `out`, so the documented `einsum(..., beta=1.0, out=acc)` accumulation left `acc` unchanged (#77) | 0.3.0–0.23.0 | 0.24.0 |
152
+ | `cp_reconstruct` returned float32 for bf16 / fp16 factors (#78) | 0.1.1–0.23.0 | 0.24.0 |
146
153
 
147
154
  ## Related Projects
148
155
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "trntensor"
7
- version = "0.25.0"
7
+ version = "0.25.1"
8
8
  description = "Tensor contractions for AWS Trainium via NKI"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -45,7 +45,7 @@ dev = [
45
45
  "pytest>=7.0,<9", # pytest-benchmark 5.3 breaks on pytest 9 (Function._nodeid)
46
46
  "pytest-benchmark>=4.0",
47
47
  "pytest-cov>=4.0",
48
- "ruff>=0.6",
48
+ "ruff==0.17.3",
49
49
  "pre-commit>=3.7",
50
50
  "scipy>=1.11",
51
51
  "mkdocs>=1.5",
@@ -1303,7 +1303,7 @@ class TestNativeRoute:
1303
1303
  torch.testing.assert_close(
1304
1304
  dispatch.nki_batched_matmul(A[None], B[None]), torch.bmm(A[None], B[None])
1305
1305
  )
1306
- assert moved == [torch.matmul, torch.bmm]
1306
+ assert moved == [dispatch._neuron_matmul, dispatch._neuron_bmm]
1307
1307
 
1308
1308
  def test_fused_quantum_kernels_off_under_auto(self, monkeypatch):
1309
1309
  monkeypatch.setattr(dispatch, "HAS_NKI", True)
@@ -0,0 +1,119 @@
1
+ """Row-block matmul for the >= 4 GiB partition-span bug on the neuron device (#123).
2
+
3
+ CPU tests: the thresholds are lowered so that small host tensors stand in for
4
+ the 32 MiB-row operands, and `_on_neuron_device` is patched so the host tensors
5
+ take the device logic. A spy on `torch.matmul` checks that no product the
6
+ blocking issues still has an unsafe operand or result. The on-device
7
+ regression tests at the real sizes are in test_native_device.py
8
+ (`TestSpan4GiB`).
9
+ """
10
+
11
+ import pytest
12
+ import torch
13
+
14
+ import trntensor
15
+ from trntensor import quantum
16
+ from trntensor.nki import dispatch as D
17
+
18
+ SPAN = 1 << 14 # stands in for 2**32
19
+ BLOCK = 1 << 13 # stands in for 2**31
20
+
21
+
22
+ @pytest.fixture
23
+ def lowered(monkeypatch):
24
+ monkeypatch.setattr(D, "_NEURON_SPAN_BYTES", SPAN)
25
+ monkeypatch.setattr(D, "_NEURON_BLOCK_BYTES", BLOCK)
26
+ monkeypatch.setattr(D, "_on_neuron_device", lambda t: True)
27
+ calls = []
28
+ real = torch.matmul
29
+
30
+ def spy(a, b, *args, **kwargs):
31
+ calls.append((tuple(a.shape), tuple(b.shape)))
32
+ if a.dim() == 2 and b.dim() == 2:
33
+ assert not D._span_block(a), f"unsafe lhs {tuple(a.shape)}"
34
+ assert not D._span_block(b), f"unsafe rhs {tuple(b.shape)}"
35
+ assert not D._out_block(a.shape[0], b.shape[1], a.element_size()), "unsafe result"
36
+ return real(a, b, *args, **kwargs)
37
+
38
+ monkeypatch.setattr(torch, "matmul", spy)
39
+ return calls
40
+
41
+
42
+ def _r(*shape, seed=0):
43
+ g = torch.Generator().manual_seed(seed)
44
+ return torch.randn(*shape, generator=g, dtype=torch.float64).float()
45
+
46
+
47
+ def _ref(a, b):
48
+ return (a.double() @ b.double()).float()
49
+
50
+
51
+ def test_real_thresholds():
52
+ assert D._NEURON_SPAN_BYTES == 1 << 32
53
+ assert D._out_block(128, 8_389_632, 4) == 64
54
+ assert D._out_block(128, 8_388_480, 4) == 0
55
+ assert D._out_block(64, 8_389_632, 4) == 0
56
+
57
+
58
+ @pytest.mark.parametrize("M,K,N", [(12, 128, 40), (12, 300, 33), (128, 40, 6), (130, 128, 40)])
59
+ def test_blocked_matches_plain(lowered, M, K, N):
60
+ a, b = _r(M, K), _r(K, N, seed=1)
61
+ assert D._neuron_mm_unsafe(a, b)
62
+ torch.testing.assert_close(D._neuron_matmul(a, b), _ref(a, b), rtol=1e-5, atol=1e-4)
63
+ assert len(lowered) > 1
64
+
65
+
66
+ def test_batched_and_bmm(lowered):
67
+ a, b = _r(3, 12, 128), _r(3, 128, 40, seed=1)
68
+ torch.testing.assert_close(D._neuron_bmm(a, b), _ref(a, b), rtol=1e-5, atol=1e-4)
69
+ assert len(lowered) > 1
70
+
71
+
72
+ def test_short_row_batches_stay_one_call(monkeypatch):
73
+ monkeypatch.setattr(D, "_NEURON_SPAN_BYTES", SPAN)
74
+ monkeypatch.setattr(D, "_on_neuron_device", lambda t: True)
75
+ # (nocc, nbasis, naux) halves with short rows: no blocking even when large.
76
+ a, b = _r(4, 6, 32), _r(4, 32, 8, seed=1)
77
+ assert not D._neuron_mm_unsafe(a, b)
78
+
79
+
80
+ def test_safe_and_host_products_untouched(monkeypatch):
81
+ a, b = _r(12, 128), _r(128, 40, seed=1)
82
+ assert torch.equal(D._neuron_matmul(a, b), torch.matmul(a, b)) # host
83
+ monkeypatch.setattr(D, "_on_neuron_device", lambda t: True)
84
+ calls = []
85
+ real = torch.matmul
86
+ monkeypatch.setattr(torch, "matmul", lambda x, y: calls.append((x, y)) or real(x, y))
87
+ out = D._neuron_matmul(a, b) # below the real 4 GiB rule
88
+ assert len(calls) == 1 and calls[0][0] is a and calls[0][1] is b
89
+ assert torch.equal(out, real(a, b))
90
+
91
+
92
+ @pytest.mark.parametrize("backend", ["auto", "pytorch"])
93
+ def test_einsum_matmul_and_bmm_routes(lowered, backend):
94
+ old = trntensor.get_backend()
95
+ trntensor.set_backend(backend)
96
+ try:
97
+ a, b = _r(12, 128), _r(128, 40, seed=1)
98
+ out = trntensor.einsum("ij,jk->ik", a, b)
99
+ torch.testing.assert_close(out, _ref(a, b), rtol=1e-5, atol=1e-4)
100
+ assert len(lowered) > 1
101
+ lowered.clear()
102
+ a3, b3 = _r(2, 12, 128), _r(2, 128, 40, seed=1)
103
+ out = trntensor.einsum("bij,bjk->bik", a3, b3)
104
+ torch.testing.assert_close(out, _ref(a3, b3), rtol=1e-5, atol=1e-4)
105
+ finally:
106
+ trntensor.set_backend(old)
107
+
108
+
109
+ def test_ao_to_mo_contiguous_route_blocks(lowered, monkeypatch):
110
+ # nbasis 128, nbasis * naux * 4 B = 2 KiB rows: the #123 layout at this scale.
111
+ nb, naux, nocc, nvir = 128, 4, 5, 7
112
+ eri = _r(nb, nb, naux)
113
+ C_occ, C_vir = _r(nb, nocc, seed=1), _r(nb, nvir, seed=2)
114
+ ref = torch.einsum(
115
+ "na,inP->iaP", C_vir.double(), torch.einsum("mi,mnP->inP", C_occ.double(), eri.double())
116
+ )
117
+ out = quantum._ao_to_mo_contiguous_lhs(eri, C_occ, C_vir)
118
+ torch.testing.assert_close(out.double(), ref, rtol=1e-5, atol=1e-5)
119
+ assert len(lowered) > 2 # the half-transform was blocked over K
@@ -0,0 +1,99 @@
1
+ """On-device regression tests for #123 (trnblas#112, aws-neuron-sdk#1457) at real sizes.
2
+
3
+ A device matmul is silently wrong once an operand's (or the result's) 128 DMA
4
+ partitions span 4 GiB or more: fp32 rows of 32 MiB or more. Operands are
5
+ uploaded above a same-size decoy holding different data, or produced on the
6
+ device by `clone`, and every result is compared with a host reference. Each
7
+ case needs about 9-14 GB of one logical core's device memory.
8
+ """
9
+
10
+ import gc
11
+
12
+ import pytest
13
+ import torch
14
+
15
+ import trntensor
16
+ from trntensor import quantum
17
+ from trntensor.nki import HAS_NKI
18
+ from trntensor.nki import dispatch as D
19
+
20
+
21
+ def _native() -> bool:
22
+ if not HAS_NKI or D._use_simulator():
23
+ return False
24
+ try:
25
+ return D._get_dispatch_path() == "native"
26
+ except Exception:
27
+ return False
28
+
29
+
30
+ pytestmark = [
31
+ pytest.mark.neuron,
32
+ pytest.mark.skipif(not _native(), reason="requires TorchNeuron (native) dispatch path"),
33
+ ]
34
+
35
+ DEV = "neuron"
36
+ N_BAD = 8_389_632 # 32 MiB + 4 KiB fp32 rows
37
+ N_OK = 8_388_480 # 32 MiB - 512 B
38
+
39
+
40
+ def _host(*shape, seed=0):
41
+ g = torch.Generator().manual_seed(seed)
42
+ return torch.randn(*shape, generator=g)
43
+
44
+
45
+ def _rel(out, ref):
46
+ out, ref = out.cpu().double(), ref.double()
47
+ return ((out - ref).norm() / ref.norm()).item()
48
+
49
+
50
+ @pytest.fixture(autouse=True)
51
+ def _free():
52
+ yield
53
+ gc.collect()
54
+
55
+
56
+ @pytest.fixture(params=["upload", "device"])
57
+ def source(request):
58
+ return request.param
59
+
60
+
61
+ def _device_operand(X, source):
62
+ decoy = (-X).to(DEV) # different data directly below
63
+ return decoy, (X.to(DEV) if source == "upload" else X.to(DEV).clone())
64
+
65
+
66
+ class TestSpan4GiB:
67
+ def test_einsum_matmul(self, source):
68
+ A, B = _host(96, 128), _host(128, N_BAD, seed=1)
69
+ decoy, Bd = _device_operand(B, source)
70
+ out = trntensor.einsum("ij,jk->ik", A.to(DEV), Bd)
71
+ assert _rel(out, A @ B) < 1e-5
72
+
73
+ def test_einsum_bmm(self, source):
74
+ A, B = _host(1, 96, 128), _host(1, 128, N_BAD, seed=1)
75
+ decoy, Bd = _device_operand(B, source)
76
+ out = trntensor.einsum("bij,bjk->bik", A.to(DEV), Bd)
77
+ assert _rel(out, A @ B) < 1e-5
78
+
79
+ def test_ao_to_mo_contiguous_route(self, source):
80
+ # nbasis * naux = 8,389,632: the #98 contiguous route's B rows are 32 MiB + 4 KiB.
81
+ nb, naux, nocc, nvir = 128, 65_544, 8, 16
82
+ eri = _host(nb, nb, naux)
83
+ C_occ, C_vir = _host(nb, nocc, seed=1), _host(nb, nvir, seed=2)
84
+ decoy, eri_d = _device_operand(eri, source)
85
+ half = (C_occ.T @ eri.reshape(nb, nb * naux)).reshape(nocc, nb, naux)
86
+ ref = torch.matmul(C_vir.T, half)
87
+ del half
88
+ out = quantum._cpu_ao_to_mo_transform(eri_d, C_occ.to(DEV), C_vir.to(DEV))
89
+ assert out.shape == (nocc, nvir, naux)
90
+ assert _rel(out, ref) < 1e-5
91
+
92
+ def test_below_rule_is_the_plain_call(self):
93
+ A, B = _host(96, 128), _host(128, N_OK, seed=1)
94
+ decoy, Bd = _device_operand(B, "upload")
95
+ Ad = A.to(DEV)
96
+ assert not D._neuron_mm_unsafe(Ad, Bd)
97
+ out = trntensor.einsum("ij,jk->ik", Ad, Bd)
98
+ assert torch.equal(out.cpu(), torch.matmul(Ad, Bd).cpu())
99
+ assert _rel(out, A @ B) < 1e-5
@@ -5,7 +5,7 @@ Einstein summation, contraction planning, and tensor decompositions
5
5
  for scientific computing. Part of the trnsci scientific computing suite.
6
6
  """
7
7
 
8
- __version__ = "0.25.0"
8
+ __version__ = "0.25.1"
9
9
 
10
10
  from .decompose import (
11
11
  cp_decompose,
@@ -574,13 +574,219 @@ def _to_xla(*tensors):
574
574
  _NEURON_DEVICE = "neuron"
575
575
 
576
576
  # TorchNeuron's aten matmul with a transposed-view left operand returns wrong
577
- # values (or a DMA abort) once the right operand exceeds 2**32 bytes, fp32 and
578
- # bf16, LNC=1 and 2 (torch-neuronx 2.14.3; aws-neuron-sdk#1448, #97).
579
- # Measured: wrong above 2**32 bytes (exactly 2**32 is correct) when the
580
- # contraction dim is a multiple of 128; the guard starts at 2**32 and
581
- # ignores the multiple-of-128 condition.
577
+ # values (or a DMA abort) once the right operand reaches 2**32 bytes, fp32 and
578
+ # bf16, LNC=1 and 2 (torch-neuronx 2.14.3; aws-neuron-sdk#1448, #97). The
579
+ # guard starts at 2**32 and ignores the contraction dim. (This comment used to
580
+ # say "exactly 2**32 is correct". That measurement was correct by chance: the
581
+ # operand sat directly above an identical copy. With other data below it,
582
+ # exactly 2**32 is wrong too (#123, aws-neuron-sdk#1457).)
582
583
  _ATEN_TRANSPOSED_LHS_MAX_BYTES = 1 << 32
583
584
 
585
+ # The same bug hits a *contiguous* left operand (#123, trnblas#112,
586
+ # aws-neuron-sdk#1457, trnsci/trnsci#140). An operand's memory rows are its DMA
587
+ # partition step, and once min(rows, 128) * row_bytes >= 2**32 (for B (K, N)
588
+ # with K >= 128, a row of 32 MiB or more: fp32 N >= 8,388,608), partitions
589
+ # 64-127 are read from 4 GiB below the right address. Measured on Trn2 (SDK
590
+ # 2.33, LNC=2, operand above a decoy, 2026-11-07): (96, 128) @ (128, 8,389,632)
591
+ # has rel err 0.79 with no error, and so do bmm and a long-row left operand.
592
+ # A device copy of a column slice of such a B is itself wrong, and so is a
593
+ # device `torch.cat` along dim 1 into a result with that layout. Contiguous
594
+ # blocks of whole rows spanning about 2 GiB are correct (also at offsets up
595
+ # to 6 GB), a `cat` of whole-row blocks along dim 0 is correct, and host round
596
+ # trips are bit-exact. So `_neuron_matmul` splits K (partial sums) or M / N
597
+ # (concatenated results) into row blocks of the long operand, and builds a
598
+ # result with that layout from blocks of its rows. Products below the rule are
599
+ # the same aten call as before.
600
+ _NEURON_SPAN_BYTES = 1 << 32
601
+ _NEURON_PARTITIONS = 128
602
+ # Rows per block: a span of at most 2 GiB + 1 MiB, so 64 rows of up to
603
+ # 32 MiB + 16 KiB (measured correct: K = 64 at 32 MiB + 4 KiB on #140, and
604
+ # 63-row blocks here) and fewer rows for longer ones. All of them sit in
605
+ # partitions 0-63, which the upstream analysis says are read correctly.
606
+ _NEURON_BLOCK_BYTES = (1 << 31) + (1 << 20)
607
+
608
+
609
+ def _even_step(total: int, step: int) -> int:
610
+ """A block length of at most `step` that cuts `total` into near-equal blocks.
611
+
612
+ Fewer distinct block shapes means fewer NEFF compiles: 128 rows in blocks of
613
+ at most 64 is 64 + 64, not 63 + 63 + 2."""
614
+ return -(-total // -(-total // step))
615
+
616
+
617
+ def _span_bytes(t: torch.Tensor) -> int:
618
+ """Bytes from the first to the last element of `t`'s view, inclusive."""
619
+ if t.numel() == 0:
620
+ return 0
621
+ return (
622
+ 1 + sum((n - 1) * abs(s) for n, s in zip(t.shape, t.stride(), strict=True))
623
+ ) * t.element_size()
624
+
625
+
626
+ def _row_layout(t: torch.Tensor) -> tuple[int, int, int]:
627
+ """(row dim, rows, row bytes) of the memory rows of a 2-D `t`.
628
+
629
+ A row-major matrix has its memory rows along dim 0, and a transposed view
630
+ (`X.T` of a row-major X) along dim 1. Row bytes is the row stride, or the
631
+ row length if that is larger, so a slice of a wider matrix counts its
632
+ parent's rows.
633
+ """
634
+ item = t.element_size()
635
+ if t.stride(1) == 1 or (t.stride(0) != 1 and t.shape[1] == 1):
636
+ return 0, t.shape[0], max(t.shape[1], abs(t.stride(0))) * item
637
+ return 1, t.shape[1], max(t.shape[0], abs(t.stride(1))) * item
638
+
639
+
640
+ def _span_block(t: torch.Tensor) -> int:
641
+ """0 if a 2-D `t` is a safe device matmul operand, else its rows per block.
642
+
643
+ Unsafe means min(rows, 128) * row bytes >= 2**32 (see above). A block of
644
+ that many memory rows spans at most 2 GiB + 1 MiB (and holds at least one row).
645
+ """
646
+ if t.dim() != 2 or _span_bytes(t) < _NEURON_SPAN_BYTES:
647
+ return 0
648
+ _, rows, row_bytes = _row_layout(t)
649
+ if min(rows, _NEURON_PARTITIONS) * row_bytes < _NEURON_SPAN_BYTES:
650
+ return 0
651
+ return max(1, _NEURON_BLOCK_BYTES // row_bytes)
652
+
653
+
654
+ def _out_block(M: int, N: int, itemsize: int) -> int:
655
+ """0 if a fresh row-major (M, N) result is safe, else its rows per block."""
656
+ row_bytes = N * itemsize
657
+ if min(M, _NEURON_PARTITIONS) * row_bytes < _NEURON_SPAN_BYTES:
658
+ return 0
659
+ return max(1, _NEURON_BLOCK_BYTES // row_bytes)
660
+
661
+
662
+ def _neuron_cat(parts: list, dim: int) -> torch.Tensor:
663
+ """`torch.cat(parts, dim)` of 2-D device blocks, safe when the result has the bad layout.
664
+
665
+ Measured on Trn2: a device `cat` along dim 0 into a (128, 8,389,632) fp32
666
+ result is correct (whole-row blocks), along dim 1 it is wrong (rel err
667
+ 0.71). So a dim-1 result with that layout is assembled on the host and
668
+ uploaded (an upload lands bit-exact). `_neuron_mm2d` blocks the output rows
669
+ first, so its dim-1 concatenations never need that.
670
+ """
671
+ if len(parts) == 1:
672
+ return parts[0]
673
+ M = sum(p.shape[0] for p in parts) if dim == 0 else parts[0].shape[0]
674
+ N = sum(p.shape[1] for p in parts) if dim == 1 else parts[0].shape[1]
675
+ if dim != 0 and _on_neuron_device(parts[0]) and _out_block(M, N, parts[0].element_size()):
676
+ return torch.cat([p.cpu() for p in parts], dim).to(parts[0].device)
677
+ return torch.cat(parts, dim)
678
+
679
+
680
+ def _neuron_mm_unsafe(a: torch.Tensor, b: torch.Tensor) -> bool:
681
+ """True when device `torch.matmul(a, b)` needs `_neuron_matmul`'s blocking.
682
+
683
+ Cheap and conservative: False whenever neither operand nor the result
684
+ spans 4 GiB, so ordinary products keep their exact aten call.
685
+ """
686
+ if a.dim() < 2 or b.dim() < 2 or not (_on_neuron_device(a) or _on_neuron_device(b)):
687
+ return False
688
+ try:
689
+ batch = torch.broadcast_shapes(a.shape[:-2], b.shape[:-2])
690
+ except RuntimeError:
691
+ return False # torch.matmul raises its own error
692
+ out_bytes = math.prod(batch) * a.shape[-2] * b.shape[-1] * a.element_size()
693
+ if max(_span_bytes(a), _span_bytes(b), out_bytes) < _NEURON_SPAN_BYTES:
694
+ return False
695
+ M, N = a.shape[-2], b.shape[-1]
696
+ rows = math.prod(batch) * M
697
+ return bool(_batched_block(a) or _batched_block(b) or _out_block(rows, N, a.element_size()))
698
+
699
+
700
+ def _batched_block(t: torch.Tensor) -> int:
701
+ """`_span_block` of a (batched) operand, its matrices' rows counted together.
702
+
703
+ Conservative for batches: the memory rows of all matrices count toward the
704
+ 128 partitions, as for an elementwise op on the whole tensor.
705
+ """
706
+ if t.dim() == 2:
707
+ return _span_block(t)
708
+ if _span_bytes(t) < _NEURON_SPAN_BYTES:
709
+ return 0
710
+ _, rows, row_bytes = _row_layout(t[(0,) * (t.dim() - 2)])
711
+ rows *= math.prod(t.shape[:-2])
712
+ if min(rows, _NEURON_PARTITIONS) * row_bytes < _NEURON_SPAN_BYTES:
713
+ return 0
714
+ return max(1, _NEURON_BLOCK_BYTES // row_bytes)
715
+
716
+
717
+ def _neuron_mm2d(a: torch.Tensor, b: torch.Tensor, mm=None) -> torch.Tensor:
718
+ """2-D `a @ b` on the device, cut into row blocks wherever trnblas#112 applies.
719
+
720
+ `mm` computes each safe block (default: aten)."""
721
+ M, K = a.shape
722
+ N = b.shape[1]
723
+ ob = _out_block(M, N, a.element_size())
724
+ if ob and ob < M: # the result itself: blocks of output rows
725
+ ob = _even_step(M, ob)
726
+ return _neuron_cat([_neuron_mm2d(a[i : i + ob], b, mm) for i in range(0, M, ob)], 0)
727
+ ab = _span_block(a)
728
+ if ab:
729
+ if _row_layout(a)[0] == 0 and ab < M: # long rows of A: split M
730
+ ab = _even_step(M, ab)
731
+ return _neuron_cat([_neuron_mm2d(a[i : i + ab], b, mm) for i in range(0, M, ab)], 0)
732
+ if _row_layout(a)[0] == 1 and ab < K: # A = X.T, long rows of X: split K
733
+ return _neuron_mm_ksum(a, b, ab, mm)
734
+ bb = _span_block(b)
735
+ if bb:
736
+ if _row_layout(b)[0] == 0 and bb < K: # long rows of B: split K
737
+ return _neuron_mm_ksum(a, b, bb, mm)
738
+ if _row_layout(b)[0] == 1 and bb < N: # B = Y.T, long rows of Y: split N
739
+ bb = _even_step(N, bb)
740
+ return _neuron_cat([_neuron_mm2d(a, b[:, j : j + bb], mm) for j in range(0, N, bb)], 1)
741
+ if mm is not None and not _neuron_mm_unsafe(a, b):
742
+ return mm(a, b)
743
+ return torch.matmul(a, b)
744
+
745
+
746
+ def _neuron_bmm(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
747
+ """`torch.bmm(a, b)`, blocked like `_neuron_matmul` when #123 applies."""
748
+ if a.dim() == 3 and b.dim() == 3 and _neuron_mm_unsafe(a, b):
749
+ return _neuron_matmul(a, b)
750
+ return torch.bmm(a, b)
751
+
752
+
753
+ def _neuron_mm_ksum(a: torch.Tensor, b: torch.Tensor, step: int, mm=None) -> torch.Tensor:
754
+ """Sum over K blocks of `step` of a[:, k] @ b[k], in order."""
755
+ out = None
756
+ step = _even_step(a.shape[1], step)
757
+ for k in range(0, a.shape[1], step):
758
+ ak, bk = a[:, k : k + step], b[k : k + step]
759
+ # The other operand's slice is small and strided: give it a dense copy.
760
+ if not _span_block(ak):
761
+ ak = ak.contiguous()
762
+ if not _span_block(bk):
763
+ bk = bk.contiguous()
764
+ part = _neuron_mm2d(ak, bk, mm)
765
+ out = part if out is None else out + part
766
+ return out
767
+
768
+
769
+ def _neuron_matmul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
770
+ """`torch.matmul(a, b)`, correct on the `neuron` device at any size (trnblas#112).
771
+
772
+ The same call as before unless an operand or the
773
+ result has a partition span of 4 GiB or more; then the product is cut into
774
+ row blocks of the long operand (see `_NEURON_SPAN_BYTES`). Splitting K
775
+ changes the fp32 summation order of those products only. Batched operands
776
+ then run matrix by matrix. Host tensors are never affected.
777
+ """
778
+ if not _neuron_mm_unsafe(a, b):
779
+ return torch.matmul(a, b)
780
+ if a.dim() == 2 and b.dim() == 2:
781
+ return _neuron_mm2d(a, b)
782
+ batch = torch.broadcast_shapes(a.shape[:-2], b.shape[:-2])
783
+ ae = a.expand(*batch, *a.shape[-2:])
784
+ be = b.expand(*batch, *b.shape[-2:])
785
+ M, N = a.shape[-2], b.shape[-1]
786
+ parts = [_neuron_mm2d(ae[idx], be[idx]) for idx in np.ndindex(*batch)]
787
+ return _neuron_cat(parts, 0).reshape(*batch, M, N)
788
+
789
+
584
790
  _dispatch_path: str | None = None
585
791
  _native_ops: dict | None = None
586
792
 
@@ -1516,7 +1722,7 @@ def nki_matmul(A: torch.Tensor, B: torch.Tensor, use_sr: bool = False) -> torch.
1516
1722
  round-to-nearest-even. The CPU fallback emulates SR in software.
1517
1723
  """
1518
1724
  if not (_use_nki() and HAS_NKI):
1519
- result = torch.matmul(A, B)
1725
+ result = _neuron_matmul(A, B)
1520
1726
  return _stochastic_round_cpu(result, A.dtype) if use_sr else result
1521
1727
 
1522
1728
  M, K = A.shape
@@ -1527,9 +1733,12 @@ def nki_matmul(A: torch.Tensor, B: torch.Tensor, use_sr: bool = False) -> torch.
1527
1733
  if use_sr and (route == "aten" or _is_device_tensor(A)):
1528
1734
  _warn_if_sr_unavailable()
1529
1735
  if route == "aten":
1530
- return _aten_on_device(torch.matmul, A, B)
1531
- result = torch.matmul(A, B)
1736
+ return _aten_on_device(_neuron_matmul, A, B)
1737
+ result = _neuron_matmul(A, B)
1532
1738
  return _stochastic_round_cpu(result, A.dtype) if use_sr else result
1739
+ if _neuron_mm_unsafe(A, B):
1740
+ # trnblas#112 / #123: no blocked kernel; the blocked aten product.
1741
+ return _neuron_matmul(A, B)
1533
1742
 
1534
1743
  if not _matmul_kernel_dtypes_ok(A, B):
1535
1744
  if A.dtype == B.dtype == torch.float64 and _fp64_to_kernel("matmul", A, B):
@@ -2518,15 +2727,15 @@ def nki_batched_matmul(A: torch.Tensor, B: torch.Tensor, use_sr: bool = False) -
2518
2727
  ``RuntimeWarning`` and round-to-nearest-even.
2519
2728
  """
2520
2729
  if not (_use_nki() and HAS_NKI):
2521
- return torch.bmm(A, B)
2730
+ return _neuron_bmm(A, B)
2522
2731
 
2523
2732
  Bsz, M, K = A.shape
2524
2733
  _, _, N = B.shape
2525
2734
  route = _route_for(Bsz * M * K * N, A, B)
2526
2735
  if route == "aten":
2527
- return _aten_on_device(torch.bmm, A, B)
2528
- if route != "nki":
2529
- return torch.bmm(A, B)
2736
+ return _aten_on_device(_neuron_bmm, A, B)
2737
+ if route != "nki" or _neuron_mm_unsafe(A, B):
2738
+ return _neuron_bmm(A, B)
2530
2739
 
2531
2740
  if not _matmul_kernel_dtypes_ok(A, B):
2532
2741
  if A.dtype == B.dtype == torch.float64 and _fp64_to_kernel("batched_matmul", A, B):
@@ -475,12 +475,17 @@ def _ao_to_mo_contiguous_lhs(
475
475
  returns wrong values without an error (or aborts with a DMA error) once
476
476
  the right operand reaches 4 GiB (#97, aws-neuron-sdk#1448). With
477
477
  the transposes materialised (a few MB) the same products are correct.
478
+ A contiguous left operand is not enough once a row of
479
+ ``eri.reshape(nbasis, nbasis * naux)`` reaches 32 MiB
480
+ (``nbasis * naux >= 8,388,608`` fp32, #123): both steps go through
481
+ ``_neuron_matmul``, which blocks such operands by rows.
478
482
  """
479
483
  nbasis, _, naux = eri.shape
480
484
  nocc, nvir = C_occ.shape[1], C_vir.shape[1]
481
- half = torch.mm(C_occ.T.contiguous(), eri.reshape(nbasis, nbasis * naux))
485
+ mm = _dispatch._neuron_matmul
486
+ half = mm(C_occ.T.contiguous(), eri.reshape(nbasis, nbasis * naux))
482
487
  half = half.reshape(nocc, nbasis, naux)
483
- return torch.bmm(C_vir.T.contiguous().expand(nocc, nvir, nbasis), half)
488
+ return mm(C_vir.T.contiguous().expand(nocc, nvir, nbasis), half)
484
489
 
485
490
 
486
491
  # Bytes of gathered packed rows the aten df_exchange path materialises at
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trntensor
3
- Version: 0.25.0
3
+ Version: 0.25.1
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
@@ -29,7 +29,7 @@ Provides-Extra: dev
29
29
  Requires-Dist: pytest<9,>=7.0; extra == "dev"
30
30
  Requires-Dist: pytest-benchmark>=4.0; extra == "dev"
31
31
  Requires-Dist: pytest-cov>=4.0; extra == "dev"
32
- Requires-Dist: ruff>=0.6; extra == "dev"
32
+ Requires-Dist: ruff==0.17.3; extra == "dev"
33
33
  Requires-Dist: pre-commit>=3.7; extra == "dev"
34
34
  Requires-Dist: scipy>=1.11; extra == "dev"
35
35
  Requires-Dist: mkdocs>=1.5; extra == "dev"
@@ -169,7 +169,7 @@ core, factors = trntensor.tucker_decompose(tensor, ranks=(5, 5, 5))
169
169
 
170
170
  ## Known issues in earlier releases
171
171
 
172
- Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details are in the [CHANGELOG](CHANGELOG.md).
172
+ Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-04 releases. Details are in the [CHANGELOG](CHANGELOG.md).
173
173
 
174
174
  | Bug | Affected | Fixed in |
175
175
  |-----|----------|----------|
@@ -180,7 +180,14 @@ Silent wrong-result bugs fixed in the 2026-10-31 to 2026-11-02 releases. Details
180
180
  | `einsum(precision="dd")` on float32/float64 was less accurate than `"fast"` (CPU emulation, #84) | 0.17.0–0.22.0 | 0.23.0 |
181
181
  | `multi_einsum` returned float32 results as float64 in mixed-dtype batches (#75) | 0.17.0–0.22.0 | 0.23.0 |
182
182
  | NKI chemistry kernels returned inf for float64 operands, and some kernel routes changed the result dtype (#87) | `df_*` 0.21.0–0.22.0; `ao_to_mo_transform` every release with its kernels | 0.23.0 |
183
- | `ao_to_mo_transform` aten route on the TorchNeuron device was wrong once `eri` exceeded 4 GiB (#97; one LNC=1 case is still open) | through 0.22.0 | 0.23.0 |
183
+ | `ao_to_mo_transform` aten route on the TorchNeuron device was wrong once `eri` exceeded 4 GiB (#97; the LNC=1 gather case is the 0.24.0 row below) | through 0.22.0 | 0.23.0 |
184
+ | `unpack_tril` / `pack_tril` (and the packed-`eri` aten / legacy routes of `ao_to_mo_transform`) on the neuron device at LNC=1 returned wrong data, at times NaN, once one gathered output reached 4 GiB (154 M mismatched elements at 4.99e9 bytes) (#97) | 0.20.0–0.23.0 | 0.24.0 |
185
+ | Complex `tucker_decompose` on the neuron device used `Uᵀ`, not `Uᴴ`: device matmul ignores the lazy conj bit of `.mH` (#89) | 0.23.0 | 0.24.0 |
186
+ | float64 on the neuron device rounded to fp32 in `gather` (device `torch.cat`) and in `pack_tril` / `unpack_tril` / `pack_density` / `unpack_packed` (device `index_select` / fancy indexing), rel. err ~4e-8 (#92) | through 0.23.0 | 0.24.0 |
187
+ | `multi_einsum` under `"auto"` pinned shared host float64 / complex128 operands to the device, where device aten computed them at fp32 precision (#92) | through 0.23.0 | 0.24.0 |
188
+ | Integer, bool, complex and mixed-dtype operands of `einsum` / `multi_einsum` reached the fp32/bf16/fp16 matmul kernels under `set_backend("nki")`, or under `"auto"` above the size thresholds (trnsci/trnsci#35) | through 0.23.0 | 0.24.0 |
189
+ | `einsum(..., out=)` never wrote `out`, so the documented `einsum(..., beta=1.0, out=acc)` accumulation left `acc` unchanged (#77) | 0.3.0–0.23.0 | 0.24.0 |
190
+ | `cp_reconstruct` returned float32 for bf16 / fp16 factors (#78) | 0.1.1–0.23.0 | 0.24.0 |
184
191
 
185
192
  ## Related Projects
186
193
 
@@ -53,6 +53,8 @@ tests/test_einsum.py
53
53
  tests/test_host_output.py
54
54
  tests/test_kernel_dtype_guard.py
55
55
  tests/test_native_dispatch.py
56
+ tests/test_neuron_span.py
57
+ tests/test_neuron_span_device.py
56
58
  tests/test_nki.py
57
59
  tests/test_nki_compile.py
58
60
  tests/test_nki_kernels.py
@@ -5,7 +5,7 @@ numpy>=1.24
5
5
  pytest<9,>=7.0
6
6
  pytest-benchmark>=4.0
7
7
  pytest-cov>=4.0
8
- ruff>=0.6
8
+ ruff==0.17.3
9
9
  pre-commit>=3.7
10
10
  scipy>=1.11
11
11
  mkdocs>=1.5
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes