3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
10 ######################################################################
13 class PScan(torch.autograd.Function):
14 # Given A is NxTx1 and X is NxTxD, expands A and X in place in O(T),
15 # and O(log(T)) if not core-bounded, so that
18 # Y[:, t] = A[:, t] * Y[:, t-1] + X[:, t]
22 # Y[:, t] = A[:, t] * Y0 + X[:, t]
28 T = 2 * (A.size(1) // 2)
29 Aa = A[:, :T].view(A.size(0), T // 2, 2, -1)
30 Xa = X[:, :T].view(X.size(0), T // 2, 2, -1)
31 Xa[:, :, 1].add_(Aa[:, :, 1].mul(Xa[:, :, 0]))
32 Aa[:, :, 1].mul_(Aa[:, :, 0])
33 PScan.expand(Aa[:, :, 1], Xa[:, :, 1])
34 Xa[:, 1:, 0].add_(Aa[:, 1:, 0].mul(Xa[:, :-1, 1]))
35 Aa[:, 1:, 0].mul_(Aa[:, :-1, 1])
37 X[:, -1].add_(A[:, -1].mul(X[:, -2]))
38 A[:, -1].mul_(A[:, -2])
40 # Computes inplace Y[:, s] = \sum_{t >= s} X[:, t]
46 T = 2 * (X.size(1) // 2)
47 Xa = X[:, -T:].view(X.size(0), T // 2, 2, -1)
48 Xa[:, :, 0].add_(Xa[:, :, 1])
49 PScan.accrev(Xa[:, :, 0])
50 Xa[:, :-1, 1].add_(Xa[:, 1:, 0])
55 def forward(ctx, A, X, Y0):
56 ctx.A = A[:, :, None].clone()
57 ctx.Y0 = Y0[:, None, :].clone()
58 ctx.A_star = A[:, :, None].clone()
59 ctx.X_star = X.clone()
60 PScan.expand(ctx.A_star, ctx.X_star)
61 return ctx.A_star * ctx.Y0 + ctx.X_star
64 def backward(ctx, grad_output):
65 U = grad_output * ctx.A_star
69 Q[:, 1:].add_(ctx.X_star[:, :-1] / ctx.A_star[:, 1:])
70 return (Q * R).sum(-1), R / ctx.A_star, U.sum(dim=1)
75 ######################################################################
77 if __name__ == "__main__":
80 # Iterative implementation
82 A = torch.randn(N, T, dtype=torch.float64).requires_grad_()
83 X = torch.randn(N, T, D, dtype=torch.float64).requires_grad_()
84 Y0 = torch.randn(N, D, dtype=torch.float64).requires_grad_()
89 for k in range(A.size(1)):
90 y = A[:, k, None] * y + X[:, k]
92 # print(f"{k} -> {y}")
97 print(torch.autograd.grad(s, A, retain_graph=True))
98 print(torch.autograd.grad(s, X, retain_graph=True))
99 print(torch.autograd.grad(s, Y0, retain_graph=True))
107 # for k in range(A.size(1)):
108 # print(f"{k} -> {Y[:,k]}")
113 print(torch.autograd.grad(s, A, retain_graph=True))
114 print(torch.autograd.grad(s, X, retain_graph=True))
115 print(torch.autograd.grad(s, Y0, retain_graph=True))