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") 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()