"""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:0")) 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" 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 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, seqlens=None): """PyTorch's memory-efficient SDPA over a jagged nested tensor, the only stock backend that trains on sm_70. Returns (N, H, D) fp16. seqlens=(min, max) document length, known on the host, avoids a device sync per call -- as a training loop that knows its packing would do.""" kw = {} if seqlens is None else {"min_seqlen": seqlens[0], "max_seqlen": seqlens[1]} nest = [torch.nested.nested_tensor_from_jagged(t, offsets, **kw).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() def attention_fp64_grads(q, k, v, offsets, do): """fp64 causal attention and its exact gradients, one (document, head) at a time. Manual backward, no autograd graph: peak memory is a few L x L fp64 matrices, so an 8192-token document fits where autograd over all heads would need tens of GB. Returns dict out, dq, dk, dv (fp64, (N, H, D)).""" res = {n: torch.empty(q.shape, dtype=torch.float64, device=q.device) for n in ("out", "dq", "dk", "dv")} scale = q.shape[-1] ** -0.5 for a, b in zip(offsets[:-1].tolist(), offsets[1:].tolist()): mask = torch.ones(b - a, b - a, dtype=torch.bool, device=q.device).triu(1) for h in range(q.shape[1]): qd, kd, vd, dod = (t[a:b, h].double() for t in (q, k, v, do)) p = (qd @ kd.T * scale).masked_fill_(mask, float("-inf")).softmax(-1) o = p @ vd dp = dod @ vd.T ds = p * (dp - (dod * o).sum(-1, keepdim=True)) del dp res["out"][a:b, h] = o res["dv"][a:b, h] = p.T @ dod res["dq"][a:b, h] = ds @ kd * scale res["dk"][a:b, h] = ds.T @ qd * scale del p, ds return res