trnsparse 0.17.0__tar.gz → 0.18.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.
- {trnsparse-0.17.0 → trnsparse-0.18.0}/CHANGELOG.md +38 -0
- {trnsparse-0.17.0/trnsparse.egg-info → trnsparse-0.18.0}/PKG-INFO +1 -1
- {trnsparse-0.17.0 → trnsparse-0.18.0}/pyproject.toml +1 -1
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_segment_sim.py +17 -6
- trnsparse-0.18.0/tests/test_psum_accumulate_lint.py +318 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/__init__.py +1 -1
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/nki/kernels.py +118 -83
- {trnsparse-0.17.0 → trnsparse-0.18.0/trnsparse.egg-info}/PKG-INFO +1 -1
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse.egg-info/SOURCES.txt +1 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/.github/workflows/ci.yml +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/.github/workflows/notify-umbrella.yml +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/.github/workflows/publish.yml +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/.gitignore +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/.pre-commit-config.yaml +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/CLAUDE.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/CODE_OF_CONDUCT.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/CONTRIBUTING.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/LICENSE +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/README.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_bsr_spmm.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_cg_fused_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_iterative.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_kernel_matmul_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_multicore_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_multiproc_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_native_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_power_fused_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_screened_tiles_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_screening.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_spmm.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/bench_spmv.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/conftest.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/probe_kmv_entries_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/benchmarks/probe_scalare_sqrt_range_trn2.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/api.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/architecture.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/aws_setup.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/benchmarks.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/index.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/installation.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/iterative_solvers.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/migration_scipy.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/quickstart.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/docs/sparse_attention.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/examples/block_sparse_attention.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/examples/sparse_fock.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/infra/terraform/.terraform.lock.hcl +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/infra/terraform/README.md +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/infra/terraform/main.tf +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/mkdocs.yml +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/scripts/bench_eager_handle.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/scripts/bench_to_md.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/scripts/conformance_expect.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/scripts/run_benchmarks.sh +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/scripts/run_neuron_tests.sh +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/scripts/run_simulator_tests.sh +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/setup.cfg +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/conftest.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/fixtures/mlip_graph_tiny.pt +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_attention.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_attn_gather.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_bsr.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_cg_bsr_reduction.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_cg_span.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_conformance.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_core_split.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_device_known.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_examples.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_formats.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_iterative.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_kernel_dtype_guard.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_kernel_matmul.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_kernel_matmul_neuron.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_multicore.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_native_dispatch.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_attn.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_bsr.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_cg_fused.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_compile.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_kernel_matmul.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_native.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_screened_spmm.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_sim.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_spmm.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_nki_tail_audit.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_ops.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_screening.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_segment.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_segment_neuron.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/tests/test_trace_cache_safety.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/_reduce.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/formats.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/iterative.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/kernel_matmul.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/multicore.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/nki/__init__.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/nki/_native.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/nki/_native_attn.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/nki/dispatch.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/ops.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/screening.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse/segment.py +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse.egg-info/dependency_links.txt +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse.egg-info/requires.txt +0 -0
- {trnsparse-0.17.0 → trnsparse-0.18.0}/trnsparse.egg-info/top_level.txt +0 -0
|
@@ -7,6 +7,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.18.0] — 2026-11-28
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **PSUM accumulation groups now open with a matmul write
|
|
15
|
+
(trnsci/trnsci#185).** The kernels zeroed their fp32 PSUM accumulators
|
|
16
|
+
with `nl.zeros(..., buffer=nl.psum)` or a PSUM `memset` and then
|
|
17
|
+
accumulated with `nc_matmul(..., accumulate=True)`. The `nc_matmul`
|
|
18
|
+
documentation calls a matmul accumulating onto PSUM that a non-matmul
|
|
19
|
+
instruction initialised undefined behaviour on NeuronCore-v3 (Trn2): the
|
|
20
|
+
first matmul into a PSUM location must use `accumulate=False`. Device
|
|
21
|
+
results have matched references so far, but the pattern could break with a
|
|
22
|
+
compiler or runtime change. Now the first matmul of each group overwrites
|
|
23
|
+
(`accumulate=False`, or `accumulate=k > 0` over a Python `range`) in the
|
|
24
|
+
dense, BSR, screened and pre-transposed SpMM kernels, the screened-tile and
|
|
25
|
+
row-group kernels, and the gather and static attention kernels (forward and
|
|
26
|
+
backward). An accumulator is zeroed only when no matmul writes it (an
|
|
27
|
+
empty padded group). The fused CG / power-iteration matvec tiles hold many
|
|
28
|
+
groups (one per block row, interleaved, overlapping in the spread layout,
|
|
29
|
+
none for an empty row), so a matmul of bf16 zeros (one partition) now
|
|
30
|
+
zeroes each tile instead of the memset, one extra TensorE instruction per
|
|
31
|
+
matvec PSUM tile; the partition-sum dot products, one matmul each, now
|
|
32
|
+
overwrite instead. The GP kernel-matmul (`kernel_matmul`) tiles and
|
|
33
|
+
`segment_sum` already opened their groups with `accumulate=False` and are
|
|
34
|
+
unchanged. Simulator outputs are bitwise equal to the previous ones at
|
|
35
|
+
every simulator test shape. `tests/test_psum_accumulate_lint.py` fails on
|
|
36
|
+
the pattern.
|
|
37
|
+
|
|
38
|
+
- **`test_feature_chunks_bitwise` no longer depends on the CI host's CPU
|
|
39
|
+
(#146).** The simulator runs `nc_matmul` as `np.matmul`, and OpenBLAS
|
|
40
|
+
picks its sgemm kernel by CPU. On some kernels the fp32 sum order for a
|
|
41
|
+
column changes with the matrix width, so the unaligned 700-column chunks
|
|
42
|
+
(512 + 188-column matmuls) were not bitwise equal to one launch. The test
|
|
43
|
+
then failed on some runners only. The unaligned case now uses integer
|
|
44
|
+
messages, whose fp32 sums are exact in any order. The aligned case still
|
|
45
|
+
uses random messages, since its matmul shapes match one launch's. Library
|
|
46
|
+
code and hardware results are unchanged.
|
|
47
|
+
|
|
10
48
|
## [0.17.0] — 2026-11-25
|
|
11
49
|
|
|
12
50
|
Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.1, native TorchNeuron) — see trnsci/trnsci#35.
|
|
@@ -164,6 +164,13 @@ def test_feature_chunks_bitwise(monkeypatch):
|
|
|
164
164
|
# #141: a call above one launch's byte range splits F into chunks over the
|
|
165
165
|
# same plan. Forced here with a small budget: 2048 + 2048 + 1024 columns,
|
|
166
166
|
# and unaligned 700-column chunks, each bitwise equal to one launch.
|
|
167
|
+
#
|
|
168
|
+
# The simulator's nc_matmul is np.matmul. Its fp32 sum order for an output
|
|
169
|
+
# column depends on the moving width and on the OpenBLAS kernel the host
|
|
170
|
+
# CPU selects (#146). Aligned chunks run the same 512-column matmuls as one
|
|
171
|
+
# launch, so random messages are bitwise equal on any host. A 700-column
|
|
172
|
+
# chunk runs 512 + 188-column matmuls, so that case uses integer messages:
|
|
173
|
+
# their sums are exact in fp32, in any order.
|
|
167
174
|
from trnsparse import segment as seg
|
|
168
175
|
|
|
169
176
|
calls = _launches(monkeypatch)
|
|
@@ -173,22 +180,26 @@ def test_feature_chunks_bitwise(monkeypatch):
|
|
|
173
180
|
plan = trnsparse.segment_plan(idx, n)
|
|
174
181
|
m = torch.randn(e, F, generator=g)
|
|
175
182
|
h = torch.randn(n, F, generator=g)
|
|
183
|
+
mi = torch.randint(-64, 65, (e, F), generator=g).float()
|
|
176
184
|
one = (trnsparse.segment_sum(m, idx, n, plan=plan), trnsparse.gather(h, idx, plan=plan))
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
("
|
|
185
|
+
one_int = trnsparse.segment_sum(mi, idx, n, plan=plan)
|
|
186
|
+
assert len(calls) == 3
|
|
187
|
+
for patch, msg, ref in (
|
|
188
|
+
(("_SEG_MAX_BYTES", seg._launch_rows(e, n) * 4 * 3000), m, one[0]),
|
|
189
|
+
(("_feature_chunk", lambda e, n, f: 700), mi, one_int),
|
|
181
190
|
):
|
|
182
191
|
calls.clear()
|
|
183
192
|
with monkeypatch.context() as mp:
|
|
184
193
|
mp.setattr(seg, *patch)
|
|
185
194
|
split = (
|
|
186
|
-
trnsparse.segment_sum(
|
|
195
|
+
trnsparse.segment_sum(msg, idx, n, plan=plan),
|
|
187
196
|
trnsparse.gather(h, idx, plan=plan),
|
|
188
197
|
)
|
|
189
198
|
assert len(calls) == (6 if patch[0] == "_SEG_MAX_BYTES" else 16)
|
|
190
|
-
assert
|
|
199
|
+
assert torch.equal(split[0], ref)
|
|
200
|
+
assert torch.equal(split[1], one[1])
|
|
191
201
|
assert _rel(one[0], _ref(m, idx, n)) <= 1e-6
|
|
202
|
+
assert torch.equal(one_int.double(), _ref(mi, idx, n))
|
|
192
203
|
|
|
193
204
|
|
|
194
205
|
def test_padding_mask_plan(monkeypatch):
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Static check: no matmul accumulates onto PSUM that a non-matmul instruction zeroed.
|
|
2
|
+
|
|
3
|
+
The `nki.isa.nc_matmul` documentation: "On NeuronCore-v3, matmul accumulating
|
|
4
|
+
into a PSUM location that was value-initialized by a non-matmul instruction
|
|
5
|
+
(e.g., memset, tensor_copy) is not supported and is undefined behavior on
|
|
6
|
+
hardware." The first matmul into a PSUM location must use accumulate=False.
|
|
7
|
+
Trn2 is NeuronCore-v3. The kernels used to open accumulation groups with
|
|
8
|
+
`nl.zeros(..., buffer=nl.psum)` (or a PSUM memset) followed by
|
|
9
|
+
`nc_matmul(..., accumulate=True)`; see trnsci/trnsci#185.
|
|
10
|
+
|
|
11
|
+
This test parses every module (no `nki` needed) and fails on a
|
|
12
|
+
`nc_matmul(dst, ..., accumulate=True)` whose `dst` is, or is a view of, a
|
|
13
|
+
tile that an `nl.zeros` / `nl.full` / `nl.ones` PSUM allocation or a
|
|
14
|
+
`memset` of PSUM initialised in the same function. A tile reaches the check
|
|
15
|
+
through names: assignments, views (subscripts, `.reshape`, ...), list
|
|
16
|
+
comprehensions, and helper functions that return such a tile. Names follow
|
|
17
|
+
Python scoping (a nested helper sees its enclosing function's names), and
|
|
18
|
+
the check is flow-insensitive within a function: a name that holds a zeroed
|
|
19
|
+
PSUM tile anywhere in it must not be the target of a literal
|
|
20
|
+
`accumulate=True` anywhere in it. `accumulate=False`, or an expression such
|
|
21
|
+
as `accumulate=k > 0` whose first write overwrites, passes.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import ast
|
|
27
|
+
import textwrap
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
import pytest
|
|
31
|
+
|
|
32
|
+
PACKAGE = "trnsparse"
|
|
33
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
34
|
+
SOURCES = sorted(
|
|
35
|
+
p.relative_to(ROOT).as_posix()
|
|
36
|
+
for p in [*(ROOT / PACKAGE).rglob("*.py"), *(ROOT / "scripts").glob("*.py")]
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
_FILL = {"zeros", "ones", "full", "zeros_like", "ones_like", "full_like"}
|
|
40
|
+
_ALLOC = _FILL | {"ndarray", "empty_like"}
|
|
41
|
+
_VIEWS = {"reshape", "permute", "broadcast", "broadcast_to", "view", "ap", "bitcast"}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _attr(node) -> str | None:
|
|
45
|
+
if isinstance(node, ast.Attribute):
|
|
46
|
+
return node.attr
|
|
47
|
+
if isinstance(node, ast.Name):
|
|
48
|
+
return node.id
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _kw(call: ast.Call, name: str):
|
|
53
|
+
for k in call.keywords:
|
|
54
|
+
if k.arg == name:
|
|
55
|
+
return k.value
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _is_psum_alloc(node, fill_only: bool) -> bool:
|
|
60
|
+
if not isinstance(node, ast.Call) or _attr(node.func) not in (_FILL if fill_only else _ALLOC):
|
|
61
|
+
return False
|
|
62
|
+
buf = _kw(node, "buffer")
|
|
63
|
+
return _attr(buf) == "psum"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _bases(expr) -> set[str]:
|
|
67
|
+
"""Names whose tile `expr` is (or is a view of)."""
|
|
68
|
+
if isinstance(expr, ast.Name):
|
|
69
|
+
return {expr.id}
|
|
70
|
+
if isinstance(expr, (ast.Subscript, ast.Starred)):
|
|
71
|
+
return _bases(expr.value)
|
|
72
|
+
if (
|
|
73
|
+
isinstance(expr, ast.Call)
|
|
74
|
+
and isinstance(expr.func, ast.Attribute)
|
|
75
|
+
and expr.func.attr in _VIEWS
|
|
76
|
+
):
|
|
77
|
+
return _bases(expr.func.value)
|
|
78
|
+
if isinstance(expr, ast.IfExp):
|
|
79
|
+
return _bases(expr.body) | _bases(expr.orelse)
|
|
80
|
+
if isinstance(expr, (ast.List, ast.Tuple)):
|
|
81
|
+
return set().union(*(_bases(e) for e in expr.elts)) if expr.elts else set()
|
|
82
|
+
if isinstance(expr, (ast.ListComp, ast.GeneratorExp)):
|
|
83
|
+
return _bases(expr.elt)
|
|
84
|
+
return set()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _target_names(target) -> set[str]:
|
|
88
|
+
if isinstance(target, ast.Name):
|
|
89
|
+
return {target.id}
|
|
90
|
+
if isinstance(target, (ast.Subscript, ast.Attribute, ast.Starred)):
|
|
91
|
+
return _target_names(target.value)
|
|
92
|
+
if isinstance(target, (ast.Tuple, ast.List)):
|
|
93
|
+
return set().union(*(_target_names(e) for e in target.elts)) if target.elts else set()
|
|
94
|
+
return set()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _contains(expr, pred) -> bool:
|
|
98
|
+
return any(pred(n) for n in ast.walk(expr))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
_FUNCS = (ast.FunctionDef, ast.AsyncFunctionDef)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _own_nodes(fn):
|
|
105
|
+
"""Nodes of `fn`'s body outside nested function definitions."""
|
|
106
|
+
stack = [c for c in fn.body if not isinstance(c, _FUNCS)]
|
|
107
|
+
while stack:
|
|
108
|
+
node = stack.pop()
|
|
109
|
+
yield node
|
|
110
|
+
stack.extend(c for c in ast.iter_child_nodes(node) if not isinstance(c, _FUNCS))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _bindings(fn):
|
|
114
|
+
"""(target names, value) for every binding in `fn`'s own body."""
|
|
115
|
+
for node in _own_nodes(fn):
|
|
116
|
+
if isinstance(node, ast.Assign):
|
|
117
|
+
yield set().union(*(_target_names(t) for t in node.targets)), node.value
|
|
118
|
+
elif isinstance(node, (ast.AnnAssign, ast.AugAssign, ast.NamedExpr)):
|
|
119
|
+
if node.value is not None:
|
|
120
|
+
yield _target_names(node.target), node.value
|
|
121
|
+
elif isinstance(node, (ast.For, ast.comprehension)):
|
|
122
|
+
yield _target_names(node.target), node.iter
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _calls(fn, name):
|
|
126
|
+
for node in _own_nodes(fn):
|
|
127
|
+
if isinstance(node, ast.Call) and _attr(node.func) == name:
|
|
128
|
+
yield node
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _dst(call: ast.Call):
|
|
132
|
+
dst = _kw(call, "dst")
|
|
133
|
+
if dst is None and call.args:
|
|
134
|
+
dst = call.args[0]
|
|
135
|
+
return dst
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def find_violations(tree: ast.AST) -> list[int]:
|
|
139
|
+
"""Line numbers of literal accumulate=True matmuls onto zero-filled PSUM.
|
|
140
|
+
|
|
141
|
+
Names follow Python scoping: a name is local to the innermost function
|
|
142
|
+
that binds it, and a nested helper reads its enclosing function's names.
|
|
143
|
+
Helper functions returning a (zeroed) PSUM tile are matched by name.
|
|
144
|
+
"""
|
|
145
|
+
parent = {}
|
|
146
|
+
|
|
147
|
+
def visit(node, enclosing):
|
|
148
|
+
for child in ast.iter_child_nodes(node):
|
|
149
|
+
if isinstance(child, _FUNCS):
|
|
150
|
+
parent[child] = enclosing
|
|
151
|
+
visit(child, child)
|
|
152
|
+
else:
|
|
153
|
+
visit(child, enclosing)
|
|
154
|
+
|
|
155
|
+
visit(tree, None)
|
|
156
|
+
funcs = list(parent)
|
|
157
|
+
local = {}
|
|
158
|
+
for fn in funcs:
|
|
159
|
+
a = fn.args
|
|
160
|
+
names = {x.arg for x in [*a.posonlyargs, *a.args, *a.kwonlyargs]}
|
|
161
|
+
names |= {x.arg for x in (a.vararg, a.kwarg) if x is not None}
|
|
162
|
+
for node in _own_nodes(fn): # names the function binds (not x[i] = ...)
|
|
163
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
|
164
|
+
names.add(node.id)
|
|
165
|
+
names |= {c.name for c in parent if parent[c] is fn} # nested defs
|
|
166
|
+
local[fn] = names
|
|
167
|
+
|
|
168
|
+
def key(fn, name):
|
|
169
|
+
f = fn
|
|
170
|
+
while f is not None:
|
|
171
|
+
if name in local[f]:
|
|
172
|
+
return (id(f), name)
|
|
173
|
+
f = parent[f]
|
|
174
|
+
return (None, name)
|
|
175
|
+
|
|
176
|
+
psum: set = set() # (scope, name) keys holding PSUM tiles
|
|
177
|
+
zero: set = set() # ... holding PSUM tiles a non-matmul instruction zeroed
|
|
178
|
+
psum_fns: set[str] = set()
|
|
179
|
+
zero_fns: set[str] = set()
|
|
180
|
+
|
|
181
|
+
def keys(fn, expr):
|
|
182
|
+
return {key(fn, n) for n in _bases(expr)}
|
|
183
|
+
|
|
184
|
+
def source(fn, expr, tiles, fns, fill_only):
|
|
185
|
+
return _contains(
|
|
186
|
+
expr,
|
|
187
|
+
lambda n: (
|
|
188
|
+
_is_psum_alloc(n, fill_only) or (isinstance(n, ast.Call) and _attr(n.func) in fns)
|
|
189
|
+
),
|
|
190
|
+
) or bool(keys(fn, expr) & tiles)
|
|
191
|
+
|
|
192
|
+
changed = True
|
|
193
|
+
while changed:
|
|
194
|
+
changed = False
|
|
195
|
+
for fn in funcs:
|
|
196
|
+
for names, value in _bindings(fn):
|
|
197
|
+
bound = {key(fn, n) for n in names}
|
|
198
|
+
for tiles, fns, fill in ((psum, psum_fns, False), (zero, zero_fns, True)):
|
|
199
|
+
if bound - tiles and source(fn, value, tiles, fns, fill):
|
|
200
|
+
tiles |= bound
|
|
201
|
+
changed = True
|
|
202
|
+
for call in _calls(fn, "memset"):
|
|
203
|
+
hit = keys(fn, _dst(call)) & psum
|
|
204
|
+
if hit - zero:
|
|
205
|
+
zero |= hit
|
|
206
|
+
changed = True
|
|
207
|
+
for ret in _own_nodes(fn):
|
|
208
|
+
if not isinstance(ret, ast.Return) or ret.value is None:
|
|
209
|
+
continue
|
|
210
|
+
for tiles, fns, fill in ((psum, psum_fns, False), (zero, zero_fns, True)):
|
|
211
|
+
if fn.name not in fns and source(fn, ret.value, tiles, fns, fill):
|
|
212
|
+
fns.add(fn.name)
|
|
213
|
+
changed = True
|
|
214
|
+
lines = []
|
|
215
|
+
for fn in funcs:
|
|
216
|
+
for call in _calls(fn, "nc_matmul"):
|
|
217
|
+
acc = _kw(call, "accumulate")
|
|
218
|
+
if isinstance(acc, ast.Constant) and acc.value is True and keys(fn, _dst(call)) & zero:
|
|
219
|
+
lines.append(call.lineno)
|
|
220
|
+
return sorted(set(lines))
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
@pytest.mark.parametrize("path", SOURCES)
|
|
224
|
+
def test_no_matmul_accumulates_onto_zero_filled_psum(path):
|
|
225
|
+
tree = ast.parse((ROOT / path).read_text(), filename=path)
|
|
226
|
+
bad = find_violations(tree)
|
|
227
|
+
assert not bad, (
|
|
228
|
+
f"{path}: nc_matmul(accumulate=True) onto PSUM zeroed by nl.zeros/memset at lines "
|
|
229
|
+
f"{bad}; open the accumulation group with accumulate=False (trnsci/trnsci#185)"
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
_BAD = {
|
|
234
|
+
"zeros_then_accumulate": """
|
|
235
|
+
def k(a, b):
|
|
236
|
+
psum = nl.zeros((128, 512), dtype=nl.float32, buffer=nl.psum)
|
|
237
|
+
for t in nl.affine_range(4):
|
|
238
|
+
nisa.nc_matmul(dst=psum, stationary=a, moving=b, accumulate=True)
|
|
239
|
+
""",
|
|
240
|
+
"zeros_view": """
|
|
241
|
+
def k(a, b):
|
|
242
|
+
y = nl.zeros((128, 4, 2, 64), dtype=nl.float32, buffer=nl.psum)
|
|
243
|
+
for q in range(4):
|
|
244
|
+
yq = y[:, q, :, :].reshape((128, 128))
|
|
245
|
+
nisa.nc_matmul(dst=yq, stationary=a, moving=b, accumulate=True)
|
|
246
|
+
""",
|
|
247
|
+
"zeros_list": """
|
|
248
|
+
def k(a, b, rows):
|
|
249
|
+
ps = [nl.zeros((128, 512), dtype=nl.float32, buffer=nl.psum) for _ in rows]
|
|
250
|
+
nisa.nc_matmul(ps[0], a, b, accumulate=True)
|
|
251
|
+
""",
|
|
252
|
+
"module_helper": """
|
|
253
|
+
def acc(shape):
|
|
254
|
+
return nl.zeros(shape, dtype=nl.float32, buffer=nl.psum)
|
|
255
|
+
|
|
256
|
+
def k(a, b):
|
|
257
|
+
ps = acc((128, 512))
|
|
258
|
+
nisa.nc_matmul(ps, a, b, accumulate=True)
|
|
259
|
+
""",
|
|
260
|
+
"memset_helper": """
|
|
261
|
+
def k(a, b):
|
|
262
|
+
pss = {}
|
|
263
|
+
pss["mv"] = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
|
|
264
|
+
|
|
265
|
+
def psum_zeros(width):
|
|
266
|
+
t = pss["mv"]
|
|
267
|
+
v = t[:, 0:width]
|
|
268
|
+
nisa.memset(v, 0.0)
|
|
269
|
+
return v
|
|
270
|
+
|
|
271
|
+
ps = psum_zeros(64)
|
|
272
|
+
nisa.nc_matmul(ps[:, 0:1], a, b, accumulate=True)
|
|
273
|
+
""",
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
_GOOD = {
|
|
277
|
+
"first_write_opens": """
|
|
278
|
+
def k(a, b):
|
|
279
|
+
psum = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
|
|
280
|
+
for t in range(4):
|
|
281
|
+
nisa.nc_matmul(dst=psum, stationary=a, moving=b, accumulate=t > 0)
|
|
282
|
+
""",
|
|
283
|
+
"zeros_only_when_no_matmul": """
|
|
284
|
+
def acc(shape, n):
|
|
285
|
+
if n == 0:
|
|
286
|
+
return nl.zeros(shape, dtype=nl.float32, buffer=nl.psum)
|
|
287
|
+
return nl.ndarray(shape, dtype=nl.float32, buffer=nl.psum)
|
|
288
|
+
|
|
289
|
+
def k(a, b, n):
|
|
290
|
+
psum = acc((128, 512), n)
|
|
291
|
+
for t in range(n):
|
|
292
|
+
nisa.nc_matmul(psum, a, b, accumulate=t > 0)
|
|
293
|
+
""",
|
|
294
|
+
"matmul_opener": """
|
|
295
|
+
def k(a, b, z):
|
|
296
|
+
v = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
|
|
297
|
+
nisa.nc_matmul(v, z, z, accumulate=False)
|
|
298
|
+
nisa.nc_matmul(v, a, b, accumulate=True)
|
|
299
|
+
""",
|
|
300
|
+
"sbuf_memset": """
|
|
301
|
+
def k(a, b):
|
|
302
|
+
sb = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.sbuf)
|
|
303
|
+
nisa.memset(sb, 0.0)
|
|
304
|
+
ps = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
|
|
305
|
+
nisa.nc_matmul(ps, a, b, accumulate=False)
|
|
306
|
+
nisa.nc_matmul(ps, a, b, accumulate=True)
|
|
307
|
+
""",
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
@pytest.mark.parametrize("name", sorted(_BAD))
|
|
312
|
+
def test_lint_flags_the_pattern(name):
|
|
313
|
+
assert find_violations(ast.parse(textwrap.dedent(_BAD[name])))
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
@pytest.mark.parametrize("name", sorted(_GOOD))
|
|
317
|
+
def test_lint_passes_matmul_opened_groups(name):
|
|
318
|
+
assert not find_violations(ast.parse(textwrap.dedent(_GOOD[name])))
|
|
@@ -5,7 +5,7 @@ CSR/COO formats, SpMV, SpMM, and integral screening for
|
|
|
5
5
|
sparse scientific computing. Part of the trnsci scientific computing suite.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
__version__ = "0.
|
|
8
|
+
__version__ = "0.18.0"
|
|
9
9
|
|
|
10
10
|
from .formats import BSRMatrix, COOMatrix, CSRMatrix, eye_sparse, from_dense, from_scipy
|
|
11
11
|
from .iterative import (
|