File size: 2,872 Bytes
bbd7f1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""TransformerEngine DotProductAttention (cuDNN fused, thd, head_dim 256, bf16) fwd/bwd at the
training sequence lengths vs an fp32 SDPA reference. DPA returns [T, H*D]."""
import torch

print("torch", torch.__version__, "| device", torch.cuda.get_device_name(0), flush=True)
import transformer_engine.pytorch as te
from transformer_engine.pytorch.attention import DotProductAttention
print("TE", getattr(te, "__version__", "?"), flush=True)
dev = "cuda"
torch.manual_seed(0)


def bad(t):
    return bool(torch.isnan(t).any() or torch.isinf(t).any())


def rel(a, b):
    return ((a.float() - b.float()).abs().max() / b.float().abs().max().clamp_min(1e-6)).item()


H, Hkv, D = 6, 1, 256   # per TP rank of 4: 24/4 heads, 4/4 kv heads
for Tl in ([400, 300], [4000, 3500], [8700, 9100, 400], [12288], [9000, 3200, 80, 8]):
    try:
        T = sum(Tl)
        cu = torch.tensor([0] + list(torch.cumsum(torch.tensor(Tl), 0)), dtype=torch.int32, device=dev)
        dpa = DotProductAttention(num_attention_heads=H, kv_channels=D, num_gqa_groups=Hkv, attention_dropout=0.0,
                                  qkv_format="thd", attn_mask_type="padding_causal").to(dev)
        q = torch.randn(T, H, D, device=dev, dtype=torch.bfloat16, requires_grad=True)
        k = torch.randn(T, Hkv, D, device=dev, dtype=torch.bfloat16, requires_grad=True)
        v = torch.randn(T, Hkv, D, device=dev, dtype=torch.bfloat16, requires_grad=True)
        out = dpa(q, k, v, cu_seqlens_q=cu, cu_seqlens_kv=cu, max_seqlen_q=max(Tl), max_seqlen_kv=max(Tl))
        out = out.view(T, H, D)
        do = torch.randn_like(out)
        (out * do).sum().backward()
        fused = {n: t.grad.detach().clone() for n, t in (("q", q), ("k", k), ("v", v))}
        print(f"TE fused thd hd256 T={T} seqs={Tl}: out nan/inf {bad(out)} | grad nan/inf", {n: bad(t) for n, t in fused.items()}, flush=True)
        for t in (q, k, v):
            t.grad = None
        ref_out = []
        for i in range(len(Tl)):
            s, e = int(cu[i]), int(cu[i + 1])
            qi = q[s:e].float().transpose(0, 1)                    # [H, L, D]
            ki = k[s:e].float().transpose(0, 1).expand(H, -1, -1)
            vi = v[s:e].float().transpose(0, 1).expand(H, -1, -1)
            oi = torch.nn.functional.scaled_dot_product_attention(qi, ki, vi, is_causal=True)
            ref_out.append(oi.transpose(0, 1))
        ref = torch.cat(ref_out, dim=0)
        (ref * do.float()).sum().backward()
        print(f"   fwd rel err {rel(out, ref):.3e} | grad rel err " + ", ".join(f"{n}={rel(fused[n], t.grad):.3e}" for n, t in (("q", q), ("k", k), ("v", v))), flush=True)
        del q, k, v, out, do, fused, ref, dpa
        torch.cuda.empty_cache()
    except Exception as exc:  # noqa: BLE001
        print(f"   case {Tl} failed: {type(exc).__name__}: {str(exc)[:300]}", flush=True)
print("DONE", flush=True)