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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
"""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, 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
|