-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_overlap.py
More file actions
32 lines (26 loc) · 842 Bytes
/
test_overlap.py
File metadata and controls
32 lines (26 loc) · 842 Bytes
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
import torch
def matmul(w, o):
return torch.matmul(w, o)
def scale(o, o_l):
if o_l is None:
return o
return o - o_l.mean(dim=-1, keepdim=True)
class OpLinear(torch.autograd.Function):
@staticmethod
def forward(ctx, w, o):
ctx.save_for_backward(w, o)
return matmul(w, o)
@staticmethod
def backward(ctx, grad_o):
w, o = ctx.saved_tensors
grad_w = torch.matmul(grad_o, o.t())
grad_o = torch.matmul(w.t(), grad_o)
return grad_w, grad_o
if __name__ == "__main__":
w = torch.rand(4, 4096, 4096, device="cuda", requires_grad=True)
o = torch.rand(4, 4096, 4096, device="cuda", requires_grad=True)
with torch.no_grad():
res = OpLinear.apply(w, o)
with torch.enable_grad():
res = OpLinear.apply(w, o)
res.sum().backward()