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
|
import unittest
import torch
from _ref import device, select, usable
def canon_inputs(B=2, T=1024, doc_starts=(0, 300, 301, 777), dev=None, seed=0):
"""qkv (B,T,1536) fp16, canon_w (1536,3) fp32, document masks and RoPE tables."""
g = torch.Generator().manual_seed(seed)
qkv = torch.randn(B, T, 1536, generator=g).to(dev, torch.float16)
w = (0.1 * torch.randn(1536, 3, generator=g)).to(dev)
start = torch.zeros(B, T, dtype=torch.bool)
start[:, list(doc_starts)] = True
first2 = start.clone()
first2[:, 1:] |= start[:, :-1]
m1 = (~start).float()[:, :, None].to(dev) # is t-1 in this document?
m2 = (~first2).float()[:, :, None].to(dev) # is t-2?
pos = torch.arange(T, dtype=torch.float32)
ang = pos[:, None] * (10000.0 ** (-torch.arange(32) / 32))[None]
cos, sin = (f(ang)[None].expand(B, T, 32).contiguous().to(dev) for f in (torch.cos, torch.sin))
return qkv, w, m1, m2, cos, sin
@unittest.skipIf(usable(device()), usable(device()) or "")
class TestCanonRope(unittest.TestCase):
@classmethod
def setUpClass(cls):
select(device())
def test_canon_rope_matches_reference(self):
from volta_kernels.canon_rope import canon_rope
from volta_kernels.canon_rope_bw import ext
qkv, w, m1, m2, cos, sin = canon_inputs(dev=device())
ref = canon_rope(qkv, w, m1, m2, cos, sin)
N = qkv.shape[0] * qkv.shape[1]
ours = ext.fwd(qkv, w.contiguous(), m1.reshape(N).contiguous(), m2.reshape(N).contiguous(),
cos.reshape(N, 32).contiguous(), sin.reshape(N, 32).contiguous(), 4, 64, 4, 1)
for name, a, b in zip("qkv", ours, ref):
self.assertTrue(torch.equal(a.reshape(b.shape), b), f"{name} differs from the Triton reference")
if __name__ == "__main__":
unittest.main()
|