-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.py
385 lines (296 loc) · 13.7 KB
/
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from util import quat2mat, invariant_coordinates_pca_chamfer
from UME import horn_for_ume, ume_no_indicators
# Part of the code is referred from: https://github.com/WangYueFt/dcp
def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
def attention(query, key, value, mask=None, dropout=None):
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1).contiguous()) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
p_attn = F.softmax(scores, dim=-1)
return torch.matmul(p_attn, value), p_attn
def nearest_neighbor(src, dst):
inner = -2 * torch.matmul(src.transpose(1, 0).contiguous(), dst) # src, dst (num_dims, num_points)
distances = -torch.sum(src ** 2, dim=0, keepdim=True).transpose(1, 0).contiguous() - inner - torch.sum(dst ** 2,
dim=0,
keepdim=True)
distances, indices = distances.topk(k=1, dim=-1)
return distances, indices
def knn(x, k):
inner = -2 * torch.matmul(x.transpose(2, 1).contiguous(), x)
xx = torch.sum(x ** 2, dim=1, keepdim=True)
pairwise_distance = -xx - inner - xx.transpose(2, 1).contiguous()
idx = pairwise_distance.topk(k=k, dim=-1)[1] # (batch_size, num_points, k)
return idx
def get_graph_feature(x, k=20):
# x = x.squeeze()
idx = knn(x, k=k) # (batch_size, num_points, k)
batch_size, num_points, _ = idx.size()
device = torch.device('cuda')
idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points
idx = idx + idx_base
idx = idx.view(-1)
_, num_dims, _ = x.size()
x = x.transpose(2,
1).contiguous() # (batch_size, num_points, num_dims) -> (batch_size*num_points, num_dims) # batch_size * num_points * k + range(0, batch_size*num_points)
feature = x.view(batch_size * num_points, -1)[idx, :]
feature = feature.view(batch_size, num_points, k, num_dims)
x = x.view(batch_size, num_points, 1, num_dims).repeat(1, 1, k, 1)
feature = torch.cat((feature, x), dim=3).permute(0, 3, 1, 2).contiguous()
return feature
class EncoderDecoder(nn.Module):
"""
A standard Encoder-Decoder architecture. Base for this and many
other models.
"""
def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):
super(EncoderDecoder, self).__init__()
self.encoder = encoder
self.decoder = decoder
self.src_embed = src_embed
self.tgt_embed = tgt_embed
self.generator = generator
def forward(self, src, tgt, src_mask, tgt_mask):
"Take in and process masked src and target sequences."
return self.decode(self.encode(src, src_mask), src_mask,
tgt, tgt_mask)
def encode(self, src, src_mask):
return self.encoder(self.src_embed(src), src_mask)
def decode(self, memory, src_mask, tgt, tgt_mask):
return self.generator(self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask))
class Generator(nn.Module):
def __init__(self, emb_dims):
super(Generator, self).__init__()
self.nn = nn.Sequential(nn.Linear(emb_dims, emb_dims // 2),
nn.BatchNorm1d(emb_dims // 2),
nn.ReLU(),
nn.Linear(emb_dims // 2, emb_dims // 4),
nn.BatchNorm1d(emb_dims // 4),
nn.ReLU(),
nn.Linear(emb_dims // 4, emb_dims // 8),
nn.BatchNorm1d(emb_dims // 8),
nn.ReLU())
self.proj_rot = nn.Linear(emb_dims // 8, 4)
self.proj_trans = nn.Linear(emb_dims // 8, 3)
def forward(self, x):
x = self.nn(x.max(dim=1)[0])
rotation = self.proj_rot(x)
translation = self.proj_trans(x)
rotation = rotation / torch.norm(rotation, p=2, dim=1, keepdim=True)
return rotation, translation
class Encoder(nn.Module):
def __init__(self, layer, N):
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, mask):
for layer in self.layers:
x = layer(x, mask)
return self.norm(x)
class Decoder(nn.Module):
"Generic N layer decoder with masking."
def __init__(self, layer, N):
super(Decoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, memory, src_mask, tgt_mask):
for layer in self.layers:
x = layer(x, memory, src_mask, tgt_mask)
return self.norm(x)
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
class SublayerConnection(nn.Module):
def __init__(self, size, dropout=None):
super(SublayerConnection, self).__init__()
self.norm = LayerNorm(size)
def forward(self, x, sublayer):
return x + sublayer(self.norm(x))
class EncoderLayer(nn.Module):
def __init__(self, size, self_attn, feed_forward, dropout):
super(EncoderLayer, self).__init__()
self.self_attn = self_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 2)
self.size = size
def forward(self, x, mask):
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward)
class DecoderLayer(nn.Module):
"Decoder is made of self-attn, src-attn, and feed forward (defined below)"
def __init__(self, size, self_attn, src_attn, feed_forward, dropout):
super(DecoderLayer, self).__init__()
self.size = size
self.self_attn = self_attn
self.src_attn = src_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 3)
def forward(self, x, memory, src_mask, tgt_mask):
"Follow Figure 1 (right) for connections."
m = memory
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))
x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))
return self.sublayer[2](x, self.feed_forward)
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
"Take in model size and number of heads."
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
# We assume d_v always equals d_k
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = None
def forward(self, query, key, value, mask=None):
"Implements Figure 2"
if mask is not None:
# Same mask applied to all h heads.
mask = mask.unsqueeze(1)
nbatches = query.size(0)
# 1) Do all the linear projections in batch from d_model => h x d_k
query, key, value = \
[l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2).contiguous()
for l, x in zip(self.linears, (query, key, value))]
# 2) Apply attention on all the projected vectors in batch.
x, self.attn = attention(query, key, value, mask=mask,
dropout=self.dropout)
# 3) "Concat" using a view and apply a final linear.
x = x.transpose(1, 2).contiguous() \
.view(nbatches, -1, self.h * self.d_k)
return self.linears[-1](x)
class PositionwiseFeedForward(nn.Module):
"Implements FFN equation."
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.norm = nn.Sequential() # nn.BatchNorm1d(d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
self.dropout = None
def forward(self, x):
return self.w_2(self.norm(F.relu(self.w_1(x)).transpose(2, 1).contiguous()).transpose(2, 1).contiguous())
class Transformer(nn.Module):
def __init__(self, args):
super(Transformer, self).__init__()
self.emb_dims = args.emb_dims
self.N = args.n_blocks
self.dropout = args.dropout
self.ff_dims = args.ff_dims
self.n_heads = args.n_heads
c = copy.deepcopy
attn = MultiHeadedAttention(self.n_heads, self.emb_dims)
ff = PositionwiseFeedForward(self.emb_dims, self.ff_dims, self.dropout)
self.model = EncoderDecoder(Encoder(EncoderLayer(self.emb_dims, c(attn), c(ff), self.dropout), self.N),
Decoder(DecoderLayer(self.emb_dims, c(attn), c(attn), c(ff), self.dropout), self.N),
nn.Sequential(),
nn.Sequential(),
nn.Sequential())
def forward(self, *input):
src = input[0]
tgt = input[1]
src = src.transpose(2, 1).contiguous()
tgt = tgt.transpose(2, 1).contiguous()
tgt_embedding = self.model(src, tgt, None, None).transpose(2, 1).contiguous()
src_embedding = self.model(tgt, src, None, None).transpose(2, 1).contiguous()
return src_embedding, tgt_embedding
class DGCNN(nn.Module):
def __init__(self, emb_dims=512):
super(DGCNN, self).__init__()
self.conv1 = nn.Conv2d(6, 64, kernel_size=1, bias=False)
self.conv2 = nn.Conv2d(64, 64, kernel_size=1, bias=False)
self.conv3 = nn.Conv2d(64, 128, kernel_size=1, bias=False)
self.conv4 = nn.Conv2d(128, 256, kernel_size=1, bias=False)
self.conv5 = nn.Conv2d(512, emb_dims, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.bn2 = nn.BatchNorm2d(64)
self.bn3 = nn.BatchNorm2d(128)
self.bn4 = nn.BatchNorm2d(256)
self.bn5 = nn.BatchNorm2d(emb_dims)
def forward(self, x):
batch_size, num_dims, num_points = x.size()
x = get_graph_feature(x)
x = F.relu(self.bn1(self.conv1(x)))
x1 = x.max(dim=-1, keepdim=True)[0]
x = F.relu(self.bn2(self.conv2(x)))
x2 = x.max(dim=-1, keepdim=True)[0]
x = F.relu(self.bn3(self.conv3(x)))
x3 = x.max(dim=-1, keepdim=True)[0]
x = F.relu(self.bn4(self.conv4(x)))
x4 = x.max(dim=-1, keepdim=True)[0]
x = torch.cat((x1, x2, x3, x4), dim=1)
x = F.relu(self.bn5(self.conv5(x))).view(batch_size, -1, num_points)
return x
class MLPHead(nn.Module):
def __init__(self, args):
super(MLPHead, self).__init__()
emb_dims = args.emb_dims
self.emb_dims = emb_dims
self.nn = nn.Sequential(nn.Linear(emb_dims * 2, emb_dims // 2),
nn.BatchNorm1d(emb_dims // 2),
nn.ReLU(),
nn.Linear(emb_dims // 2, emb_dims // 4),
nn.BatchNorm1d(emb_dims // 4),
nn.ReLU(),
nn.Linear(emb_dims // 4, emb_dims // 8),
nn.BatchNorm1d(emb_dims // 8),
nn.ReLU())
self.proj_rot = nn.Linear(emb_dims // 8, 4)
self.proj_trans = nn.Linear(emb_dims // 8, 3)
def forward(self, *input):
src_embedding = input[0]
tgt_embedding = input[1]
embedding = torch.cat((src_embedding, tgt_embedding), dim=1)
embedding = self.nn(embedding.max(dim=-1)[0])
rotation = self.proj_rot(embedding)
rotation = rotation / torch.norm(rotation, p=2, dim=1, keepdim=True)
translation = self.proj_trans(embedding)
return quat2mat(rotation), translation
class UMEHead(nn.Module):
def __init__(self):
super(UMEHead, self).__init__()
def forward(self, src_embedding, tgt_embedding,
src, tgt,
src_mass=None, tgt_mass=None):
return horn_for_ume(src, ume_no_indicators(src, src_embedding),
tgt, ume_no_indicators(tgt, tgt_embedding),
src_mass, tgt_mass)
class DeepUME(nn.Module):
def __init__(self, args):
super(DeepUME, self).__init__()
self.pointer2 = Transformer(args=args)
self.emb_nn = DGCNN()
self.head = UMEHead()
def forward(self, *input):
src = input[0]
tgt = input[1]
# inv cords
src_inv_cords, src_axes, src_mass, \
tgt_inv_cords, tgt_axes, tgt_mass = invariant_coordinates_pca_chamfer(src, tgt)
# sampling
src_cords_p, tgt_cords_p = self.pointer2(src_inv_cords, tgt_inv_cords)
src_inv_cords = src_inv_cords + src_cords_p
tgt_inv_cords = tgt_inv_cords + tgt_cords_p
# embedding
src_embedding = self.emb_nn(src_inv_cords)
tgt_embedding = self.emb_nn(tgt_inv_cords)
# re-projection
src = torch.matmul(src_axes, src_inv_cords)
tgt = torch.matmul(tgt_axes, tgt_inv_cords)
# parameters estimation
rotation_perd, translation_perd = self.head(src_embedding, tgt_embedding, src, tgt, src_mass, tgt_mass)
return rotation_perd, translation_perd