trnsparse 0.11.0__tar.gz → 0.12.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.11.0 → trnsparse-0.12.0}/CHANGELOG.md +35 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/PKG-INFO +1 -1
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/architecture.md +5 -1
- {trnsparse-0.11.0 → trnsparse-0.12.0}/pyproject.toml +1 -1
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_native_dispatch.py +165 -6
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_native.py +41 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_tail_audit.py +45 -8
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/__init__.py +1 -1
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/nki/_native_attn.py +11 -7
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/nki/dispatch.py +52 -8
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/ops.py +20 -12
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse.egg-info/PKG-INFO +1 -1
- {trnsparse-0.11.0 → trnsparse-0.12.0}/.github/workflows/ci.yml +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/.github/workflows/notify-umbrella.yml +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/.github/workflows/publish.yml +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/.gitignore +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/.pre-commit-config.yaml +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/CLAUDE.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/CODE_OF_CONDUCT.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/CONTRIBUTING.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/LICENSE +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/README.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_bsr_spmm.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_cg_fused_trn2.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_iterative.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_multicore_trn2.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_multiproc_trn2.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_native_trn2.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_power_fused_trn2.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_screening.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_spmm.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/bench_spmv.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/benchmarks/conftest.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/api.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/aws_setup.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/benchmarks.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/index.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/installation.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/iterative_solvers.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/migration_scipy.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/quickstart.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/docs/sparse_attention.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/examples/block_sparse_attention.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/examples/sparse_fock.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/infra/terraform/.terraform.lock.hcl +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/infra/terraform/README.md +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/infra/terraform/main.tf +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/mkdocs.yml +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/scripts/bench_to_md.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/scripts/run_benchmarks.sh +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/scripts/run_neuron_tests.sh +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/scripts/run_simulator_tests.sh +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/setup.cfg +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/conftest.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_attention.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_attn_gather.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_bsr.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_core_split.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_examples.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_formats.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_iterative.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_multicore.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_attn.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_bsr.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_cg_fused.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_compile.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_screened_spmm.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_sim.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_nki_spmm.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_ops.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/tests/test_screening.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/formats.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/iterative.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/multicore.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/nki/__init__.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/nki/_native.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/nki/kernels.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse/screening.py +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse.egg-info/SOURCES.txt +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse.egg-info/dependency_links.txt +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse.egg-info/requires.txt +0 -0
- {trnsparse-0.11.0 → trnsparse-0.12.0}/trnsparse.egg-info/top_level.txt +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.12.0] — 2026-11-01
|
|
11
|
+
|
|
12
|
+
Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
|
|
13
|
+
|
|
14
|
+
Headline: **correctness fix — upgrade recommended if you pass `scale` to block-sparse attention.** In 0.6.0–0.11.0 a custom `scale` passed to `block_sparse_attention_tiled` was silently ignored on the NKI paths (forward and dQ/dK/dV; 29–99% relative error at scale 0.1–2.0). The native `trnsparse::bsr_attn` op was affected from 0.9.0. The PyTorch backend and `ShardedAttention` were correct, and the default `scale=None` was unaffected (#50, #47). Also: BSR block sizes other than 128 go straight to the torch path instead of paying a failed NKI compile on every call (7–41 s first call, 6.7–8.3× steady), which covers `bsr_spmm`, attention and the iterative solvers (#48, #46).
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- **`block_sparse_attention_tiled` silently ignored a custom `scale` on the
|
|
19
|
+
NKI paths** (released 0.6.0 through 0.11.0; #47). With `backend="nki"` or
|
|
20
|
+
`"auto"` on Neuron, the forward and all three gradients always used
|
|
21
|
+
`head_dim ** -0.5`, and no error was raised. On Trn2 (seq 384, head_dim 64,
|
|
22
|
+
relative error against dense fp64 attention) the forward was off by 29%
|
|
23
|
+
(`scale=0.1`), 93% (`1.0`) and 95% (`2.0`), and dQ / dK by up to 99%. The
|
|
24
|
+
XLA / simulator path (`_AttnTiledFunction` and the no-grad call) was
|
|
25
|
+
affected from 0.6.0, and the native TorchNeuron `trnsparse::bsr_attn` op
|
|
26
|
+
from 0.9.0. The PyTorch backend was always correct. `scale` now reaches
|
|
27
|
+
`nki_bsr_attn_tiled`, `nki_bsr_attn_bwd` and the `bsr_attn` /
|
|
28
|
+
`bsr_attn_bwd` ops, each of which takes a new optional `scale` argument
|
|
29
|
+
(default `head_dim ** -0.5`). The kernels are unchanged: they already take
|
|
30
|
+
`Q * scale`, and the static backward takes `scale` as a kernel argument.
|
|
31
|
+
With the default `scale=None`, outputs and gradients are bit-identical to
|
|
32
|
+
0.11.0 on Trn2. `ShardedAttention.shard_rows(Q, scale)` was not affected.
|
|
33
|
+
- `bsr_spmm` and `block_sparse_attention_tiled` with a `block_size` other than
|
|
34
|
+
128 (16, 32 and 64 in the audit) no longer try an NKI kernel first. The
|
|
35
|
+
kernels take 128x128 blocks only, so that trace always failed, and the call
|
|
36
|
+
fell back to torch only after paying for it: 7-9 s on the first `bsr_spmm`
|
|
37
|
+
call and 27-41 s on the first attention call on Trn2. These block sizes now
|
|
38
|
+
go straight to the PyTorch path under `auto` (and under `nki` when
|
|
39
|
+
`TRNSPARSE_REQUIRE_NKI` is not set). Under `TRNSPARSE_REQUIRE_NKI` they raise
|
|
40
|
+
`NotImplementedError` naming the supported block size. The unfused
|
|
41
|
+
iterative solvers (`cg_bsr`, `power_iteration_bsr`, `chebyshev_bsr`,
|
|
42
|
+
`richardson_bsr`) also benefit, because they call `bsr_spmm` on every
|
|
43
|
+
iteration (#46).
|
|
44
|
+
|
|
10
45
|
## [0.11.0] — 2026-11-01
|
|
11
46
|
|
|
12
47
|
Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.
|
|
@@ -121,7 +121,11 @@ operands run in fp32.
|
|
|
121
121
|
interop with scipy/PyTorch, and SpMV.
|
|
122
122
|
- **COO**: three parallel 1-D tensors. Preferred for construction and permutation.
|
|
123
123
|
- **BSR** (`block_size=128`): stacked 128×128 blocks + block-level CSR pattern.
|
|
124
|
-
Every block maps to one `nc_matmul`; zero gather overhead.
|
|
124
|
+
Every block maps to one `nc_matmul`; zero gather overhead. Other block
|
|
125
|
+
sizes work everywhere on the PyTorch path. The NKI kernels take 128 only, so
|
|
126
|
+
`bsr_spmm` and `block_sparse_attention_tiled` send any other block size
|
|
127
|
+
straight to PyTorch, or raise `NotImplementedError` under
|
|
128
|
+
`TRNSPARSE_REQUIRE_NKI=1`.
|
|
125
129
|
|
|
126
130
|
All three support `from_dense`, `to_dense`, and interconversion.
|
|
127
131
|
|
|
@@ -912,6 +912,26 @@ class TestNativePathOnCpu:
|
|
|
912
912
|
for g_, w_ in zip(got, want, strict=True):
|
|
913
913
|
torch.testing.assert_close(g_, w_, atol=1e-4, rtol=1e-4)
|
|
914
914
|
|
|
915
|
+
@pytest.mark.parametrize("scale", [0.1, 1.0, 2.0])
|
|
916
|
+
def test_attention_static_custom_scale(self, cpu_native, scale):
|
|
917
|
+
"""trnsparse#47: the static kernels see Q * scale and the dQ scale."""
|
|
918
|
+
from trnsparse.ops import _block_sparse_attn_backward, _block_sparse_attn_pytorch
|
|
919
|
+
|
|
920
|
+
torch.manual_seed(15)
|
|
921
|
+
seq_len, hd = 3 * P, 64
|
|
922
|
+
pattern = torch.tril(torch.ones(3, 3)).repeat_interleave(P, 0).repeat_interleave(P, 1)
|
|
923
|
+
mask = trnsparse.BSRMatrix.from_dense(pattern, block_size=P)
|
|
924
|
+
Q, K, V, dO = (torch.randn(seq_len, hd) for _ in range(4))
|
|
925
|
+
out, rm, rd = dispatch.nki_bsr_attn_tiled(Q, K, V, mask, return_stats=True, scale=scale)
|
|
926
|
+
ref, rm_ref, rd_ref = _block_sparse_attn_pytorch(Q, K, V, mask, scale, return_stats=True)
|
|
927
|
+
torch.testing.assert_close(out, ref, atol=1e-4, rtol=1e-4)
|
|
928
|
+
got = dispatch.nki_bsr_attn_bwd(Q, K, V, dO, out, mask, rm, rd, scale=scale)
|
|
929
|
+
want = _block_sparse_attn_backward(
|
|
930
|
+
Q, K, V, ref, dO, mask, scale, row_max=rm_ref, row_denom=rd_ref
|
|
931
|
+
)
|
|
932
|
+
for g_, w_ in zip(got, want, strict=True):
|
|
933
|
+
torch.testing.assert_close(g_, w_, atol=1e-4, rtol=1e-4)
|
|
934
|
+
|
|
915
935
|
def test_static_kernels_bf16_operand_contract(self, cpu_native, monkeypatch):
|
|
916
936
|
"""bf16 inputs reach the static kernels as bf16 operands; statistics stay fp32."""
|
|
917
937
|
seen = {}
|
|
@@ -1004,14 +1024,14 @@ class TestNativeAttentionOps:
|
|
|
1004
1024
|
from trnsparse.nki import _native_attn # registers once per process
|
|
1005
1025
|
from trnsparse.ops import _block_sparse_attn_backward, _block_sparse_attn_pytorch
|
|
1006
1026
|
|
|
1007
|
-
def fwd(Q, K, V, mask, return_stats=False):
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
)
|
|
1027
|
+
def fwd(Q, K, V, mask, return_stats=False, scale=None):
|
|
1028
|
+
scale = Q.shape[1] ** -0.5 if scale is None else scale
|
|
1029
|
+
return _block_sparse_attn_pytorch(Q, K, V, mask, scale, return_stats=return_stats)
|
|
1011
1030
|
|
|
1012
|
-
def bwd(Q, K, V, dO, O, mask, row_max, row_denom):
|
|
1031
|
+
def bwd(Q, K, V, dO, O, mask, row_max, row_denom, scale=None):
|
|
1032
|
+
scale = Q.shape[1] ** -0.5 if scale is None else scale
|
|
1013
1033
|
return _block_sparse_attn_backward(
|
|
1014
|
-
Q, K, V, O, dO, mask,
|
|
1034
|
+
Q, K, V, O, dO, mask, scale, row_max=row_max, row_denom=row_denom
|
|
1015
1035
|
)
|
|
1016
1036
|
|
|
1017
1037
|
monkeypatch.setattr(dispatch, "nki_bsr_attn_tiled", fwd)
|
|
@@ -1051,6 +1071,34 @@ class TestNativeAttentionOps:
|
|
|
1051
1071
|
for got, exp in ((Q.grad, Qr.grad), (K.grad, Kr.grad), (V.grad, Vr.grad)):
|
|
1052
1072
|
torch.testing.assert_close(got, exp)
|
|
1053
1073
|
|
|
1074
|
+
@pytest.mark.parametrize("scale", [0.1, 1.0, 2.0])
|
|
1075
|
+
def test_custom_scale_reaches_op_and_backward(self, attn, scale, monkeypatch):
|
|
1076
|
+
"""trnsparse#47: a non-default scale reaches bsr_attn and bsr_attn_bwd."""
|
|
1077
|
+
torch.manual_seed(14)
|
|
1078
|
+
seq_len, hd = 3 * P, 32
|
|
1079
|
+
mask = self._mask(seq_len)
|
|
1080
|
+
Q, K, V = (torch.randn(seq_len, hd, requires_grad=True) for _ in range(3))
|
|
1081
|
+
Qr, Kr, Vr = (t.detach().clone().requires_grad_(True) for t in (Q, K, V))
|
|
1082
|
+
prev = trnsparse.get_backend()
|
|
1083
|
+
trnsparse.set_backend("pytorch")
|
|
1084
|
+
try:
|
|
1085
|
+
ref = trnsparse.block_sparse_attention_tiled(Qr, Kr, Vr, mask, scale=scale)
|
|
1086
|
+
finally:
|
|
1087
|
+
trnsparse.set_backend(prev)
|
|
1088
|
+
|
|
1089
|
+
monkeypatch.setattr(dispatch, "HAS_NKI", True)
|
|
1090
|
+
monkeypatch.setattr(dispatch, "_USE_SIMULATOR", False)
|
|
1091
|
+
monkeypatch.setattr(dispatch, "_backend", "nki")
|
|
1092
|
+
monkeypatch.setattr(dispatch, "_dispatch_path", "native")
|
|
1093
|
+
monkeypatch.setattr(dispatch, "_native_ops", {"bsr_attn": torch.ops.trnsparse.bsr_attn})
|
|
1094
|
+
out = trnsparse.block_sparse_attention_tiled(Q, K, V, mask, scale=scale)
|
|
1095
|
+
g = torch.randn_like(out)
|
|
1096
|
+
out.backward(g)
|
|
1097
|
+
ref.backward(g)
|
|
1098
|
+
torch.testing.assert_close(out, ref)
|
|
1099
|
+
for got, exp in ((Q.grad, Qr.grad), (K.grad, Kr.grad), (V.grad, Vr.grad)):
|
|
1100
|
+
torch.testing.assert_close(got, exp)
|
|
1101
|
+
|
|
1054
1102
|
def test_fake_shapes(self, attn):
|
|
1055
1103
|
m = torch.empty(2 * P, 64, device="meta")
|
|
1056
1104
|
idx = torch.zeros(3, dtype=torch.long, device="meta")
|
|
@@ -1076,3 +1124,114 @@ class TestNativeAttentionOps:
|
|
|
1076
1124
|
assert len(calls) == 1
|
|
1077
1125
|
# Mask structure is passed as host tensors.
|
|
1078
1126
|
assert calls[0][3].device.type == "cpu" and calls[0][4].device.type == "cpu"
|
|
1127
|
+
|
|
1128
|
+
|
|
1129
|
+
class TestUnsupportedBlockSize:
|
|
1130
|
+
"""#46: the BSR and attention kernels take 128x128 blocks only. Other
|
|
1131
|
+
block sizes go straight to the PyTorch path (no kernel trace, which
|
|
1132
|
+
used to fail and cost seconds per call) or, under TRNSPARSE_REQUIRE_NKI,
|
|
1133
|
+
raise NotImplementedError naming the supported size."""
|
|
1134
|
+
|
|
1135
|
+
@pytest.fixture(params=["native", "xla"])
|
|
1136
|
+
def no_kernels(self, request, monkeypatch):
|
|
1137
|
+
# The wrappers catch kernel errors and fall back, so record any
|
|
1138
|
+
# launch attempt and check the record, not only the exception.
|
|
1139
|
+
attempts = []
|
|
1140
|
+
|
|
1141
|
+
def boom(*a, **k):
|
|
1142
|
+
attempts.append(a)
|
|
1143
|
+
raise AssertionError("no kernel may be traced for an unsupported block size")
|
|
1144
|
+
|
|
1145
|
+
monkeypatch.setattr(dispatch, "HAS_NKI", True)
|
|
1146
|
+
monkeypatch.setattr(dispatch, "_USE_SIMULATOR", False)
|
|
1147
|
+
monkeypatch.setattr(dispatch, "_REQUIRE_NKI", False)
|
|
1148
|
+
monkeypatch.setattr(dispatch, "_backend", "nki")
|
|
1149
|
+
monkeypatch.setattr(dispatch, "_dispatch_path", request.param)
|
|
1150
|
+
monkeypatch.setattr(dispatch, "_get_native_ops", boom)
|
|
1151
|
+
monkeypatch.setattr(dispatch, "_launch", boom)
|
|
1152
|
+
monkeypatch.setattr(dispatch, "_run", boom)
|
|
1153
|
+
monkeypatch.setattr(dispatch, "_to_device", boom)
|
|
1154
|
+
monkeypatch.setattr(dispatch._BSRSpMMFunction, "apply", boom)
|
|
1155
|
+
yield
|
|
1156
|
+
assert attempts == [], f"{len(attempts)} kernel launch attempt(s)"
|
|
1157
|
+
|
|
1158
|
+
@staticmethod
|
|
1159
|
+
def _bsr(m, n, b, seed=0):
|
|
1160
|
+
g = torch.Generator().manual_seed(seed)
|
|
1161
|
+
bm = torch.rand(-(-m // b), -(-n // b), generator=g) < 0.5
|
|
1162
|
+
bm[-1, -1] = True
|
|
1163
|
+
mask = bm.repeat_interleave(b, 0).repeat_interleave(b, 1)[:m, :n]
|
|
1164
|
+
dense = torch.randn(m, n, generator=g) * mask
|
|
1165
|
+
return dense, trnsparse.BSRMatrix.from_dense(dense, block_size=b)
|
|
1166
|
+
|
|
1167
|
+
@pytest.mark.parametrize("b", [16, 32, 64])
|
|
1168
|
+
def test_bsr_spmm_goes_to_torch(self, no_kernels, b):
|
|
1169
|
+
dense, A = self._bsr(200, 136, b)
|
|
1170
|
+
A.blocks.requires_grad_(True)
|
|
1171
|
+
B = torch.randn(136, 7, requires_grad=True)
|
|
1172
|
+
C = trnsparse.bsr_spmm(A, B)
|
|
1173
|
+
torch.testing.assert_close(C, dense @ B.detach(), atol=1e-4, rtol=1e-4)
|
|
1174
|
+
C.sum().backward()
|
|
1175
|
+
assert A.blocks.grad is not None and B.grad is not None
|
|
1176
|
+
# The dispatch-level entry point is guarded as well.
|
|
1177
|
+
torch.testing.assert_close(dispatch.nki_bsr_spmm(A, B.detach()), C.detach())
|
|
1178
|
+
|
|
1179
|
+
@pytest.mark.parametrize("b", [16, 32, 64])
|
|
1180
|
+
def test_bsr_spmm_require_nki_raises(self, no_kernels, monkeypatch, b):
|
|
1181
|
+
monkeypatch.setattr(dispatch, "_REQUIRE_NKI", True)
|
|
1182
|
+
_, A = self._bsr(64, 64, b)
|
|
1183
|
+
with pytest.raises(NotImplementedError, match=r"block_size 128 only, got " + str(b)):
|
|
1184
|
+
trnsparse.bsr_spmm(A, torch.randn(64, 3))
|
|
1185
|
+
with pytest.raises(NotImplementedError, match="block_size 128"):
|
|
1186
|
+
dispatch.nki_bsr_spmm(A, torch.randn(64, 3))
|
|
1187
|
+
|
|
1188
|
+
def test_pytorch_backend_never_raises(self, no_kernels, monkeypatch):
|
|
1189
|
+
monkeypatch.setattr(dispatch, "_REQUIRE_NKI", True)
|
|
1190
|
+
monkeypatch.setattr(dispatch, "_backend", "pytorch")
|
|
1191
|
+
dense, A = self._bsr(64, 64, 32)
|
|
1192
|
+
B = torch.randn(64, 3)
|
|
1193
|
+
torch.testing.assert_close(trnsparse.bsr_spmm(A, B), dense @ B, atol=1e-4, rtol=1e-4)
|
|
1194
|
+
|
|
1195
|
+
def test_cg_bsr_block32_goes_to_torch(self, no_kernels):
|
|
1196
|
+
n = 96
|
|
1197
|
+
g = torch.Generator().manual_seed(3)
|
|
1198
|
+
M = torch.randn(n, n, generator=g) * 0.05
|
|
1199
|
+
A = (M + M.T) / 2 + 2.0 * torch.eye(n)
|
|
1200
|
+
b = torch.randn(n, generator=g)
|
|
1201
|
+
x, iters = trnsparse.cg_bsr(trnsparse.BSRMatrix.from_dense(A, block_size=32), b)[:2]
|
|
1202
|
+
torch.testing.assert_close(A @ x, b, atol=1e-4, rtol=1e-4)
|
|
1203
|
+
|
|
1204
|
+
@staticmethod
|
|
1205
|
+
def _attn(seq, b, seed=5):
|
|
1206
|
+
g = torch.Generator().manual_seed(seed)
|
|
1207
|
+
nb = seq // b
|
|
1208
|
+
bm = (torch.rand(nb, nb, generator=g) < 0.4) | torch.eye(nb, dtype=torch.bool)
|
|
1209
|
+
dense = bm.repeat_interleave(b, 0).repeat_interleave(b, 1).float()
|
|
1210
|
+
return trnsparse.BSRMatrix.from_dense(dense, block_size=b)
|
|
1211
|
+
|
|
1212
|
+
@pytest.mark.parametrize("b", [32, 64])
|
|
1213
|
+
def test_attention_goes_to_torch(self, no_kernels, b):
|
|
1214
|
+
from trnsparse.ops import _block_sparse_attn_pytorch
|
|
1215
|
+
|
|
1216
|
+
mask = self._attn(256, b)
|
|
1217
|
+
g = torch.Generator().manual_seed(6)
|
|
1218
|
+
Q, K, V = (torch.randn(256, 16, generator=g) for _ in range(3))
|
|
1219
|
+
ref = _block_sparse_attn_pytorch(Q, K, V, mask, 16**-0.5)
|
|
1220
|
+
torch.testing.assert_close(trnsparse.block_sparse_attention_tiled(Q, K, V, mask), ref)
|
|
1221
|
+
Qg, Kg, Vg = (t.clone().requires_grad_(True) for t in (Q, K, V))
|
|
1222
|
+
out = trnsparse.block_sparse_attention_tiled(Qg, Kg, Vg, mask)
|
|
1223
|
+
torch.testing.assert_close(out, ref)
|
|
1224
|
+
out.sum().backward()
|
|
1225
|
+
assert all(t.grad is not None for t in (Qg, Kg, Vg))
|
|
1226
|
+
# Dispatch-level entry points (what the native composite ops call).
|
|
1227
|
+
o, rm, rd = dispatch.nki_bsr_attn_tiled(Q, K, V, mask, return_stats=True)
|
|
1228
|
+
torch.testing.assert_close(o, ref)
|
|
1229
|
+
dQ, dK, dV = dispatch.nki_bsr_attn_bwd(Q, K, V, torch.ones_like(Q), o, mask, rm, rd)
|
|
1230
|
+
torch.testing.assert_close(dQ, Qg.grad, atol=1e-5, rtol=1e-4)
|
|
1231
|
+
|
|
1232
|
+
def test_attention_require_nki_raises(self, no_kernels, monkeypatch):
|
|
1233
|
+
monkeypatch.setattr(dispatch, "_REQUIRE_NKI", True)
|
|
1234
|
+
mask = self._attn(256, 64)
|
|
1235
|
+
Q = torch.randn(256, 16)
|
|
1236
|
+
with pytest.raises(NotImplementedError, match="block_size 128 only, got 64"):
|
|
1237
|
+
trnsparse.block_sparse_attention_tiled(Q, Q, Q, mask)
|
|
@@ -329,6 +329,47 @@ class TestTwoCoreAndBf16:
|
|
|
329
329
|
assert got.dtype == dtype
|
|
330
330
|
assert _rel(got, exp) < tol
|
|
331
331
|
|
|
332
|
+
# fp32 gradients at scale 2.0 measure ~1.2e-5 against fp64 on Trn2.
|
|
333
|
+
@pytest.mark.parametrize("dtype,tol", [(torch.float32, 1e-5), (torch.bfloat16, 3e-2)])
|
|
334
|
+
@pytest.mark.parametrize("scale", [0.1, 1.0, 2.0])
|
|
335
|
+
def test_attention_custom_scale(self, scale, dtype, tol):
|
|
336
|
+
"""trnsparse#47: a non-default scale reaches the forward and backward kernels.
|
|
337
|
+
|
|
338
|
+
Same shape for every scale in one process, so a trace cache keyed
|
|
339
|
+
without the scale would reuse the first trace and fail the later ones.
|
|
340
|
+
"""
|
|
341
|
+
g = torch.Generator().manual_seed(16)
|
|
342
|
+
seq_len, hd = 3 * P, 64
|
|
343
|
+
mask = _block_causal_mask(seq_len)
|
|
344
|
+
Q, K, V, dO = (torch.randn(seq_len, hd, generator=g).to(dtype) for _ in range(4))
|
|
345
|
+
q64, k64, v64, do64 = (t.double().requires_grad_(True) for t in (Q, K, V, dO))
|
|
346
|
+
allowed = mask.to_dense().bool()
|
|
347
|
+
s = (q64 @ k64.T * scale).masked_fill(~allowed, float("-inf"))
|
|
348
|
+
ref = torch.softmax(s, dim=-1) @ v64
|
|
349
|
+
ref.backward(do64.detach())
|
|
350
|
+
|
|
351
|
+
Qd, Kd, Vd = (t.to(DEV).requires_grad_(True) for t in (Q, K, V))
|
|
352
|
+
out = trnsparse.block_sparse_attention_tiled(Qd, Kd, Vd, mask, scale=scale)
|
|
353
|
+
assert _rel(out, ref.detach()) < tol
|
|
354
|
+
out.backward(dO.to(DEV))
|
|
355
|
+
for got, exp in ((Qd.grad, q64.grad), (Kd.grad, k64.grad), (Vd.grad, v64.grad)):
|
|
356
|
+
assert _rel(got, exp) < 5 * tol
|
|
357
|
+
with torch.no_grad():
|
|
358
|
+
out2 = trnsparse.block_sparse_attention_tiled(
|
|
359
|
+
Q.to(DEV), K.to(DEV), V.to(DEV), mask, scale=scale
|
|
360
|
+
)
|
|
361
|
+
assert _rel(out2, ref.detach()) < tol
|
|
362
|
+
|
|
363
|
+
def test_attention_default_scale_unchanged(self):
|
|
364
|
+
"""scale=None and scale=head_dim**-0.5 give bit-identical results."""
|
|
365
|
+
g = torch.Generator().manual_seed(17)
|
|
366
|
+
seq_len, hd = 3 * P, 64
|
|
367
|
+
mask = _block_causal_mask(seq_len)
|
|
368
|
+
Q, K, V = (torch.randn(seq_len, hd, generator=g).to(DEV) for _ in range(3))
|
|
369
|
+
a = trnsparse.block_sparse_attention_tiled(Q, K, V, mask)
|
|
370
|
+
b = trnsparse.block_sparse_attention_tiled(Q, K, V, mask, scale=hd**-0.5)
|
|
371
|
+
assert torch.equal(a.cpu(), b.cpu())
|
|
372
|
+
|
|
332
373
|
def test_attention_bf16_stats_are_fp32(self):
|
|
333
374
|
seq_len, hd = 2 * P, 64
|
|
334
375
|
mask = _block_causal_mask(seq_len)
|
|
@@ -15,6 +15,8 @@ as OK, SILENT (wrong result) or LOUD (exception) instead of asserting.
|
|
|
15
15
|
|
|
16
16
|
from __future__ import annotations
|
|
17
17
|
|
|
18
|
+
import itertools
|
|
19
|
+
|
|
18
20
|
import pytest
|
|
19
21
|
import torch
|
|
20
22
|
|
|
@@ -117,6 +119,18 @@ def case_bsr(m, n, N, static=True, block_size=P, dtype=torch.float32, seed=1):
|
|
|
117
119
|
return _rel(C, A @ B), tol
|
|
118
120
|
|
|
119
121
|
|
|
122
|
+
def case_bsr_unsupported(m, n, N, block_size):
|
|
123
|
+
"""Block sizes the kernels do not take (#46): straight to torch, or a
|
|
124
|
+
NotImplementedError naming block_size 128 under TRNSPARSE_REQUIRE_NKI."""
|
|
125
|
+
import trnsparse.nki.dispatch as d
|
|
126
|
+
|
|
127
|
+
if not d._REQUIRE_NKI:
|
|
128
|
+
return case_bsr(m, n, N, block_size=block_size)
|
|
129
|
+
with pytest.raises(NotImplementedError, match="block_size 128 only"):
|
|
130
|
+
case_bsr(m, n, N, block_size=block_size)
|
|
131
|
+
return 0.0, 1e-4
|
|
132
|
+
|
|
133
|
+
|
|
120
134
|
# ── Screened SpMM (`_screened_spmm_kernel`) ───────────────────────────────────
|
|
121
135
|
|
|
122
136
|
SCREENED_SHAPES = [(1, 1), (127, 7), (129, 513), (200, 600), (1000, 33), (4097, 5)]
|
|
@@ -148,33 +162,33 @@ def _attn_mask(seq: int, seed: int) -> trnsparse.BSRMatrix:
|
|
|
148
162
|
return trnsparse.BSRMatrix.from_dense(dense, block_size=P)
|
|
149
163
|
|
|
150
164
|
|
|
151
|
-
def _attn_ref(Q, K, V, mask):
|
|
165
|
+
def _attn_ref(Q, K, V, mask, scale=None):
|
|
152
166
|
dense = mask.to_dense().bool()[: Q.shape[0], : Q.shape[0]]
|
|
153
|
-
s = (Q @ K.T) * Q.shape[1] ** -0.5
|
|
167
|
+
s = (Q @ K.T) * (Q.shape[1] ** -0.5 if scale is None else scale)
|
|
154
168
|
s = s.masked_fill(~dense, float("-inf"))
|
|
155
169
|
return torch.softmax(s, dim=-1) @ V
|
|
156
170
|
|
|
157
171
|
|
|
158
|
-
def case_attn(seq, hd, static=True, backward=False, seed=3):
|
|
172
|
+
def case_attn(seq, hd, static=True, backward=False, seed=3, scale=None):
|
|
159
173
|
import trnsparse.nki.dispatch as d
|
|
160
174
|
|
|
161
175
|
g = _g(seed)
|
|
162
176
|
Q, K, V = (torch.randn(seq, hd, generator=g, dtype=torch.float64) for _ in range(3))
|
|
163
177
|
mask = _attn_mask(seq, seed)
|
|
164
|
-
ref = _attn_ref(Q, K, V, mask)
|
|
178
|
+
ref = _attn_ref(Q, K, V, mask, scale)
|
|
165
179
|
prev = d._STATIC_STRUCTURE
|
|
166
180
|
d._STATIC_STRUCTURE = static
|
|
167
181
|
try:
|
|
168
182
|
if not backward:
|
|
169
183
|
out = trnsparse.block_sparse_attention_tiled(
|
|
170
|
-
*(t.float().to(DEV) for t in (Q, K, V)), mask
|
|
184
|
+
*(t.float().to(DEV) for t in (Q, K, V)), mask, scale=scale
|
|
171
185
|
)
|
|
172
186
|
return _rel(out, ref), 1e-4
|
|
173
187
|
dO = torch.randn(seq, hd, generator=g, dtype=torch.float64)
|
|
174
188
|
Qr, Kr, Vr = (t.detach().clone().requires_grad_(True) for t in (Q, K, V))
|
|
175
|
-
(_attn_ref(Qr, Kr, Vr, mask) * dO).sum().backward()
|
|
189
|
+
(_attn_ref(Qr, Kr, Vr, mask, scale) * dO).sum().backward()
|
|
176
190
|
Qd, Kd, Vd = (t.float().to(DEV).requires_grad_(True) for t in (Q, K, V))
|
|
177
|
-
out = trnsparse.block_sparse_attention_tiled(Qd, Kd, Vd, mask)
|
|
191
|
+
out = trnsparse.block_sparse_attention_tiled(Qd, Kd, Vd, mask, scale=scale)
|
|
178
192
|
(out * dO.float().to(DEV)).sum().backward()
|
|
179
193
|
err = max(_rel(a.grad, b.grad) for a, b in ((Qd, Qr), (Kd, Kr), (Vd, Vr)))
|
|
180
194
|
return err, 1e-3
|
|
@@ -266,7 +280,16 @@ for m, n, N in [(129, 200, 513), (4097, 257, 5)]:
|
|
|
266
280
|
lambda m=m, n=n, N=N: case_bsr(m, n, N, dtype=torch.bfloat16),
|
|
267
281
|
)
|
|
268
282
|
)
|
|
269
|
-
|
|
283
|
+
for b, (m, n, N) in itertools.product(
|
|
284
|
+
(16, 32, 64), [(200, 200, 7), (256, 256, 513), (1000, 300, 33)]
|
|
285
|
+
):
|
|
286
|
+
CASES.append(
|
|
287
|
+
(
|
|
288
|
+
f"bsr_spmm_block{b}",
|
|
289
|
+
_s(m, n, N),
|
|
290
|
+
lambda m=m, n=n, N=N, b=b: case_bsr_unsupported(m, n, N, b),
|
|
291
|
+
)
|
|
292
|
+
)
|
|
270
293
|
for M, N in SCREENED_SHAPES:
|
|
271
294
|
CASES.append(("screened_spmm", _s(M, M, N), lambda M=M, N=N: case_screened(M, N)))
|
|
272
295
|
for seq, hd in ATTN_SHAPES:
|
|
@@ -285,6 +308,20 @@ for seq, hd in ATTN_SHAPES:
|
|
|
285
308
|
lambda s=seq, h=hd: case_attn(s, h, static=False, backward=True),
|
|
286
309
|
)
|
|
287
310
|
)
|
|
311
|
+
# Non-default QK scale (trnsparse#47: it was dropped on every NKI path).
|
|
312
|
+
for path, static in (("static", True), ("gather", False)):
|
|
313
|
+
for direction, bwd in (("fwd", False), ("bwd", True)):
|
|
314
|
+
for scale in (0.1, 2.0):
|
|
315
|
+
CASES.append(
|
|
316
|
+
(
|
|
317
|
+
f"attn_{direction}_{path}_scale{scale}",
|
|
318
|
+
_s(384, 64),
|
|
319
|
+
lambda st=static, b=bwd, sc=scale: case_attn(
|
|
320
|
+
384, 64, static=st, backward=b, scale=sc
|
|
321
|
+
),
|
|
322
|
+
)
|
|
323
|
+
)
|
|
324
|
+
CASES.append(("attn_fwd_gather_scale0.1", _s(384, 256), lambda: case_attn(384, 256, scale=0.1)))
|
|
288
325
|
for n in FUSED_N:
|
|
289
326
|
for R in (1, 3, 33):
|
|
290
327
|
CASES.append(("cg_bsr_fused", f"n={n},R={R}", lambda n=n, R=R: case_cg(n, R)))
|
|
@@ -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.12.0"
|
|
9
9
|
|
|
10
10
|
from .formats import BSRMatrix, COOMatrix, CSRMatrix, eye_sparse, from_dense, from_scipy
|
|
11
11
|
from .iterative import (
|
|
@@ -6,7 +6,7 @@ NKI forward and the dQ / dK-dV NKI backward on the PyTorch/XLA path. On the
|
|
|
6
6
|
native path the same pair is two composite custom ops, linked with
|
|
7
7
|
`register_autograd`:
|
|
8
8
|
|
|
9
|
-
- `trnsparse::bsr_attn(Q, K, V, block_col_indices, block_row_ptrs, block_size)`
|
|
9
|
+
- `trnsparse::bsr_attn(Q, K, V, block_col_indices, block_row_ptrs, block_size, scale=None)`
|
|
10
10
|
-> `(out, row_max, row_denom)`: `dispatch.nki_bsr_attn_tiled`, i.e. the
|
|
11
11
|
`trnsparse::attn_stats` and `trnsparse::attn_out` kernel ops plus the
|
|
12
12
|
host-side softmax reduction.
|
|
@@ -53,9 +53,10 @@ def bsr_attn(
|
|
|
53
53
|
block_col_indices: torch.Tensor,
|
|
54
54
|
block_row_ptrs: torch.Tensor,
|
|
55
55
|
block_size: int,
|
|
56
|
+
scale: float | None = None,
|
|
56
57
|
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
57
58
|
mask = _pattern(block_col_indices, block_row_ptrs, Q.shape[0], block_size)
|
|
58
|
-
out, row_max, row_denom = _d.nki_bsr_attn_tiled(Q, K, V, mask, return_stats=True)
|
|
59
|
+
out, row_max, row_denom = _d.nki_bsr_attn_tiled(Q, K, V, mask, return_stats=True, scale=scale)
|
|
59
60
|
# Fixed output contract (Q's device; out in Q's dtype, the statistics in
|
|
60
61
|
# `_stats_dtype`) to match the fake.
|
|
61
62
|
sdt = _stats_dtype(Q.dtype)
|
|
@@ -67,7 +68,7 @@ def bsr_attn(
|
|
|
67
68
|
|
|
68
69
|
|
|
69
70
|
@bsr_attn.register_fake
|
|
70
|
-
def _bsr_attn_fake(Q, K, V, block_col_indices, block_row_ptrs, block_size):
|
|
71
|
+
def _bsr_attn_fake(Q, K, V, block_col_indices, block_row_ptrs, block_size, scale=None):
|
|
71
72
|
M_tiles = Q.shape[0] // block_size
|
|
72
73
|
sdt = _stats_dtype(Q.dtype)
|
|
73
74
|
return (
|
|
@@ -89,22 +90,24 @@ def bsr_attn_bwd(
|
|
|
89
90
|
block_size: int,
|
|
90
91
|
row_max: torch.Tensor,
|
|
91
92
|
row_denom: torch.Tensor,
|
|
93
|
+
scale: float | None = None,
|
|
92
94
|
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
93
95
|
mask = _pattern(block_col_indices, block_row_ptrs, Q.shape[0], block_size)
|
|
94
|
-
dQ, dK, dV = _d.nki_bsr_attn_bwd(Q, K, V, dO, O, mask, row_max, row_denom)
|
|
96
|
+
dQ, dK, dV = _d.nki_bsr_attn_bwd(Q, K, V, dO, O, mask, row_max, row_denom, scale=scale)
|
|
95
97
|
return tuple(t.to(device=Q.device, dtype=Q.dtype) for t in (dQ, dK, dV))
|
|
96
98
|
|
|
97
99
|
|
|
98
100
|
@bsr_attn_bwd.register_fake
|
|
99
|
-
def _bsr_attn_bwd_fake(Q, K, V, dO, O, block_col_indices, block_row_ptrs, block_size, *
|
|
101
|
+
def _bsr_attn_bwd_fake(Q, K, V, dO, O, block_col_indices, block_row_ptrs, block_size, *rest):
|
|
100
102
|
return torch.empty_like(Q), torch.empty_like(K), torch.empty_like(V)
|
|
101
103
|
|
|
102
104
|
|
|
103
105
|
def _bsr_attn_setup_context(ctx, inputs, output):
|
|
104
|
-
Q, K, V, block_col_indices, block_row_ptrs, block_size = inputs
|
|
106
|
+
Q, K, V, block_col_indices, block_row_ptrs, block_size, scale = inputs
|
|
105
107
|
out, row_max, row_denom = output
|
|
106
108
|
ctx.save_for_backward(Q, K, V, out, row_max, row_denom, block_col_indices, block_row_ptrs)
|
|
107
109
|
ctx.block_size = block_size
|
|
110
|
+
ctx.scale = scale
|
|
108
111
|
|
|
109
112
|
|
|
110
113
|
def _bsr_attn_backward(ctx, d_out, d_row_max, d_row_denom):
|
|
@@ -122,8 +125,9 @@ def _bsr_attn_backward(ctx, d_out, d_row_max, d_row_denom):
|
|
|
122
125
|
ctx.block_size,
|
|
123
126
|
row_max,
|
|
124
127
|
row_denom,
|
|
128
|
+
ctx.scale,
|
|
125
129
|
)
|
|
126
|
-
return dQ, dK, dV, None, None, None
|
|
130
|
+
return dQ, dK, dV, None, None, None, None
|
|
127
131
|
|
|
128
132
|
|
|
129
133
|
bsr_attn.register_autograd(_bsr_attn_backward, setup_context=_bsr_attn_setup_context)
|
|
@@ -113,6 +113,31 @@ def _use_nki() -> bool:
|
|
|
113
113
|
return HAS_NKI
|
|
114
114
|
|
|
115
115
|
|
|
116
|
+
# Block sizes the BSR / attention kernels take. Every kernel treats a
|
|
117
|
+
# block as one 128x128 Tensor Engine tile (`_TILE_M` is built into its
|
|
118
|
+
# shapes), so any other block size fails to lower on every call (#46).
|
|
119
|
+
_NKI_BLOCK_SIZES = (_TILE_M,)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _nki_block_ok(op: str, block_size: int) -> bool:
|
|
123
|
+
"""True when the NKI kernels behind `op` take `block_size`.
|
|
124
|
+
|
|
125
|
+
Callers route to the PyTorch path on False, without tracing a kernel
|
|
126
|
+
that cannot lower. Under `TRNSPARSE_REQUIRE_NKI` an unsupported block
|
|
127
|
+
size raises `NotImplementedError` instead.
|
|
128
|
+
"""
|
|
129
|
+
if int(block_size) in _NKI_BLOCK_SIZES:
|
|
130
|
+
return True
|
|
131
|
+
if _REQUIRE_NKI:
|
|
132
|
+
sizes = ", ".join(str(b) for b in _NKI_BLOCK_SIZES)
|
|
133
|
+
raise NotImplementedError(
|
|
134
|
+
f"trnsparse {op}: the NKI kernels support block_size {sizes} only, "
|
|
135
|
+
f"got {block_size}. Rebuild the BSR matrix with block_size={_TILE_M}, "
|
|
136
|
+
"or unset TRNSPARSE_REQUIRE_NKI to use the PyTorch path."
|
|
137
|
+
)
|
|
138
|
+
return False
|
|
139
|
+
|
|
140
|
+
|
|
116
141
|
def _round_up(n: int, multiple: int) -> int:
|
|
117
142
|
return ((n + multiple - 1) // multiple) * multiple
|
|
118
143
|
|
|
@@ -678,10 +703,14 @@ def nki_bsr_spmm(A, B: torch.Tensor) -> torch.Tensor:
|
|
|
678
703
|
`A.blocks` and `B` through the gather), so no per-block Python loop
|
|
679
704
|
runs on device tensors. The result is on B's device.
|
|
680
705
|
"""
|
|
706
|
+
if not _nki_block_ok("bsr_spmm", A.block_size):
|
|
707
|
+
from ..ops import _bsr_spmm_pytorch
|
|
708
|
+
|
|
709
|
+
return _bsr_spmm_pytorch(A, B)
|
|
681
710
|
if _native_path():
|
|
682
711
|
out_cols = B.shape[1]
|
|
683
712
|
n_tiles = 1 if out_cols <= _TILE_N else -(-out_cols // _TILE_N)
|
|
684
|
-
if
|
|
713
|
+
if _static_structure_ok(A.n_blocks * n_tiles):
|
|
685
714
|
try:
|
|
686
715
|
return _nki_bsr_spmm_static(A, B)
|
|
687
716
|
except Exception:
|
|
@@ -1013,6 +1042,7 @@ def nki_bsr_attn_tiled(
|
|
|
1013
1042
|
V: torch.Tensor,
|
|
1014
1043
|
mask_bsr,
|
|
1015
1044
|
return_stats: bool = False,
|
|
1045
|
+
scale: float | None = None,
|
|
1016
1046
|
):
|
|
1017
1047
|
"""Two-pass block-sparse attention via NKI kernel pair.
|
|
1018
1048
|
|
|
@@ -1030,6 +1060,8 @@ def nki_bsr_attn_tiled(
|
|
|
1030
1060
|
return_stats: If True, returns (out, row_max, row_denom) where row_max
|
|
1031
1061
|
and row_denom have shape (M_tiles, block_size). Used by
|
|
1032
1062
|
`_AttnTiledFunction.forward` to save stats for backward.
|
|
1063
|
+
scale: QK scale; None means head_dim ** -0.5. Applied to Q on
|
|
1064
|
+
the host/device before the kernels (they take Q * scale).
|
|
1033
1065
|
|
|
1034
1066
|
Returns:
|
|
1035
1067
|
(seq_len, head_dim) attention output, or a 3-tuple when return_stats=True.
|
|
@@ -1038,12 +1070,16 @@ def nki_bsr_attn_tiled(
|
|
|
1038
1070
|
raise RuntimeError("NKI not available")
|
|
1039
1071
|
|
|
1040
1072
|
seq_len, head_dim = Q.shape
|
|
1041
|
-
scale = head_dim**-0.5
|
|
1073
|
+
scale = head_dim**-0.5 if scale is None else float(scale)
|
|
1074
|
+
|
|
1075
|
+
if not _nki_block_ok("block_sparse_attention_tiled", mask_bsr.block_size):
|
|
1076
|
+
from ..ops import _block_sparse_attn_pytorch
|
|
1077
|
+
|
|
1078
|
+
return _block_sparse_attn_pytorch(Q, K, V, mask_bsr, scale, return_stats=return_stats)
|
|
1042
1079
|
|
|
1043
1080
|
if (
|
|
1044
1081
|
_native_path()
|
|
1045
1082
|
and head_dim <= _TILE_K
|
|
1046
|
-
and mask_bsr.block_size == _TILE_M
|
|
1047
1083
|
and seq_len % _TILE_M == 0
|
|
1048
1084
|
and _static_structure_ok(2 * mask_bsr.n_blocks)
|
|
1049
1085
|
):
|
|
@@ -1116,10 +1152,9 @@ def nki_bsr_attn_tiled(
|
|
|
1116
1152
|
# PyTorch fallback — import lazily to avoid circular dependency.
|
|
1117
1153
|
from ..ops import _block_sparse_attn_pytorch
|
|
1118
1154
|
|
|
1119
|
-
scale_val = head_dim**-0.5
|
|
1120
1155
|
if return_stats:
|
|
1121
|
-
return _block_sparse_attn_pytorch(Q, K, V, mask_bsr,
|
|
1122
|
-
return _block_sparse_attn_pytorch(Q, K, V, mask_bsr,
|
|
1156
|
+
return _block_sparse_attn_pytorch(Q, K, V, mask_bsr, scale, return_stats=True)
|
|
1157
|
+
return _block_sparse_attn_pytorch(Q, K, V, mask_bsr, scale)
|
|
1123
1158
|
|
|
1124
1159
|
|
|
1125
1160
|
def _nki_attn_fwd_static(Q, K, V, mask_bsr, scale: float, return_stats: bool):
|
|
@@ -1368,6 +1403,7 @@ def nki_bsr_attn_bwd(
|
|
|
1368
1403
|
mask_bsr,
|
|
1369
1404
|
row_max: torch.Tensor,
|
|
1370
1405
|
row_denom: torch.Tensor,
|
|
1406
|
+
scale: float | None = None,
|
|
1371
1407
|
) -> tuple:
|
|
1372
1408
|
"""NKI backward pass for block-sparse tiled attention.
|
|
1373
1409
|
|
|
@@ -1375,6 +1411,8 @@ def nki_bsr_attn_bwd(
|
|
|
1375
1411
|
1. `_attn_bwd_dq_kernel` — row-first, computes dQ.
|
|
1376
1412
|
2. `_attn_bwd_dkdv_kernel` — column-first, computes dK and dV.
|
|
1377
1413
|
|
|
1414
|
+
`scale` must be the forward's QK scale (None means head_dim ** -0.5).
|
|
1415
|
+
|
|
1378
1416
|
Returns:
|
|
1379
1417
|
(dQ, dK, dV) — same shape as (Q, K, V).
|
|
1380
1418
|
"""
|
|
@@ -1383,12 +1421,18 @@ def nki_bsr_attn_bwd(
|
|
|
1383
1421
|
|
|
1384
1422
|
seq_len, head_dim = Q.shape
|
|
1385
1423
|
b = mask_bsr.block_size
|
|
1386
|
-
scale = head_dim**-0.5
|
|
1424
|
+
scale = head_dim**-0.5 if scale is None else float(scale)
|
|
1425
|
+
|
|
1426
|
+
if not _nki_block_ok("block_sparse_attention_tiled backward", b):
|
|
1427
|
+
from ..ops import _block_sparse_attn_backward
|
|
1428
|
+
|
|
1429
|
+
return _block_sparse_attn_backward(
|
|
1430
|
+
Q, K, V, O, dO, mask_bsr, scale, row_max=row_max, row_denom=row_denom
|
|
1431
|
+
)
|
|
1387
1432
|
|
|
1388
1433
|
if (
|
|
1389
1434
|
_native_path()
|
|
1390
1435
|
and head_dim <= _TILE_K
|
|
1391
|
-
and b == _TILE_M
|
|
1392
1436
|
and seq_len % _TILE_M == 0
|
|
1393
1437
|
and _static_structure_ok(2 * mask_bsr.n_blocks)
|
|
1394
1438
|
):
|
|
@@ -264,9 +264,10 @@ def bsr_spmm(A: BSRMatrix, B: torch.Tensor) -> torch.Tensor:
|
|
|
264
264
|
`A.block_col_indices` on the host; `A.blocks` and `B` on the host or on
|
|
265
265
|
`neuron`. The result is on B's device.
|
|
266
266
|
"""
|
|
267
|
-
from .nki.dispatch import _use_nki
|
|
267
|
+
from .nki.dispatch import _nki_block_ok, _use_nki
|
|
268
268
|
|
|
269
|
-
|
|
269
|
+
# Block sizes the kernels do not take go straight to PyTorch (#46).
|
|
270
|
+
if _use_nki() and _nki_block_ok("bsr_spmm", A.block_size):
|
|
270
271
|
from .nki.dispatch import nki_bsr_spmm
|
|
271
272
|
|
|
272
273
|
return nki_bsr_spmm(A, B)
|
|
@@ -566,12 +567,14 @@ class _AttnTiledFunction(torch.autograd.Function):
|
|
|
566
567
|
|
|
567
568
|
mask_bsr = _BSRHandle()
|
|
568
569
|
|
|
569
|
-
from .nki.dispatch import _use_nki
|
|
570
|
+
from .nki.dispatch import _nki_block_ok, _use_nki
|
|
570
571
|
|
|
571
|
-
if _use_nki():
|
|
572
|
+
if _use_nki() and _nki_block_ok("block_sparse_attention_tiled", mask_block_size):
|
|
572
573
|
from .nki.dispatch import nki_bsr_attn_tiled
|
|
573
574
|
|
|
574
|
-
out, row_max, row_denom = nki_bsr_attn_tiled(
|
|
575
|
+
out, row_max, row_denom = nki_bsr_attn_tiled(
|
|
576
|
+
Q, K, V, mask_bsr, return_stats=True, scale=scale
|
|
577
|
+
)
|
|
575
578
|
else:
|
|
576
579
|
out, row_max, row_denom = _block_sparse_attn_pytorch(
|
|
577
580
|
Q, K, V, mask_bsr, scale, return_stats=True
|
|
@@ -601,12 +604,14 @@ class _AttnTiledFunction(torch.autograd.Function):
|
|
|
601
604
|
|
|
602
605
|
mask_bsr = _BSRHandle()
|
|
603
606
|
|
|
604
|
-
from .nki.dispatch import _use_nki
|
|
607
|
+
from .nki.dispatch import _nki_block_ok, _use_nki
|
|
605
608
|
|
|
606
|
-
if _use_nki():
|
|
609
|
+
if _use_nki() and _nki_block_ok("block_sparse_attention_tiled", ctx.mask_block_size):
|
|
607
610
|
from .nki.dispatch import nki_bsr_attn_bwd
|
|
608
611
|
|
|
609
|
-
dQ, dK, dV = nki_bsr_attn_bwd(
|
|
612
|
+
dQ, dK, dV = nki_bsr_attn_bwd(
|
|
613
|
+
Q, K, V, dO, O, mask_bsr, row_max, row_denom, scale=ctx.scale
|
|
614
|
+
)
|
|
610
615
|
else:
|
|
611
616
|
dQ, dK, dV = _block_sparse_attn_backward(
|
|
612
617
|
Q, K, V, O, dO, mask_bsr, ctx.scale, row_max=row_max, row_denom=row_denom
|
|
@@ -688,9 +693,11 @@ def block_sparse_attention_tiled(
|
|
|
688
693
|
if scale is None:
|
|
689
694
|
scale = head_dim**-0.5
|
|
690
695
|
|
|
691
|
-
from .nki.dispatch import _native_path, _use_nki
|
|
696
|
+
from .nki.dispatch import _native_path, _nki_block_ok, _use_nki
|
|
692
697
|
|
|
693
|
-
|
|
698
|
+
# Block sizes the kernels do not take go straight to PyTorch (#46).
|
|
699
|
+
use_nki = _use_nki() and _nki_block_ok("block_sparse_attention_tiled", b)
|
|
700
|
+
if use_nki and _native_path():
|
|
694
701
|
from .nki.dispatch import _get_native_ops
|
|
695
702
|
|
|
696
703
|
out, _, _ = _get_native_ops()["bsr_attn"](
|
|
@@ -700,6 +707,7 @@ def block_sparse_attention_tiled(
|
|
|
700
707
|
mask_bsr.block_col_indices.cpu(),
|
|
701
708
|
mask_bsr.block_row_ptrs.cpu(),
|
|
702
709
|
mask_bsr.block_size,
|
|
710
|
+
float(scale),
|
|
703
711
|
)
|
|
704
712
|
return out
|
|
705
713
|
|
|
@@ -715,9 +723,9 @@ def block_sparse_attention_tiled(
|
|
|
715
723
|
scale,
|
|
716
724
|
)
|
|
717
725
|
|
|
718
|
-
if
|
|
726
|
+
if use_nki:
|
|
719
727
|
from .nki.dispatch import nki_bsr_attn_tiled
|
|
720
728
|
|
|
721
|
-
return nki_bsr_attn_tiled(Q, K, V, mask_bsr)
|
|
729
|
+
return nki_bsr_attn_tiled(Q, K, V, mask_bsr, scale=scale)
|
|
722
730
|
|
|
723
731
|
return _block_sparse_attn_pytorch(Q, K, V, mask_bsr, scale)
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|