summaryrefslogtreecommitdiff
path: root/tests/_ref.py
blob: 36ddd2738f2f3fa2917f6b819cd5084922feb2ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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()