Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

graph_encoder.py 6.8 KB

You have to be logged in to leave a comment. Sign In
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
  1. import torch
  2. import numpy as np
  3. from torch import nn
  4. import math
  5. class SkipConnection(nn.Module):
  6. def __init__(self, module):
  7. super(SkipConnection, self).__init__()
  8. self.module = module
  9. def forward(self, input):
  10. return input + self.module(input)
  11. class MultiHeadAttention(nn.Module):
  12. def __init__(
  13. self,
  14. n_heads,
  15. input_dim,
  16. embed_dim=None,
  17. val_dim=None,
  18. key_dim=None
  19. ):
  20. super(MultiHeadAttention, self).__init__()
  21. if val_dim is None:
  22. assert embed_dim is not None, "Provide either embed_dim or val_dim"
  23. val_dim = embed_dim // n_heads
  24. if key_dim is None:
  25. key_dim = val_dim
  26. self.n_heads = n_heads
  27. self.input_dim = input_dim
  28. self.embed_dim = embed_dim
  29. self.val_dim = val_dim
  30. self.key_dim = key_dim
  31. self.norm_factor = 1 / math.sqrt(key_dim) # See Attention is all you need
  32. self.W_query = nn.Parameter(torch.Tensor(n_heads, input_dim, key_dim))
  33. self.W_key = nn.Parameter(torch.Tensor(n_heads, input_dim, key_dim))
  34. self.W_val = nn.Parameter(torch.Tensor(n_heads, input_dim, val_dim))
  35. if embed_dim is not None:
  36. self.W_out = nn.Parameter(torch.Tensor(n_heads, key_dim, embed_dim))
  37. self.init_parameters()
  38. def init_parameters(self):
  39. for param in self.parameters():
  40. stdv = 1. / math.sqrt(param.size(-1))
  41. param.data.uniform_(-stdv, stdv)
  42. def forward(self, q, h=None, mask=None):
  43. """
  44. :param q: queries (batch_size, n_query, input_dim)
  45. :param h: data (batch_size, graph_size, input_dim)
  46. :param mask: mask (batch_size, n_query, graph_size) or viewable as that (i.e. can be 2 dim if n_query == 1)
  47. Mask should contain 1 if attention is not possible (i.e. mask is negative adjacency)
  48. :return:
  49. """
  50. if h is None:
  51. h = q # compute self-attention
  52. # h should be (batch_size, graph_size, input_dim)
  53. batch_size, graph_size, input_dim = h.size()
  54. n_query = q.size(1)
  55. assert q.size(0) == batch_size
  56. assert q.size(2) == input_dim
  57. assert input_dim == self.input_dim, "Wrong embedding dimension of input"
  58. hflat = h.contiguous().view(-1, input_dim)
  59. qflat = q.contiguous().view(-1, input_dim)
  60. # last dimension can be different for keys and values
  61. shp = (self.n_heads, batch_size, graph_size, -1)
  62. shp_q = (self.n_heads, batch_size, n_query, -1)
  63. # Calculate queries, (n_heads, n_query, graph_size, key/val_size)
  64. Q = torch.matmul(qflat, self.W_query).view(shp_q)
  65. # Calculate keys and values (n_heads, batch_size, graph_size, key/val_size)
  66. K = torch.matmul(hflat, self.W_key).view(shp)
  67. V = torch.matmul(hflat, self.W_val).view(shp)
  68. # Calculate compatibility (n_heads, batch_size, n_query, graph_size)
  69. compatibility = self.norm_factor * torch.matmul(Q, K.transpose(2, 3))
  70. # Optionally apply mask to prevent attention
  71. if mask is not None:
  72. mask = mask.view(1, batch_size, n_query, graph_size).expand_as(compatibility)
  73. compatibility[mask] = -np.inf
  74. attn = torch.softmax(compatibility, dim=-1)
  75. # If there are nodes with no neighbours then softmax returns nan so we fix them to 0
  76. if mask is not None:
  77. attnc = attn.clone()
  78. attnc[mask] = 0
  79. attn = attnc
  80. heads = torch.matmul(attn, V)
  81. out = torch.mm(
  82. heads.permute(1, 2, 0, 3).contiguous().view(-1, self.n_heads * self.val_dim),
  83. self.W_out.view(-1, self.embed_dim)
  84. ).view(batch_size, n_query, self.embed_dim)
  85. return out
  86. class Normalization(nn.Module):
  87. def __init__(self, embed_dim, normalization='batch'):
  88. super(Normalization, self).__init__()
  89. normalizer_class = {
  90. 'batch': nn.BatchNorm1d,
  91. 'instance': nn.InstanceNorm1d
  92. }.get(normalization, None)
  93. self.normalizer = normalizer_class(embed_dim, affine=True)
  94. # Normalization by default initializes affine parameters with bias 0 and weight unif(0,1) which is too large!
  95. # self.init_parameters()
  96. def init_parameters(self):
  97. for name, param in self.named_parameters():
  98. stdv = 1. / math.sqrt(param.size(-1))
  99. param.data.uniform_(-stdv, stdv)
  100. def forward(self, input):
  101. if isinstance(self.normalizer, nn.BatchNorm1d):
  102. return self.normalizer(input.view(-1, input.size(-1))).view(*input.size())
  103. elif isinstance(self.normalizer, nn.InstanceNorm1d):
  104. return self.normalizer(input.permute(0, 2, 1)).permute(0, 2, 1)
  105. else:
  106. assert self.normalizer is None, "Unknown normalizer type"
  107. return input
  108. class MultiHeadAttentionLayer(nn.Sequential):
  109. def __init__(
  110. self,
  111. n_heads,
  112. embed_dim,
  113. feed_forward_hidden=512,
  114. normalization='batch',
  115. ):
  116. super(MultiHeadAttentionLayer, self).__init__(
  117. SkipConnection(
  118. MultiHeadAttention(
  119. n_heads,
  120. input_dim=embed_dim,
  121. embed_dim=embed_dim
  122. )
  123. ),
  124. Normalization(embed_dim, normalization),
  125. SkipConnection(
  126. nn.Sequential(
  127. nn.Linear(embed_dim, feed_forward_hidden),
  128. nn.ReLU(),
  129. nn.Linear(feed_forward_hidden, embed_dim)
  130. ) if feed_forward_hidden > 0 else nn.Linear(embed_dim, embed_dim)
  131. ),
  132. Normalization(embed_dim, normalization)
  133. )
  134. class GraphAttentionEncoder(nn.Module):
  135. def __init__(
  136. self,
  137. n_heads,
  138. embed_dim,
  139. n_layers,
  140. node_dim=None,
  141. normalization='batch',
  142. feed_forward_hidden=512
  143. ):
  144. super(GraphAttentionEncoder, self).__init__()
  145. # To map input to embedding space
  146. self.init_embed = nn.Linear(node_dim, embed_dim) if node_dim is not None else None
  147. self.layers = nn.Sequential(*(
  148. MultiHeadAttentionLayer(n_heads, embed_dim, feed_forward_hidden, normalization)
  149. for _ in range(n_layers)
  150. ))
  151. def forward(self, x, mask=None):
  152. assert mask is None, "TODO mask not yet supported!"
  153. # Batch multiply to get initial embeddings of nodes
  154. h = self.init_embed(x.view(-1, x.size(-1))).view(*x.size()[:2], -1) if self.init_embed is not None else x
  155. h = self.layers(h)
  156. return (
  157. h, # (batch_size, graph_size, embed_dim)
  158. h.mean(dim=1), # average to get embedding of graph, (batch_size, embed_dim)
  159. )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...