summaryrefslogtreecommitdiff
path: root/tests/test_ref.py
diff options
context:
space:
mode:
Diffstat (limited to 'tests/test_ref.py')
-rw-r--r--tests/test_ref.py23
1 files changed, 23 insertions, 0 deletions
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()