diff options
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/_ref.py | 25 | ||||
| -rw-r--r-- | tests/test_ref.py | 23 |
2 files changed, 48 insertions, 0 deletions
diff --git a/tests/_ref.py b/tests/_ref.py index 17834fa..dc8626b 100644 --- a/tests/_ref.py +++ b/tests/_ref.py @@ -61,3 +61,28 @@ def sdpa_stock(q, k, v, offsets, seqlens=None): 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 diff --git a/tests/test_ref.py b/tests/test_ref.py new file mode 100644 index 0000000..5024971 --- /dev/null +++ b/tests/test_ref.py @@ -0,0 +1,23 @@ +import unittest + +import torch + +from _ref import attention_fp64, attention_fp64_grads, device, packed_qkv, select, usable + + +@unittest.skipIf(usable(device()), usable(device()) or "") +class TestReference(unittest.TestCase): + def test_manual_backward_matches_autograd(self): + select(device()) + q, k, v, off = packed_qkv([200, 1, 77], dev=device()) + do = torch.randn_like(q) + m = attention_fp64_grads(q, k, v, off, do) + leaves = [t.double().requires_grad_() for t in (q, k, v)] + o = attention_fp64(*leaves, off) + o.backward(do.double()) + for name, want in (("out", o), ("dq", leaves[0].grad), ("dk", leaves[1].grad), ("dv", leaves[2].grad)): + self.assertLess(((m[name] - want).norm() / want.norm()).item(), 1e-12, name) + + +if __name__ == "__main__": + unittest.main() |
