-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathsparse_graph_model.py
259 lines (209 loc) · 9.75 KB
/
sparse_graph_model.py
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# Copyright 2018 AimBrain Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence
from layers import NeighbourhoodGraphConvolution as GraphConvolution
from layers import GraphLearner
class Model(nn.Module):
def __init__(self,
vocab_size,
emb_dim,
feat_dim,
hid_dim,
out_dim,
pretrained_wemb,
dropout,
n_kernels=8,
neighbourhood_size=16):
'''
## Variables:
- vocab_size: dimensionality of input vocabulary
- emb_dim: question embedding size
- feat_dim: dimensionality of input image features
- out_dim: dimensionality of the output
- dropout: dropout probability
- n_kernels : number of Gaussian kernels for convolutions
- bias: whether to add a bias to Gaussian kernels
'''
super(Model, self).__init__()
# Set parameters
self.vocab_size = vocab_size
self.emb_dim = emb_dim
self.feat_dim = feat_dim
self.hid_dim = hid_dim
self.out_dim = out_dim
self.neighbourhood_size = neighbourhood_size
# initialize word embedding layer weight
self.wembed = nn.Embedding(vocab_size, emb_dim)
self.wembed.weight.data.copy_(torch.from_numpy(pretrained_wemb))
# question encoding
self.q_lstm = nn.GRU(input_size=emb_dim, hidden_size=hid_dim)
# graph learner
self.adjacency_1 = GraphLearner(in_feature_dim=feat_dim + hid_dim,
combined_feature_dim=512,
K=36,
dropout=dropout)
# dropout layers
self.dropout = nn.Dropout(p=dropout)
self.dropout_q = nn.Dropout(p=dropout/2)
# graph convolution layers
self.graph_convolution_1 = \
GraphConvolution(feat_dim, hid_dim * 2, n_kernels, 2)
self.graph_convolution_2 = \
GraphConvolution(hid_dim * 2, hid_dim, n_kernels, 2)
# output classifier
self.out_1 = nn.utils.weight_norm(nn.Linear(hid_dim, out_dim))
self.out_2 = nn.utils.weight_norm(nn.Linear(out_dim, out_dim))
def forward(self, question, image, K, qlen):
'''
## Inputs:
- question (batch_size, max_qlen): input tokenised question
- image (batch_size, K, feat_dim): input image features
- K (int): number of image features/objects in the image
- qlen (batch_size): vector describing the length (in words) of each input question
## Returns:
- logits (batch_size, out_dim)
'''
K = int(K[0].cpu().data.numpy())
# extract bounding boxes and compute centres
bb = image[:, :, -4:].contiguous()
bb_size = (bb[:, :, 2:]-bb[:, :, :2])
bb_centre = bb[:, :, :2] + 0.5*bb_size
# apply dropout to image features
image = self.dropout(image)
# Compute pseudo coordinates
pseudo_coord = self._compute_pseudo(bb_centre)
# Compute question encoding
emb = self.wembed(question)
packed = pack_padded_sequence(emb, qlen, batch_first=True) # questions have variable lengths
_, hid = self.q_lstm(packed)
qenc = hid[0].unsqueeze(1)
qenc_repeat = qenc.repeat(1, K, 1)
# Learn adjacency matrix
image_qenc_cat = torch.cat((image, qenc_repeat), dim=-1)
adjacency_matrix = self.adjacency_1(image_qenc_cat)
# Graph convolution 1
neighbourhood_image, neighbourhood_pseudo = self._create_neighbourhood(image,
pseudo_coord,
adjacency_matrix,
self.neighbourhood_size,
weight=True)
hidden_graph_1 = self.graph_convolution_1(
neighbourhood_image, neighbourhood_pseudo)
hidden_graph_1 = F.relu(hidden_graph_1)
hidden_graph_1 = self.dropout(hidden_graph_1)
# graph convolution 2
hidden_graph_1, neighbourhood_pseudo = self._create_neighbourhood(hidden_graph_1,
pseudo_coord,
adjacency_matrix,
self.neighbourhood_size,
weight=False)
hidden_graph_2 = self.graph_convolution_2(
hidden_graph_1, neighbourhood_pseudo)
hidden_graph_2 = F.relu(hidden_graph_2)
hidden_graph_2, _ = torch.max(hidden_graph_2, dim=1)
h = F.relu(qenc).squeeze(1)*hidden_graph_2
# Output classifier
hidden_1 = self.out_1(h)
hidden_1 = F.relu(hidden_1)
hidden_1 = self.dropout(hidden_1)
logits = self.out_2(hidden_1)
return logits, adjacency_matrix
def _create_neighbourhood_feat(self, image, top_ind):
'''
## Inputs:
- image (batch_size, K, feat_dim)
- top_ind (batch_size, K, neighbourhood_size)
## Returns:
- neighbourhood_image (batch_size, K, neighbourhood_size, feat_dim)
'''
batch_size = image.size(0)
K = image.size(1)
feat_dim = image.size(2)
neighbourhood_size = top_ind.size(-1)
image = image.unsqueeze(1).expand(batch_size, K, K, feat_dim)
idx = top_ind.unsqueeze(-1).expand(batch_size,
K, neighbourhood_size, feat_dim)
return torch.gather(image, dim=2, index=idx)
def _create_neighbourhood_pseudo(self, pseudo, top_ind):
'''
## Inputs:
- pseudo_coord (batch_size, K, K, coord_dim)
- top_ind (batch_size, K, neighbourhood_size)
## Returns:
- neighbourhood_pseudo (batch_size, K, neighbourhood_size, coord_dim)
'''
batch_size = pseudo.size(0)
K = pseudo.size(1)
coord_dim = pseudo.size(3)
neighbourhood_size = top_ind.size(-1)
idx = top_ind.unsqueeze(-1).expand(batch_size,
K, neighbourhood_size, coord_dim)
return torch.gather(pseudo, dim=2, index=idx)
def _create_neighbourhood(self,
features,
pseudo_coord,
adjacency_matrix,
neighbourhood_size,
weight=True):
'''
Creates a neighbourhood system for each graph node/image object
## Inputs:
- features (batch_size, K, feat_dim): input image features
- pseudo_coord (batch_size, K, K, coord_dim): pseudo coordinates for graph convolutions
- adjacency_matrix (batch_size, K, K): learned adjacency matrix
- neighbourhood_size (int)
- weight (bool): specify if the features should be weighted by the adjacency matrix values
## Returns:
- neighbourhood_image (batch_size, K, neighbourhood_size, feat_dim)
- neighbourhood_pseudo (batch_size, K, neighbourhood_size, coord_dim)
'''
# Number of graph nodes
K = features.size(1)
# extract top k neighbours for each node and normalise
top_k, top_ind = torch.topk(
adjacency_matrix, k=neighbourhood_size, dim=-1, sorted=False)
top_k = torch.stack([F.softmax(top_k[:, k]) for k in range(K)]).transpose(0, 1) # (batch_size, K, neighbourhood_size)
# extract top k features and pseudo coordinates
neighbourhood_image = \
self._create_neighbourhood_feat(features, top_ind)
neighbourhood_pseudo = \
self._create_neighbourhood_pseudo(pseudo_coord, top_ind)
# weight neighbourhood features with graph edge weights
if weight:
neighbourhood_image = top_k.unsqueeze(-1)*neighbourhood_image
return neighbourhood_image, neighbourhood_pseudo
def _compute_pseudo(self, bb_centre):
'''
Computes pseudo-coordinates from bounding box centre coordinates
## Inputs:
- bb_centre (batch_size, K, coord_dim)
- polar (bool: polar or euclidean coordinates)
## Returns:
- pseudo_coord (batch_size, K, K, coord_dim)
'''
K = bb_centre.size(1)
# Compute cartesian coordinates (batch_size, K, K, 2)
pseudo_coord = bb_centre.view(-1, K, 1, 2) - \
bb_centre.view(-1, 1, K, 2)
# Conver to polar coordinates
rho = torch.sqrt(
pseudo_coord[:, :, :, 0]**2 + pseudo_coord[:, :, :, 1]**2)
theta = torch.atan2(
pseudo_coord[:, :, :, 0], pseudo_coord[:, :, :, 1])
pseudo_coord = torch.cat(
(torch.unsqueeze(rho, -1), torch.unsqueeze(theta, -1)), dim=-1)
return pseudo_coord