diff options
| author | jdj <jdj@kunix.org> | 2026-10-29 11:28:55 -0700 |
|---|---|---|
| committer | jdj <jdj@kunix.org> | 2026-10-29 11:28:55 -0700 |
| commit | 3d4aa8a382220ceeafc34c0c59af80f565d3a4a8 (patch) | |
| tree | 32edcf8de9f339b7415a4d8b3ff6bfdc9d435088 | |
| parent | 72fab81a09083eb858840a21366eace175d01721 (diff) | |
| download | volta-train-kernels-3d4aa8a382220ceeafc34c0c59af80f565d3a4a8.tar.gz volta-train-kernels-3d4aa8a382220ceeafc34c0c59af80f565d3a4a8.zip | |
Correctness tests: fp64 error vs stock SDPA, document isolation, Canon+RoPE bitwise
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | README.md | 2 | ||||
| -rw-r--r-- | tests/_ref.py | 59 | ||||
| -rw-r--r-- | tests/test_attention.py | 65 | ||||
| -rw-r--r-- | tests/test_canon_rope.py | 44 |
4 files changed, 169 insertions, 1 deletions
@@ -54,7 +54,7 @@ bitwise deterministic run to run (the difference is fp32 summation order only). ## Tests ```bash -VK_TEST_DEVICE=cuda:0 python -m unittest discover -s tests -v +VK_TEST_DEVICE=cuda:0 python -m unittest discover -s tests -v # run from the repo root ``` ## Results diff --git a/tests/_ref.py b/tests/_ref.py new file mode 100644 index 0000000..36ddd27 --- /dev/null +++ b/tests/_ref.py @@ -0,0 +1,59 @@ +"""References for the tests and benchmarks: fp64 math and stock PyTorch SDPA.""" +import os + +import torch +import torch.nn.functional as F +from torch.nn.attention import SDPBackend, sdpa_kernel + + +def device(): + return torch.device(os.environ.get("VK_TEST_DEVICE", "cuda:1")) + + +def select(dev): + """Make dev the current device: Triton compiles for the current device, not the tensors'.""" + torch.cuda.set_device(dev) + torch.cuda.set_per_process_memory_fraction(0.15, dev) + + +def usable(dev): + """None if the kernels can run on dev, else the reason to skip.""" + if not torch.cuda.is_available(): + return "no CUDA" + if torch.cuda.get_device_capability(dev) < (7, 0): + return "needs compute capability >= 7.0" + return None + + +def packed_qkv(doc_lens, heads=8, dim=64, dev=None, seed=0): + """Random (N, H, D) fp16 q, k, v and int64 offsets for documents packed back to back.""" + g = torch.Generator().manual_seed(seed) + n = sum(doc_lens) + q, k, v = (torch.randn(n, heads, dim, generator=g).to(dev, torch.float16) for _ in range(3)) + offsets = torch.tensor([0] + list(torch.tensor(doc_lens).cumsum(0)), device=dev) + return q, k, v, offsets + + +def attention_fp64(q, k, v, offsets): + """Causal attention per document, computed in fp64.""" + out = torch.empty(q.shape, dtype=torch.float64, device=q.device) + scale = q.shape[-1] ** -0.5 + for a, b in zip(offsets[:-1].tolist(), offsets[1:].tolist()): + qd, kd, vd = (t[a:b].double().transpose(0, 1) for t in (q, k, v)) + s = qd @ kd.transpose(-1, -2) * scale + s = s.masked_fill(torch.ones(b - a, b - a, dtype=torch.bool, device=q.device).triu(1), float("-inf")) + out[a:b] = (s.softmax(-1) @ vd).transpose(0, 1) + return out + + +def sdpa_stock(q, k, v, offsets): + """PyTorch's memory-efficient SDPA over a jagged nested tensor, the only stock + backend that trains on sm_70. Returns (N, H, D) fp16.""" + nest = [torch.nested.nested_tensor_from_jagged(t, offsets).transpose(1, 2) for t in (q, k, v)] + with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION): + o = F.scaled_dot_product_attention(*nest, is_causal=True) + return o.transpose(1, 2).values() + + +def rel_err(x, ref): + return ((x.double() - ref).norm() / ref.norm()).item() diff --git a/tests/test_attention.py b/tests/test_attention.py new file mode 100644 index 0000000..0def2cf --- /dev/null +++ b/tests/test_attention.py @@ -0,0 +1,65 @@ +import unittest + +import torch + +from _ref import attention_fp64, device, packed_qkv, rel_err, sdpa_stock, select, usable + +DOCS = [700, 64, 1, 2048, 333] +BAR = 1.05 # ours may be at most 5% worse than stock against fp64 + + +@unittest.skipIf(usable(device()), usable(device()) or "") +class TestAttention(unittest.TestCase): + @classmethod + def setUpClass(cls): + select(device()) + + def _grads(self, fn, q, k, v, offsets, do): + q, k, v = (t.clone().requires_grad_() for t in (q, k, v)) + o = fn(q, k, v, offsets) + o.backward(do) + return o.detach(), q.grad, k.grad, v.grad + + def test_fwd_error_within_stock(self): + from volta_kernels import varlen_causal_attention + q, k, v, off = packed_qkv(DOCS, dev=device()) + ref = attention_fp64(q, k, v, off) + ours = rel_err(varlen_causal_attention(q, k, v, off), ref) + stock = rel_err(sdpa_stock(q, k, v, off), ref) + self.assertLessEqual(ours, BAR * stock, f"ours {ours:.3e} stock {stock:.3e}") + + def test_bwd_error_within_stock(self): + from volta_kernels import varlen_causal_attention + q, k, v, off = packed_qkv(DOCS, dev=device()) + do = torch.randn_like(q) + ref = self._grads(attention_fp64, q.double(), k.double(), v.double(), off, do.double()) + ours = self._grads(varlen_causal_attention, q, k, v, off, do) + stock = self._grads(sdpa_stock, q, k, v, off, do) + for name, i in (("dq", 1), ("dk", 2), ("dv", 3)): + eo, es = rel_err(ours[i], ref[i]), rel_err(stock[i], ref[i]) + self.assertLessEqual(eo, BAR * es, f"{name}: ours {eo:.3e} stock {es:.3e}") + + def test_document_isolation_bitwise(self): + from volta_kernels import varlen_causal_attention + q, k, v, off = packed_qkv(DOCS, dev=device()) + do = torch.randn_like(q) + a, b = off[2].item(), off[3].item() # document 2 + q2, k2, v2 = q.clone(), k.clone(), v.clone() + for t in (q2, k2, v2): + t[a:b] = torch.randn_like(t[a:b]) + base = self._grads(varlen_causal_attention, q, k, v, off, do) + pert = self._grads(varlen_causal_attention, q2, k2, v2, off, do) + keep = torch.ones(q.shape[0], dtype=torch.bool, device=q.device) + keep[a:b] = False + for name, i in (("out", 0), ("dk", 2), ("dv", 3)): + self.assertTrue(torch.equal(base[i][keep], pert[i][keep]), f"{name} leaked across documents") + + def test_rejects_bad_head_dim(self): + from volta_kernels import varlen_causal_attention + q, k, v, off = packed_qkv([128], dim=32, dev=device()) + with self.assertRaisesRegex(RuntimeError, "q"): + varlen_causal_attention(q, k, v, off) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_canon_rope.py b/tests/test_canon_rope.py new file mode 100644 index 0000000..c9f939d --- /dev/null +++ b/tests/test_canon_rope.py @@ -0,0 +1,44 @@ +import unittest + +import torch + +from _ref import device, select, usable + + +def canon_inputs(B=2, T=1024, doc_starts=(0, 300, 301, 777), dev=None, seed=0): + """qkv (B,T,1536) fp16, canon_w (1536,3) fp32, document masks and RoPE tables.""" + g = torch.Generator().manual_seed(seed) + qkv = torch.randn(B, T, 1536, generator=g).to(dev, torch.float16) + w = (0.1 * torch.randn(1536, 3, generator=g)).to(dev) + start = torch.zeros(B, T, dtype=torch.bool) + start[:, list(doc_starts)] = True + first2 = start.clone() + first2[:, 1:] |= start[:, :-1] + m1 = (~start).float()[:, :, None].to(dev) # is t-1 in this document? + m2 = (~first2).float()[:, :, None].to(dev) # is t-2? + pos = torch.arange(T, dtype=torch.float32) + ang = pos[:, None] * (10000.0 ** (-torch.arange(32) / 32))[None] + cos, sin = (f(ang)[None].expand(B, T, 32).contiguous().to(dev) for f in (torch.cos, torch.sin)) + return qkv, w, m1, m2, cos, sin + + +@unittest.skipIf(usable(device()), usable(device()) or "") +class TestCanonRope(unittest.TestCase): + @classmethod + def setUpClass(cls): + select(device()) + + def test_canon_rope_matches_reference(self): + from volta_kernels.canon_rope import canon_rope + from volta_kernels.canon_rope_bw import ext + qkv, w, m1, m2, cos, sin = canon_inputs(dev=device()) + ref = canon_rope(qkv, w, m1, m2, cos, sin) + N = qkv.shape[0] * qkv.shape[1] + ours = ext.fwd(qkv, w.contiguous(), m1.reshape(N).contiguous(), m2.reshape(N).contiguous(), + cos.reshape(N, 32).contiguous(), sin.reshape(N, 32).contiguous(), 4, 64, 4, 1) + for name, a, b in zip("qkv", ours, ref): + self.assertTrue(torch.equal(a.reshape(b.shape), b), f"{name} differs from the Triton reference") + + +if __name__ == "__main__": + unittest.main() |
