Update.
[pytorch.git] / eingather.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import re, torch
9
10 #####################
11
12
13 def eingather(op, src, *indexes):
14     s_src, s_dst = re.search("^([^ ]*) *-> *(.*)", op).groups()
15     s_indexes = re.findall("\(([^)]*)\)", s_src)
16     s_src = re.sub("\([^)]*\)", "_", s_src)
17
18     all_sizes = tuple(d for s in ( src, ) + indexes for d in s.size())
19     s_all = "".join([s_src] + s_indexes)
20     shape = tuple(all_sizes[s_all.index(v)] for v in s_dst)
21
22     idx = []
23     n_index = 0
24
25     for i in range(src.dim()):
26         v = s_src[i]
27         if v == "_":
28             index, s_index = indexes[n_index], s_indexes[n_index]
29             n_index += 1
30
31             sub_idx = []
32
33             for i in range(index.dim()):
34                 v = s_index[i]
35                 j = s_dst.index(v)
36                 a = (
37                     torch.arange(index.size(i))
38                     .reshape((1,) * j + (-1,) + (1,) * (len(s_dst) - j - 1))
39                     .expand(shape)
40                 )
41                 sub_idx.append(a)
42
43             index = index[sub_idx]
44             idx.append(index)
45         else:
46             j = s_dst.index(v)
47             a = (
48                 torch.arange(src.size(i))
49                 .reshape((1,) * j + (-1,) + (1,) * (len(s_dst) - j - 1))
50                 .expand(shape)
51             )
52             idx.append(a)
53
54     return src[idx]
55
56
57 #######################
58
59 src = torch.rand(3, 5, 7, 11)
60 index1 = torch.randint(src.size(2), (src.size(3), src.size(1), src.size(3)))
61 index2 = torch.randint(src.size(3), (src.size(1),))
62
63 # I want result[a, c, e] = src[c, a, index1[e, a, e], index2[a], e]
64
65 result = eingather("ca(eae)(a) -> ace", src, index1, index2)
66
67 # Check
68
69 error = 0
70
71 for a in range(result.size(0)):
72     for c in range(result.size(1)):
73         for e in range(result.size(2)):
74             error += (result[a, c, e] - src[c, a, index1[e, a, e], index2[a]]).abs()
75
76 print(error.item())