trnsolver 0.23.0__tar.gz → 0.24.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. {trnsolver-0.23.0 → trnsolver-0.24.0}/CHANGELOG.md +35 -0
  2. {trnsolver-0.23.0 → trnsolver-0.24.0}/PKG-INFO +1 -1
  3. {trnsolver-0.23.0 → trnsolver-0.24.0}/pyproject.toml +1 -1
  4. trnsolver-0.24.0/scripts/conformance_expect.py +65 -0
  5. trnsolver-0.24.0/tests/conftest.py +154 -0
  6. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_conformance.py +93 -13
  7. trnsolver-0.24.0/tests/test_device_known.py +76 -0
  8. trnsolver-0.24.0/tests/test_psum_accumulate_lint.py +188 -0
  9. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/__init__.py +1 -1
  10. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/nki/subspace.py +18 -15
  11. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver.egg-info/PKG-INFO +1 -1
  12. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver.egg-info/SOURCES.txt +3 -0
  13. trnsolver-0.23.0/tests/conftest.py +0 -82
  14. {trnsolver-0.23.0 → trnsolver-0.24.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  15. {trnsolver-0.23.0 → trnsolver-0.24.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  16. {trnsolver-0.23.0 → trnsolver-0.24.0}/.github/pull_request_template.md +0 -0
  17. {trnsolver-0.23.0 → trnsolver-0.24.0}/.github/workflows/ci.yml +0 -0
  18. {trnsolver-0.23.0 → trnsolver-0.24.0}/.github/workflows/neuron.yml +0 -0
  19. {trnsolver-0.23.0 → trnsolver-0.24.0}/.github/workflows/notify-umbrella.yml +0 -0
  20. {trnsolver-0.23.0 → trnsolver-0.24.0}/.github/workflows/publish.yml +0 -0
  21. {trnsolver-0.23.0 → trnsolver-0.24.0}/.gitignore +0 -0
  22. {trnsolver-0.23.0 → trnsolver-0.24.0}/.pre-commit-config.yaml +0 -0
  23. {trnsolver-0.23.0 → trnsolver-0.24.0}/CLAUDE.md +0 -0
  24. {trnsolver-0.23.0 → trnsolver-0.24.0}/CODE_OF_CONDUCT.md +0 -0
  25. {trnsolver-0.23.0 → trnsolver-0.24.0}/CONTRIBUTING.md +0 -0
  26. {trnsolver-0.23.0 → trnsolver-0.24.0}/LICENSE +0 -0
  27. {trnsolver-0.23.0 → trnsolver-0.24.0}/README.md +0 -0
  28. {trnsolver-0.23.0 → trnsolver-0.24.0}/benchmarks/bench_cuda.py +0 -0
  29. {trnsolver-0.23.0 → trnsolver-0.24.0}/benchmarks/bench_solver.py +0 -0
  30. {trnsolver-0.23.0 → trnsolver-0.24.0}/benchmarks/conftest.py +0 -0
  31. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/api/eigen.md +0 -0
  32. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/api/factor.md +0 -0
  33. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/api/iterative.md +0 -0
  34. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/api/nki.md +0 -0
  35. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/architecture.md +0 -0
  36. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/aws_setup.md +0 -0
  37. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/benchmarks.md +0 -0
  38. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/developing_kernels.md +0 -0
  39. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/index.md +0 -0
  40. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/installation.md +0 -0
  41. {trnsolver-0.23.0 → trnsolver-0.24.0}/docs/quickstart.md +0 -0
  42. {trnsolver-0.23.0 → trnsolver-0.24.0}/examples/df_store.py +0 -0
  43. {trnsolver-0.23.0 → trnsolver-0.24.0}/examples/scf_df_mp2.py +0 -0
  44. {trnsolver-0.23.0 → trnsolver-0.24.0}/examples/scf_df_rhf.py +0 -0
  45. {trnsolver-0.23.0 → trnsolver-0.24.0}/examples/scf_eigen.py +0 -0
  46. {trnsolver-0.23.0 → trnsolver-0.24.0}/infra/terraform/README.md +0 -0
  47. {trnsolver-0.23.0 → trnsolver-0.24.0}/infra/terraform/gpu.tf +0 -0
  48. {trnsolver-0.23.0 → trnsolver-0.24.0}/infra/terraform/main.tf +0 -0
  49. {trnsolver-0.23.0 → trnsolver-0.24.0}/mkdocs.yml +0 -0
  50. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/bench_eager_handle.py +0 -0
  51. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/bench_gp_precond.py +0 -0
  52. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/bench_jacobi.py +0 -0
  53. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/bench_jacobi_multicore.py +0 -0
  54. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/bench_occupied_subspace.py +0 -0
  55. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/bench_scf.py +0 -0
  56. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/bench_scf_ladder.py +0 -0
  57. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/probe_cg_reduction.py +0 -0
  58. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/probe_large_n_split.py +0 -0
  59. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/run_cuda_tests.sh +0 -0
  60. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/run_neuron_tests.sh +0 -0
  61. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/run_simulator_tests.sh +0 -0
  62. {trnsolver-0.23.0 → trnsolver-0.24.0}/scripts/stop_neuron_ci.sh +0 -0
  63. {trnsolver-0.23.0 → trnsolver-0.24.0}/setup.cfg +0 -0
  64. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_bench_scf_ladder.py +0 -0
  65. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_block_neuron.py +0 -0
  66. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_cg_block.py +0 -0
  67. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_cg_reduction.py +0 -0
  68. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_compile.py +0 -0
  69. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_complex_rhs.py +0 -0
  70. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_dtype.py +0 -0
  71. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_eigen.py +0 -0
  72. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_eigh_cutover.py +0 -0
  73. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_eigh_neuron.py +0 -0
  74. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_factor.py +0 -0
  75. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_hermitian_batch.py +0 -0
  76. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_iterative.py +0 -0
  77. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_iterative_autograd.py +0 -0
  78. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_iterative_rhs_scale.py +0 -0
  79. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_jacobi.py +0 -0
  80. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_jacobi_onezero_arg.py +0 -0
  81. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_kernel_dtype_guard.py +0 -0
  82. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_native_dispatch.py +0 -0
  83. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_nki_compile.py +0 -0
  84. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_nki_native.py +0 -0
  85. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_nki_sim.py +0 -0
  86. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_nki_tail_audit.py +0 -0
  87. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_orthogonalize.py +0 -0
  88. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_scf_df_mp2.py +0 -0
  89. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_scf_df_rhf.py +0 -0
  90. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_subspace.py +0 -0
  91. {trnsolver-0.23.0 → trnsolver-0.24.0}/tests/test_trace_cache_safety.py +0 -0
  92. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/_jacobi.py +0 -0
  93. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/block.py +0 -0
  94. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/eigen.py +0 -0
  95. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/factor.py +0 -0
  96. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/iterative.py +0 -0
  97. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/nki/__init__.py +0 -0
  98. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/nki/_native.py +0 -0
  99. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/nki/dispatch.py +0 -0
  100. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/nki/eigh_pool.py +0 -0
  101. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/nki/jacobi.py +0 -0
  102. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/orthogonalize.py +0 -0
  103. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver/subspace.py +0 -0
  104. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver.egg-info/dependency_links.txt +0 -0
  105. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver.egg-info/requires.txt +0 -0
  106. {trnsolver-0.23.0 → trnsolver-0.24.0}/trnsolver.egg-info/top_level.txt +0 -0
  107. {trnsolver-0.23.0 → trnsolver-0.24.0}/uv.lock +0 -0
@@ -7,6 +7,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.24.0] — 2026-11-28
11
+
12
+ ### Added
13
+
14
+ - **Device conformance runs are signal-only (trnsci/trnsci#35).** On a
15
+ device run (`--backend nki --conformance-device neuron`), the known
16
+ platform-limit cases in `tests/test_conformance.py` are marked
17
+ `xfail(strict=False)` by category rules: `complex-linalg` (41 cases, #98)
18
+ and `device-fp64` (60 cases, #147, which takes over #144's
19
+ `test_gmres_truncated[2-2]` marker). CPU runs are unchanged and still run
20
+ every case. The run ends with a summary (passed, xfailed and XPASS by
21
+ category, NEW failures); `--conformance-json PATH` writes it as JSON, and
22
+ `scripts/conformance_expect.py` merges chunked runs and exits 1 on NEW
23
+ failures. Test-only; no library change.
24
+
25
+ ### Fixed
26
+
27
+ - **`subspace_filter_kernel` / `subspace_step_kernel` PSUM accumulation
28
+ groups now open with a matmul write (trnsci/trnsci#185).** The kernels
29
+ zeroed PSUM tiles with `nl.zeros(..., buffer=nl.psum)` (a memset) and then
30
+ accumulated into them with `nisa.nc_matmul(..., accumulate=True)`. The
31
+ `nc_matmul` docs make that undefined behaviour on NeuronCore-v3 (Trn2):
32
+ accumulating onto PSUM that a non-matmul instruction initialised is not
33
+ supported, and the first write must use `accumulate=False`. Device results
34
+ matched the references so far, but they relied on that behaviour. The five
35
+ sites (the on-chip `X Q` fold, the F-apply, the residual-norm reduction,
36
+ the Gram blocks and `E = Y - X M`) pass `accumulate=(j > 0)` over their
37
+ static loops, and their PSUM tiles are plain `nl.ndarray`s, so the
38
+ redundant memsets are gone. The two `matmul_kernel` variants in
39
+ `nki/dispatch.py` already wrote with `accumulate=False` and are unchanged.
40
+ Simulator outputs are bitwise equal to 0.23.0 at the test shapes. A new
41
+ static lint (`tests/test_psum_accumulate_lint.py`) fails when a zeroed
42
+ PSUM tile is a matmul accumulation target, or when a tile is only ever
43
+ accumulated into.
44
+
10
45
  ## [0.23.0] — 2026-11-10
11
46
 
12
47
  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: trnsolver
3
- Version: 0.23.0
3
+ Version: 0.24.0
4
4
  Summary: Linear solvers and eigendecomposition for AWS Trainium via NKI
5
5
  Author-email: Scott Friedman <scttfrdmn@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "trnsolver"
7
- version = "0.23.0"
7
+ version = "0.24.0"
8
8
  description = "Linear solvers and eigendecomposition for AWS Trainium via NKI"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env python3
2
+ """Merge device conformance summaries and list the NEW failures.
3
+
4
+ A device conformance run (``pytest tests/test_conformance.py --backend nki
5
+ --conformance-device neuron``) marks known platform limits as
6
+ ``xfail(strict=False)`` with a ``[device-known:<category>]`` reason, and prints
7
+ a summary at the end. Runs on a Trainium box are split into chunks, so pass
8
+ ``--conformance-json PATH`` to each chunk and merge them here::
9
+
10
+ pytest tests/test_conformance.py --backend nki --conformance-device neuron \\
11
+ -k "<chunk>" --conformance-json chunk1.json
12
+ python scripts/conformance_expect.py chunk*.json
13
+
14
+ Prints passed, xfailed by category, XPASS by category (a known category that
15
+ now passes: a signal, not a failure) and the NEW failures. Exits 1 if there
16
+ are NEW failures, else 0.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import sys
24
+
25
+
26
+ def merge(paths):
27
+ out = {"passed": 0, "skipped": 0, "xfailed": {}, "xpassed": {}, "new_failures": []}
28
+ for p in paths:
29
+ with open(p) as fh:
30
+ s = json.load(fh)
31
+ out["passed"] += s["passed"]
32
+ out["skipped"] += s["skipped"]
33
+ for key in ("xfailed", "xpassed"):
34
+ for cat, ids in s[key].items():
35
+ out[key].setdefault(cat, []).extend(ids)
36
+ out["new_failures"].extend(s["new_failures"])
37
+ return out
38
+
39
+
40
+ def report(s, verbose=False):
41
+ lines = ["conformance expectations (device run)"]
42
+ lines.append(f" passed: {s['passed']} skipped: {s['skipped']}")
43
+ for key, label in (("xfailed", "xfailed"), ("xpassed", "XPASS (known category now passes)")):
44
+ lines.append(f" {label}: {sum(len(v) for v in s[key].values())}")
45
+ for cat, ids in sorted(s[key].items()):
46
+ lines.append(f" {cat}: {len(ids)}")
47
+ if verbose or key == "xpassed":
48
+ lines.extend(f" {i}" for i in ids)
49
+ lines.append(f" NEW failures: {len(s['new_failures'])}")
50
+ lines.extend(f" {i}" for i in s["new_failures"])
51
+ return "\n".join(lines)
52
+
53
+
54
+ def main(argv=None):
55
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
56
+ ap.add_argument("json", nargs="+", help="--conformance-json files from device runs")
57
+ ap.add_argument("-v", "--verbose", action="store_true", help="list xfailed IDs too")
58
+ args = ap.parse_args(argv)
59
+ s = merge(args.json)
60
+ print(report(s, args.verbose))
61
+ return 1 if s["new_failures"] else 0
62
+
63
+
64
+ if __name__ == "__main__":
65
+ sys.exit(main())
@@ -0,0 +1,154 @@
1
+ """Test configuration and fixtures."""
2
+
3
+ import atexit
4
+ import os
5
+ import shutil
6
+ import tempfile
7
+
8
+ import pytest
9
+ import torch
10
+
11
+ # NKI trace cache (aws-neuron/aws-neuron-sdk#1454, trnsci/trnsci#35).
12
+ # `import torch_neuronx` turns the cache on (NKI_ENABLE_TRACE_CACHE=1), so
13
+ # that is how users run these kernels, and the neuron tests run the same way.
14
+ # The cache lives on disk and is versioned by wheel .dist-info, which an
15
+ # editable install or source checkout does not change, so a shared cache could
16
+ # serve a trace of an older kernel. Each session therefore gets a fresh,
17
+ # empty cache directory (NKI_TRACE_CACHE_URL), removed at exit.
18
+ # tests/test_trace_cache_safety.py checks that no kernel depends on a value
19
+ # the cache key misses (closure or global). Overrides: NKI_ENABLE_TRACE_CACHE=0
20
+ # runs with the cache off; an explicit NKI_TRACE_CACHE_URL is kept as is.
21
+ os.environ.setdefault("NKI_ENABLE_TRACE_CACHE", "1")
22
+ if os.environ["NKI_ENABLE_TRACE_CACHE"] != "0" and "NKI_TRACE_CACHE_URL" not in os.environ:
23
+ _trace_cache_dir = tempfile.mkdtemp(prefix="trnsolver-nki-trace-cache-")
24
+ os.environ["NKI_TRACE_CACHE_URL"] = _trace_cache_dir
25
+ atexit.register(shutil.rmtree, _trace_cache_dir, ignore_errors=True)
26
+
27
+
28
+ def pytest_addoption(parser):
29
+ # Reference-conformance suite (tests/test_conformance.py): run the same
30
+ # cases against a non-default backend and/or with device inputs on a
31
+ # Trainium box, e.g. ``pytest tests/test_conformance.py --backend nki
32
+ # --conformance-device neuron``.
33
+ parser.addoption(
34
+ "--backend",
35
+ default="pytorch",
36
+ choices=("pytorch", "nki", "auto"),
37
+ help="trnsolver backend for tests/test_conformance.py (default: pytorch)",
38
+ )
39
+ parser.addoption(
40
+ "--conformance-device",
41
+ default="cpu",
42
+ help="device for tests/test_conformance.py inputs (default: cpu; e.g. neuron)",
43
+ )
44
+ parser.addoption(
45
+ "--conformance-json",
46
+ default=None,
47
+ metavar="PATH",
48
+ help="write the device conformance summary (passed, xfailed/XPASS by category, "
49
+ "NEW failures) as JSON",
50
+ )
51
+
52
+
53
+ def pytest_configure(config):
54
+ config.addinivalue_line("markers", "neuron: requires Neuron hardware")
55
+
56
+
57
+ @pytest.fixture
58
+ def rng():
59
+ return torch.Generator().manual_seed(42)
60
+
61
+
62
+ @pytest.fixture
63
+ def sym_matrix(rng):
64
+ """Random symmetric matrix."""
65
+
66
+ def _make(n, dtype=torch.float32):
67
+ A = torch.randn(n, n, generator=rng, dtype=dtype)
68
+ return 0.5 * (A + A.T)
69
+
70
+ return _make
71
+
72
+
73
+ @pytest.fixture
74
+ def spd_matrix(rng):
75
+ """Symmetric positive definite matrix."""
76
+
77
+ def _make(n, dtype=torch.float32):
78
+ A = torch.randn(n, n, generator=rng, dtype=dtype)
79
+ return A @ A.T + n * torch.eye(n, dtype=dtype)
80
+
81
+ return _make
82
+
83
+
84
+ @pytest.fixture
85
+ def random_matrix(rng):
86
+ def _make(m, n, dtype=torch.float32):
87
+ return torch.randn(m, n, generator=rng, dtype=dtype)
88
+
89
+ return _make
90
+
91
+
92
+ # ---------------------------------------------------------------- device conformance summary
93
+ # Device conformance runs (``--backend nki --conformance-device neuron``) mark
94
+ # known platform limits ``xfail(strict=False)`` at run time, with a reason that
95
+ # starts ``[device-known:<category>]`` (see DEVICE_KNOWN in
96
+ # tests/test_conformance.py). On a non-CPU device run this prints passed,
97
+ # xfailed and XPASS by category, and the NEW failures (anything not expected).
98
+ # ``--conformance-json PATH`` also writes it as JSON; merge the JSON from
99
+ # chunked runs with ``python scripts/conformance_expect.py run1.json ...``.
100
+
101
+ _KNOWN_PREFIX = "[device-known:"
102
+
103
+
104
+ def _expect_category(reason):
105
+ reason = reason or ""
106
+ if reason.startswith(_KNOWN_PREFIX):
107
+ return reason[len(_KNOWN_PREFIX) :].split("]", 1)[0]
108
+ return "other xfail"
109
+
110
+
111
+ def _expect_summary(stats):
112
+ def ids(key):
113
+ return [
114
+ r.nodeid for r in stats.get(key, []) if getattr(r, "when", "call") in ("call", "setup")
115
+ ]
116
+
117
+ by_cat = {}
118
+ for key in ("xfailed", "xpassed"):
119
+ for r in stats.get(key, []):
120
+ cat = _expect_category(getattr(r, "wasxfail", ""))
121
+ by_cat.setdefault(key, {}).setdefault(cat, []).append(r.nodeid)
122
+ return {
123
+ "passed": len(ids("passed")),
124
+ "skipped": len(stats.get("skipped", [])),
125
+ "xfailed": by_cat.get("xfailed", {}),
126
+ "xpassed": by_cat.get("xpassed", {}),
127
+ "new_failures": ids("failed") + [r.nodeid for r in stats.get("error", [])],
128
+ }
129
+
130
+
131
+ def _print_expect_summary(write, s):
132
+ write("conformance expectations (device run)")
133
+ write(f" passed: {s['passed']} skipped: {s['skipped']}")
134
+ for key, label in (("xfailed", "xfailed"), ("xpassed", "XPASS (known category now passes)")):
135
+ total = sum(len(v) for v in s[key].values())
136
+ write(f" {label}: {total}")
137
+ for cat, nodeids in sorted(s[key].items()):
138
+ write(f" {cat}: {len(nodeids)}")
139
+ write(f" NEW failures: {len(s['new_failures'])}")
140
+ for nodeid in s["new_failures"]:
141
+ write(f" {nodeid}")
142
+
143
+
144
+ def pytest_terminal_summary(terminalreporter, exitstatus, config):
145
+ path = config.getoption("--conformance-json", None)
146
+ if config.getoption("--conformance-device", "cpu") == "cpu" and not path:
147
+ return
148
+ s = _expect_summary(terminalreporter.stats)
149
+ _print_expect_summary(lambda line: terminalreporter.write_line(line), s)
150
+ if path:
151
+ import json
152
+
153
+ with open(path, "w") as fh:
154
+ json.dump(s, fh, indent=1)
@@ -272,6 +272,94 @@ def _pending(issue, pr, what):
272
272
  KNOWN: dict[str, pytest.MarkDecorator] = {} # filled in next to each case table
273
273
 
274
274
 
275
+ # ---------------------------------------------------------------- device-known categories
276
+ #
277
+ # A device conformance run (``--backend nki --conformance-device neuron``) has
278
+ # known failures that are platform limits, not trnsolver bugs. Each category
279
+ # has one tracking issue, and the cases in it are marked
280
+ # ``xfail(strict=False)`` at run time, on device runs only (the pattern of
281
+ # #146): CPU CI runs them and they must pass. So on device a NEW failure is the
282
+ # only red, and a case of a known category that starts to pass shows as XPASS,
283
+ # a signal rather than a failure. The rules are by test and parameter, not ID
284
+ # lists, from the trnsci/trnsci#35 window-4/5/6 baselines (41 complex, 60
285
+ # device float64). The conftest summary counts them by category;
286
+ # scripts/conformance_expect.py merges chunked runs.
287
+
288
+ DEVICE_KNOWN = {
289
+ "complex-linalg": (
290
+ "trnsci/trnsolver#98",
291
+ "complex cholesky/eigh/svd/solve/qr/lu are unsupported on the neuron device",
292
+ ),
293
+ "device-fp64": (
294
+ "trnsci/trnsolver#147",
295
+ "device float64 under explicit nki computes at fp32 precision "
296
+ "(fp64 policy, #89): fp64-tight residual, solve and torch.equal checks",
297
+ ),
298
+ }
299
+
300
+ # Every case of these tests is float64 with an fp64-tight check (cg / gmres /
301
+ # gmres_ir "reported != true residual" or x vs linalg.solve at <= 1e-8; schur
302
+ # QTQᵀ at 1e-8; eigh_randomized eigenvalues across seeds at 1e-8).
303
+ _FP64_WHOLE_TESTS = {
304
+ "test_cg",
305
+ "test_gmres",
306
+ "test_gmres_ir",
307
+ "test_scaled_system",
308
+ "test_cg_exact_x0",
309
+ "test_schur_requires_grad_raises",
310
+ "test_eigh_randomized_seeds_differ_answer_same",
311
+ }
312
+ # Checked at 1e-8 against linalg.solve; the other three cases use tol_for(F64).
313
+ _FP64_NONCONTIG_EXTRA = {"cg-b_step", "gmres-A_T", "gmres_ir-A_T"}
314
+ # 1-D operands: _view builds the device view with torch.stack, which rounds
315
+ # float64 to fp32, so the torch.equal layout check fails.
316
+ _FP64_VECTOR_OPS = {"solve_vec", "solve_spd_vec"}
317
+
318
+
319
+ def _device_known_category(node) -> str | None:
320
+ """The DEVICE_KNOWN category of a conformance case on a device nki run, or None."""
321
+ name = getattr(node, "originalname", None) or node.name
322
+ cs = getattr(node, "callspec", None)
323
+ p = cs.params if cs is not None else {}
324
+ dt = p.get("dt")
325
+ if name == "test_dtype":
326
+ return "complex-linalg" if dt.is_complex and p["op"] not in REAL_ONLY else None
327
+ if name == "test_mixed_real_complex":
328
+ # eigh_generalized may raise (an accepted skip); solve / solve_spd fail.
329
+ return "complex-linalg" if p["op"] in ("solve", "solve_spd") else None
330
+ if name == "test_eigh_randomized_dtype":
331
+ return "complex-linalg" if dt is not None and dt.is_complex else None
332
+ if name in _FP64_WHOLE_TESTS:
333
+ return "device-fp64"
334
+ if name == "test_noncontiguous":
335
+ return "device-fp64" if dt == F64 and p["op"] in _FP64_VECTOR_OPS else None
336
+ if name == "test_noncontiguous_extra":
337
+ return "device-fp64" if p["case"] in _FP64_NONCONTIG_EXTRA else None
338
+ if name == "test_gmres_truncated":
339
+ return "device-fp64" if (p["maxiter"], p["restart"]) == (2, 2) else None # #144
340
+ if name == "test_cg_maxiter":
341
+ # maxiter=3: the fp32 reported residual misses the fp64 true residual
342
+ # by ~1.1e-6 relative (check: 1e-6). maxiter=0 (x0 comes back
343
+ # unchanged) and maxiter=1 pass on device (trnsci/trnsci#35, windows 6, 7).
344
+ return "device-fp64" if p["maxiter"] == 3 else None
345
+ if name == "test_inv_sqrt_spd_ns_kwargs":
346
+ # max_iters=0: torch.equal against the fp64 initial guess.
347
+ return "device-fp64" if p["max_iters"] == 0 else None
348
+ return None
349
+
350
+
351
+ @pytest.fixture(autouse=True)
352
+ def _device_known_xfail(request, _conformance_env):
353
+ if BACKEND != "nki" or DEV.type == "cpu":
354
+ return
355
+ cat = _device_known_category(request.node)
356
+ if cat is not None:
357
+ issue, what = DEVICE_KNOWN[cat]
358
+ request.applymarker(
359
+ pytest.mark.xfail(strict=False, reason=f"[device-known:{cat}] {issue}: {what}")
360
+ )
361
+
362
+
275
363
  # ---------------------------------------------------------------- reference checkers
276
364
 
277
365
 
@@ -1047,19 +1135,11 @@ def test_gmres(n, tol, restart, maxiter, callable_A, x0):
1047
1135
 
1048
1136
 
1049
1137
  @pytest.mark.parametrize("maxiter,restart", [(1, 3), (2, 2)])
1050
- def test_gmres_truncated(request, maxiter, restart):
1051
- if BACKEND == "nki" and DEV.type != "cpu" and (maxiter, restart) == (2, 2):
1052
- # Device float64 under explicit nki runs at fp32. With the #141
1053
- # reductions the reported residual is 1.2e-6 (relative) from the fp64
1054
- # true residual, against a 1e-6 bound: the known device-fp64 category,
1055
- # accepted into the baseline (trnsci/trnsolver#144, 2026-11-10).
1056
- request.applymarker(
1057
- pytest.mark.xfail(
1058
- strict=False,
1059
- reason="trnsci/trnsolver#144: device float64 at fp32 precision, "
1060
- "reported vs true residual 1.2e-6 > 1e-6 (known category)",
1061
- )
1062
- )
1138
+ def test_gmres_truncated(maxiter, restart):
1139
+ # [2-2] on device under nki: the device-fp64 category (DEVICE_KNOWN). With
1140
+ # the #141 reductions the reported residual is 1.2e-6 (relative) from the
1141
+ # fp64 true residual, against a 1e-6 bound; accepted into the baseline
1142
+ # (trnsci/trnsolver#144, 2026-11-10).
1063
1143
  A, b = gen(20), rand(20)
1064
1144
  out = ts.gmres(dev(A), dev(b), tol=1e-14, maxiter=maxiter, restart=restart)
1065
1145
  _check_iterative(A, b, out, 1e-14, maxiter * restart)
@@ -0,0 +1,76 @@
1
+ """The device-known category rules of tests/test_conformance.py (trnsci/trnsci#35).
2
+
3
+ CPU only: checks that representative conformance IDs map to their category
4
+ (and others to None) without a device, and that the conftest summary groups
5
+ xfail reasons by category.
6
+ """
7
+
8
+ from types import SimpleNamespace
9
+
10
+ import pytest
11
+ import torch
12
+ from conftest import _expect_category, _expect_summary
13
+ from test_conformance import DEVICE_KNOWN, _device_known_category
14
+
15
+ c64, c128, f32, f64 = torch.complex64, torch.complex128, torch.float32, torch.float64
16
+
17
+
18
+ def node(name, **params):
19
+ return SimpleNamespace(originalname=name, name=name, callspec=SimpleNamespace(params=params))
20
+
21
+
22
+ @pytest.mark.parametrize(
23
+ "item,cat",
24
+ [
25
+ (node("test_dtype", op="cholesky", dt=c64), "complex-linalg"),
26
+ (node("test_dtype", op="eigh_generalized", dt=c128), "complex-linalg"),
27
+ (node("test_dtype", op="schur", dt=c128), None), # real-only: raising is a skip
28
+ (node("test_dtype", op="cholesky", dt=f64), None),
29
+ (node("test_dtype", op="svd", dt=f32), None),
30
+ (node("test_mixed_real_complex", op="solve"), "complex-linalg"),
31
+ (node("test_mixed_real_complex", op="eigh_generalized"), None),
32
+ (node("test_eigh_randomized_dtype", dt=c128), "complex-linalg"),
33
+ (node("test_eigh_randomized_dtype", dt=f64), None),
34
+ (node("test_cg", n=129, tol=1e-10, M="jacobi", callable_A=False, x0=False), "device-fp64"),
35
+ (node("test_gmres_ir", n=1, kw={}), "device-fp64"),
36
+ (node("test_noncontiguous", op="solve_vec", dt=f64, kind="step_slice"), "device-fp64"),
37
+ (node("test_noncontiguous", op="solve_vec", dt=f32, kind="step_slice"), None),
38
+ (node("test_noncontiguous", op="cholesky", dt=f64, kind="step_slice"), None),
39
+ (node("test_noncontiguous_extra", case="gmres-A_T"), "device-fp64"),
40
+ (node("test_noncontiguous_extra", case="solve-B_T"), None),
41
+ (node("test_gmres_truncated", maxiter=2, restart=2), "device-fp64"),
42
+ (node("test_gmres_truncated", maxiter=1, restart=3), None),
43
+ (node("test_cg_maxiter", maxiter=0), None),
44
+ (node("test_cg_maxiter", maxiter=1), None),
45
+ (node("test_cg_maxiter", maxiter=3), "device-fp64"),
46
+ (node("test_inv_sqrt_spd_ns_kwargs", max_iters=0, tol=1e-7), "device-fp64"),
47
+ (node("test_inv_sqrt_spd_ns_kwargs", max_iters=20, tol=1e-7), None),
48
+ (SimpleNamespace(name="test_cg_exact_x0"), "device-fp64"),
49
+ (node("test_iterative_dtype", solver="cg", dt=c64), None),
50
+ (SimpleNamespace(name="test_lu_convention"), None),
51
+ ],
52
+ )
53
+ def test_category_rules(item, cat):
54
+ got = _device_known_category(item)
55
+ assert got == cat
56
+ assert got is None or got in DEVICE_KNOWN
57
+
58
+
59
+ def test_summary_groups_by_category():
60
+ def rep(nodeid, reason=None):
61
+ return SimpleNamespace(nodeid=nodeid, when="call", wasxfail=reason)
62
+
63
+ assert _expect_category("[device-known:device-fp64] trnsci/trnsolver#147: x") == "device-fp64"
64
+ assert _expect_category("trnsci/trnsolver#132, fix in #1: y") == "other xfail"
65
+ s = _expect_summary(
66
+ {
67
+ "passed": [rep("a"), rep("b")],
68
+ "xfailed": [rep("c", "[device-known:complex-linalg] #98: y"), rep("d", "plain")],
69
+ "xpassed": [rep("e", "[device-known:device-fp64] #147: x")],
70
+ "failed": [rep("f")],
71
+ }
72
+ )
73
+ assert s["passed"] == 2
74
+ assert s["xfailed"] == {"complex-linalg": ["c"], "other xfail": ["d"]}
75
+ assert s["xpassed"] == {"device-fp64": ["e"]}
76
+ assert s["new_failures"] == ["f"]
@@ -0,0 +1,188 @@
1
+ """Static lint: every PSUM accumulation group is opened by a matmul write (trnsci/trnsci#185).
2
+
3
+ ``nisa.nc_matmul`` documents that on NeuronCore-v3 (Trn2) a matmul that
4
+ accumulates onto PSUM initialised by a non-matmul instruction is undefined
5
+ behaviour, and that the first matmul into a PSUM location must use
6
+ ``accumulate=False``. ``nl.zeros(..., buffer=nl.psum)`` is such an
7
+ instruction (a memset), so ``nl.zeros`` followed by
8
+ ``nc_matmul(..., accumulate=True)`` on the same tile relies on undefined
9
+ behaviour even when the device happens to return the right numbers.
10
+
11
+ The kernels open each group with a matmul write instead: the first K step
12
+ is peeled with ``accumulate=False`` (``nl.affine_range`` indices may be
13
+ symbolic), or a static loop passes ``accumulate=(k > 0)``.
14
+
15
+ The scan parses every module under ``<package>/nki`` and, per top-level
16
+ function (nested helpers share their enclosing kernel's tile names), flags:
17
+
18
+ * ``zeroed-psum``: a PSUM tile bound by ``nl.zeros(..., buffer=nl.psum)``
19
+ (directly, in a list, or appended to one) that is the ``dst`` of an
20
+ ``nc_matmul`` whose ``accumulate`` is anything but the literal ``False``;
21
+ * ``never-opened``: a PSUM tile that some ``nc_matmul`` accumulates into with
22
+ the literal ``accumulate=True`` but that no ``nc_matmul`` writes with any
23
+ other ``accumulate`` value, so nothing opens its group.
24
+
25
+ A PSUM tile zeroed for a non-matmul reason (say, a later Vector Engine
26
+ accumulate) may keep its memset; it just must not be a matmul accumulation
27
+ target.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import ast
33
+ import textwrap
34
+ from pathlib import Path
35
+
36
+ PACKAGE = "trnsolver"
37
+ NKI_DIR = Path(__file__).resolve().parents[1] / PACKAGE / "nki"
38
+
39
+ # Fewest nc_matmul calls the scan must see, so a broken detector cannot pass vacuously.
40
+ MIN_MATMULS = 10
41
+
42
+
43
+ def _is_psum_alloc(node: ast.AST, fn: str) -> bool:
44
+ """``nl.<fn>(..., buffer=nl.psum)``."""
45
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
46
+ return False
47
+ if node.func.attr != fn:
48
+ return False
49
+ return any(
50
+ kw.arg == "buffer" and isinstance(kw.value, ast.Attribute) and kw.value.attr == "psum"
51
+ for kw in node.keywords
52
+ )
53
+
54
+
55
+ def _root(node: ast.AST) -> str | None:
56
+ """``accs[j][ug]`` / ``ps[0:L, 0:RB]`` / ``ps`` -> the bound name."""
57
+ while isinstance(node, (ast.Subscript, ast.Attribute, ast.Starred)):
58
+ node = node.value
59
+ return node.id if isinstance(node, ast.Name) else None
60
+
61
+
62
+ def _contains(node: ast.AST, fn: str) -> bool:
63
+ return any(_is_psum_alloc(n, fn) for n in ast.walk(node))
64
+
65
+
66
+ def _bound_tiles(func: ast.AST, fn: str) -> set[str]:
67
+ """Names bound to PSUM tiles made by ``nl.<fn>`` (also lists of them)."""
68
+ names: set[str] = set()
69
+ for node in ast.walk(func):
70
+ if isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None:
71
+ if _contains(node.value, fn):
72
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
73
+ for t in targets:
74
+ for n in ast.walk(t):
75
+ if isinstance(n, ast.Name):
76
+ names.add(n.id)
77
+ elif (
78
+ isinstance(node, ast.Call)
79
+ and isinstance(node.func, ast.Attribute)
80
+ and node.func.attr in ("append", "extend", "insert")
81
+ and any(_contains(a, fn) for a in node.args)
82
+ ):
83
+ r = _root(node.func.value)
84
+ if r:
85
+ names.add(r)
86
+ return names
87
+
88
+
89
+ def _matmuls(func: ast.AST):
90
+ """``(lineno, dst root name, accumulate node or None)`` per ``nc_matmul``."""
91
+ for node in ast.walk(func):
92
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
93
+ continue
94
+ if node.func.attr != "nc_matmul":
95
+ continue
96
+ kws = {kw.arg: kw.value for kw in node.keywords}
97
+ dst = kws.get("dst", node.args[0] if node.args else None)
98
+ acc = kws.get("accumulate")
99
+ if acc is None and len(node.args) >= 9: # positional accumulate (signature order)
100
+ acc = node.args[8]
101
+ yield node.lineno, _root(dst) if dst is not None else None, acc
102
+
103
+
104
+ def _is_const(node: ast.AST | None, value: bool) -> bool:
105
+ return isinstance(node, ast.Constant) and node.value is value
106
+
107
+
108
+ def lint_source(src: str, label: str = "<src>") -> tuple[list[str], int]:
109
+ """(findings, number of nc_matmul calls seen) for one module's source."""
110
+ tree = ast.parse(src)
111
+ findings: list[str] = []
112
+ seen = 0
113
+ tops = [n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
114
+ # Top-level functions only: a def nested in another is scanned with its parent.
115
+ nested = {id(c) for t in tops for c in ast.walk(t) if c is not t and c in tops}
116
+ for func in (t for t in tops if id(t) not in nested):
117
+ zeroed = _bound_tiles(func, "zeros")
118
+ psum = zeroed | _bound_tiles(func, "ndarray")
119
+ mms = list(_matmuls(func))
120
+ seen += len(mms)
121
+ opened = {dst for _, dst, acc in mms if not _is_const(acc, True)}
122
+ for line, dst, acc in mms:
123
+ if dst in zeroed and not _is_const(acc, False):
124
+ findings.append(
125
+ f"{label}:{line} {func.name}: zeroed-psum: nc_matmul into nl.zeros PSUM "
126
+ f"tile {dst!r} with accumulate={ast.unparse(acc) if acc else None}"
127
+ )
128
+ if dst in psum and _is_const(acc, True) and dst not in opened:
129
+ findings.append(
130
+ f"{label}:{line} {func.name}: never-opened: nc_matmul accumulates into "
131
+ f"PSUM tile {dst!r} that no matmul opens with accumulate=False"
132
+ )
133
+ return findings, seen
134
+
135
+
136
+ def test_psum_groups_open_with_a_matmul_write():
137
+ findings, seen = [], 0
138
+ for path in sorted(NKI_DIR.glob("*.py")):
139
+ f, n = lint_source(path.read_text(), str(path.relative_to(NKI_DIR.parents[1])))
140
+ findings += f
141
+ seen += n
142
+ assert seen >= MIN_MATMULS, f"scan saw only {seen} nc_matmul calls; detector broken?"
143
+ assert not findings, "PSUM accumulation opened by a memset (trnsci/trnsci#185):\n" + (
144
+ "\n".join(findings)
145
+ )
146
+
147
+
148
+ _BAD = """
149
+ def k(a, b, K):
150
+ ps = nl.zeros((128, 512), dtype=nl.float32, buffer=nl.psum)
151
+ for k in nl.affine_range(K):
152
+ nisa.nc_matmul(dst=ps, stationary=a, moving=b, accumulate=True)
153
+ accs = [nl.zeros((128, 512), dtype=nl.float32, buffer=nl.psum) for _ in range(2)]
154
+ def inner():
155
+ nisa.nc_matmul(dst=accs[1][0:128], stationary=a, moving=b, accumulate=True)
156
+ pp = []
157
+ pp.append(nl.zeros((128, 512), dtype=nl.float32, buffer=nl.psum))
158
+ nisa.nc_matmul(dst=pp[0], stationary=a, moving=b)
159
+ q = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
160
+ nisa.nc_matmul(dst=q, stationary=a, moving=b, accumulate=True)
161
+ """
162
+
163
+ _GOOD = """
164
+ def k(a, b, K):
165
+ ps = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
166
+ nisa.nc_matmul(dst=ps, stationary=a, moving=b, accumulate=False)
167
+ for k in nl.affine_range(1, K):
168
+ nisa.nc_matmul(dst=ps, stationary=a, moving=b, accumulate=True)
169
+ qs = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
170
+ for k in range(K):
171
+ nisa.nc_matmul(dst=qs, stationary=a, moving=b, accumulate=(k > 0))
172
+ z = nl.zeros((128, 512), dtype=nl.float32, buffer=nl.psum)
173
+ nisa.nc_matmul(dst=z, stationary=a, moving=b, accumulate=False)
174
+ t = nl.ndarray((128, 128), dtype=nl.float32, buffer=nl.psum)
175
+ nisa.nc_matmul(dst=t, stationary=a, moving=b)
176
+ """
177
+
178
+
179
+ def test_lint_flags_the_bad_pattern():
180
+ findings, seen = lint_source(textwrap.dedent(_BAD))
181
+ assert seen == 4
182
+ kinds = sorted(f.split(": ")[1] for f in findings)
183
+ assert kinds == ["never-opened"] * 3 + ["zeroed-psum"] * 3, findings
184
+
185
+
186
+ def test_lint_accepts_the_fixed_forms():
187
+ findings, seen = lint_source(textwrap.dedent(_GOOD))
188
+ assert seen == 5 and not findings, findings
@@ -6,7 +6,7 @@ computing on Trainium. Complements trnblas (BLAS) and trnfft (FFT).
6
6
  Part of the trnsci scientific computing suite.
7
7
  """
8
8
 
9
- __version__ = "0.23.0"
9
+ __version__ = "0.24.0"
10
10
 
11
11
  # Block CG on matrix-free operators, low-rank preconditioner, SLQ log-det (#97)
12
12
  from .block import (