From a0ddfb1b2f6242fac72f98e8d6ee1888e79667f3 Mon Sep 17 00:00:00 2001 From: jdj Date: Thu, 29 Oct 2026 11:50:22 -0700 Subject: Validate offsets and canon_rope_attention shapes; default test device cuda:0 with safe skip; narrow README claims Co-Authored-By: Claude Opus 5.5 --- README.md | 15 +++++++++------ tests/_ref.py | 8 ++++++-- tests/test_attention.py | 8 ++++++++ tests/test_canon_rope.py | 13 +++++++++++++ tests/test_ref.py | 5 +++++ volta_kernels/__init__.py | 27 ++++++++++++++++++++++----- 6 files changed, 63 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 1fc3451..89daa8a 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,8 @@ described in the paper *Outrageously Fast Training on Volta*. |---|---| | `attn.cu` via `varlen_causal_attention` | Causal attention over packed variable-length documents, head_dim 64, fp16 in/out. Forward and backward run on raw `mma.sync.aligned.m8n8k4` tensor-core instructions (HMMA.884) with fp32 accumulation. Documents are launched longest-first. | | `canon_rope_bw.py` via `canon_rope_attention` | A Canon depthwise 3-tap convolution, RoPE and the attention above, as one autograd function. The Canon/RoPE part is a bandwidth-bound CUDA kernel. | -| `canon_rope.py` | The Triton reference for Canon+RoPE. The CUDA version is bitwise-identical to it. | -| `head.py` via `fused_lm_loss` | Chunked cross-entropy LM head that never materializes `(N, V)` logits. dW and dx come from fp32-output GEMMs. | +| `canon_rope.py` | The Triton reference for Canon+RoPE. The CUDA forward is bitwise-identical to it; the CUDA backward reduces the weight gradient in a different order. | +| `head.py` via `fused_lm_loss` | Chunked cross-entropy LM head that never materializes `(N, V)` logits. dW and dx come from fp32-output GEMMs. It saves memory; it is not faster than an unchunked head that fits in memory. | | `integ_ops.py` | Fused residual-add + RMSNorm backward, weight-gradient accumulation straight into fp32 `.grad`, and a tied-embedding gradient. | ## Requirements @@ -46,15 +46,18 @@ o.sum().backward() ## Precision Every kernel keeps the operand dtypes and fp32 accumulation of the stock path it -replaces. The test suite holds each output's error against an fp64 reference -to at most 1.05x the stock path's own error on the same inputs. Document -isolation is exact. dQ uses fp32 atomics, so the attention backward is not +replaces. For attention (forward and backward), the test suite holds each output's +error against an fp64 reference to at most 1.05x the stock path's own error on the +same inputs, and checks that document isolation is exact. The Canon+RoPE forward is +tested bitwise against its Triton reference. The Canon backward and the ops in +`integ_ops.py` were validated inside the Boris-2 training code but have no +standalone tests here yet. dQ uses fp32 atomics, so the attention backward is not 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 # run from the repo root +python -m unittest discover -s tests -v # from the repo root; VK_TEST_DEVICE=cuda:N picks the GPU ``` ## Results diff --git a/tests/_ref.py b/tests/_ref.py index dc8626b..d4d8543 100644 --- a/tests/_ref.py +++ b/tests/_ref.py @@ -7,7 +7,7 @@ from torch.nn.attention import SDPBackend, sdpa_kernel def device(): - return torch.device(os.environ.get("VK_TEST_DEVICE", "cuda:1")) + return torch.device(os.environ.get("VK_TEST_DEVICE", "cuda:0")) def select(dev): @@ -20,7 +20,11 @@ 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): + try: + cap = torch.cuda.get_device_capability(dev) + except (AssertionError, RuntimeError) as e: + return f"{dev} unavailable: {e}" + if cap < (7, 0): return "needs compute capability >= 7.0" return None diff --git a/tests/test_attention.py b/tests/test_attention.py index 0def2cf..99b6dcc 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -60,6 +60,14 @@ class TestAttention(unittest.TestCase): with self.assertRaisesRegex(RuntimeError, "q"): varlen_causal_attention(q, k, v, off) + def test_rejects_offsets_not_covering_tokens(self): + from volta_kernels import varlen_causal_attention + q, k, v, off = packed_qkv([128, 64], dev=device()) + with self.assertRaisesRegex(RuntimeError, "offsets"): + varlen_causal_attention(q, k, v, off[:-1]) # last 64 tokens uncovered + with self.assertRaisesRegex(RuntimeError, "offsets"): + varlen_causal_attention(q, k, v, off + 1) # does not start at 0 + if __name__ == "__main__": unittest.main() diff --git a/tests/test_canon_rope.py b/tests/test_canon_rope.py index c9f939d..9a4db6e 100644 --- a/tests/test_canon_rope.py +++ b/tests/test_canon_rope.py @@ -39,6 +39,19 @@ class TestCanonRope(unittest.TestCase): 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") + def test_canon_attention_rejects_bad_shapes(self): + from volta_kernels import canon_rope_attention + qkv, w, m1, m2, cos, sin = canon_inputs(B=1, T=192, doc_starts=(0,), dev=device()) + off = torch.tensor([0, 192], device=device()) + with self.assertRaisesRegex(RuntimeError, "128"): # T=192 passes fwd, fails bwd + canon_rope_attention(qkv, w, m1, m2, cos, sin, off) + qkv, w, m1, m2, cos, sin = canon_inputs(B=1, T=256, doc_starts=(0,), dev=device()) + off = torch.tensor([0, 256], device=device()) + with self.assertRaisesRegex(RuntimeError, "1536"): + canon_rope_attention(qkv[..., :1024].contiguous(), w, m1, m2, cos, sin, off) + with self.assertRaisesRegex(RuntimeError, "fp16"): + canon_rope_attention(qkv.float(), w, m1, m2, cos, sin, off) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_ref.py b/tests/test_ref.py index 5024971..c9fd93d 100644 --- a/tests/test_ref.py +++ b/tests/test_ref.py @@ -19,5 +19,10 @@ class TestReference(unittest.TestCase): self.assertLess(((m[name] - want).norm() / want.norm()).item(), 1e-12, name) +class TestDeviceSelection(unittest.TestCase): + def test_missing_device_is_a_skip_reason_not_an_error(self): + self.assertIsInstance(usable(torch.device("cuda:99")), str) + + if __name__ == "__main__": unittest.main() diff --git a/volta_kernels/__init__.py b/volta_kernels/__init__.py index 4d183b0..ed3247e 100644 --- a/volta_kernels/__init__.py +++ b/volta_kernels/__init__.py @@ -27,7 +27,17 @@ def _load(): return _ext -def tile_table(offsets: torch.Tensor): +def _check_offsets(offsets: torch.Tensor, n_tokens: int) -> None: + """One host sync per offsets tensor (the table is cached): a wrong boundary list would + otherwise leave output rows unwritten or read past the end of q/k/v.""" + if offsets.dim() != 1 or offsets.numel() < 2: + raise RuntimeError(f"offsets must be 1-D with at least 2 entries, got shape {tuple(offsets.shape)}") + o = offsets.tolist() + if o[0] != 0 or o[-1] != n_tokens or any(b < a for a, b in zip(o, o[1:])): + raise RuntimeError(f"offsets must rise from 0 to the token count {n_tokens}; got {o[0]} .. {o[-1]}") + + +def tile_table(offsets: torch.Tensor, n_tokens: int): """(cu, tcum, perm) int32 for a document-offset tensor, cached on the tensor. tcum is the cumulative 64-tile count over documents sorted LONGEST FIRST and @@ -41,13 +51,14 @@ def tile_table(offsets: torch.Tensor): tab = getattr(offsets, "_volta_tab", None) # Keyed on the version counter too: an in-place edit of the offsets must # never be served a stale table. - if tab is None or tab[3] != offsets._version: + if tab is None or tab[3] != offsets._version or tab[4] != n_tokens: + _check_offsets(offsets, n_tokens) cu = offsets.to(torch.int32) tiles = (cu[1:] - cu[:-1] + 63) // 64 order = torch.argsort(tiles, descending=True, stable=True) tcum = torch.zeros_like(cu) tcum[1:] = torch.cumsum(tiles[order], 0) - tab = (cu, tcum, order.to(torch.int32), offsets._version) + tab = (cu, tcum, order.to(torch.int32), offsets._version, n_tokens) offsets._volta_tab = tab return tab[0], tab[1], tab[2] @@ -76,7 +87,7 @@ def varlen_causal_attention(q, k, v, offsets, scale: float | None = None): """ if scale is None: scale = q.shape[-1] ** -0.5 - cu, tcum, perm = tile_table(offsets) + cu, tcum, perm = tile_table(offsets, q.shape[0]) return _VarlenAttn.apply(q, k, v, cu, tcum, perm, scale) @@ -99,7 +110,7 @@ class _CanonRopeAttn(torch.autograd.Function): m1f, m2f = m1.reshape(N).contiguous(), m2.reshape(N).contiguous() cf, sf = cos.reshape(N, 32).contiguous(), sin.reshape(N, 32).contiguous() q, k, v = canon_ext.fwd(qkv, w.contiguous(), m1f, m2f, cf, sf, 4, 64, 4, 1) - cu, tcum, perm = tile_table(offsets) + cu, tcum, perm = tile_table(offsets, N) qv, kv, vv = q.view(N, 8, 64), k.view(N, 8, 64), v.view(N, 8, 64) o, lse = _load().fwd(qv, kv, vv, cu, tcum, perm, scale) ctx.save_for_backward(qkv, w, m1f, m2f, cf, sf, qv, kv, vv, o, lse, cu, tcum, perm) @@ -120,4 +131,10 @@ class _CanonRopeAttn(torch.autograd.Function): def canon_rope_attention(qkv, canon_w, m1, m2, cos, sin, offsets): """qkv (B, T, 1536) fp16 -> Canon + RoPE -> causal varlen attention -> (N, 8, 64).""" + if qkv.dim() != 3 or qkv.shape[-1] != 1536: + raise RuntimeError(f"qkv must be (B, T, 1536) (8 heads x 64 x q|k|v), got {tuple(qkv.shape)}") + if qkv.dtype != torch.float16 or not qkv.is_contiguous(): + raise RuntimeError("qkv must be contiguous fp16") + if qkv.shape[1] % 128: + raise RuntimeError(f"T must be a multiple of 128 (the Canon backward's chunk), got {qkv.shape[1]}") return _CanonRopeAttn.apply(qkv, canon_w, m1, m2, cos, sin, offsets, 0.125) -- cgit v1.2.3