-
Notifications
You must be signed in to change notification settings - Fork 21
/
crw.py
262 lines (203 loc) · 7.89 KB
/
crw.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
"""
Inference routines from Jabri et al., (2020)
Credit: https://github.com/ajabri/videowalk.git
License: MIT
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
class CRW(object):
"""Propagation algorithm"""
def __init__(self, cfg):
self.n_context = cfg.CXT_SIZE
self.radius = cfg.RADIUS
self.temperature = cfg.TEMP
self.topk = cfg.KNN
print("Inference Opts:")
print("Context size: {}".format(self.n_context))
print(" Radius: {}".format(self.radius))
print(" Temp: {}".format(self.temperature))
print(" TopK: {}".format(self.topk))
# always keeping the first frame
# TODO: move to cfg
self.long_mem = [0]
# for bwd-compatibility
self.norm_mask = False
self.mask = None
self.mask_hw = None
def _prep_context(self, feats, lbls, hw):
"""Adjust for context
Args:
lbls: [N,M,H,W]
"""
lbls = F.interpolate(lbls, hw, mode="bilinear", align_corners=True)
ref = lbls[:1].expand(self.n_context,-1,-1,-1)
lbls = torch.cat([ref, lbls], 0)
fref = feats[:1].expand(self.n_context,-1,-1,-1)
fref = torch.cat([fref, feats], 0)
return fref, lbls
def forward(self, feats, lbls):
"""Propagate features
Args:
feats: [N,K,h,w]
lbls: [N,M,H,W]
"""
N,K,h,w = feats.shape
M,H,W = lbls.shape[-3:]
feats, lbls = self._prep_context(feats, lbls, (h,w))
# [N,K,h,w] -> [1,K,N,h,w]
feats = feats.permute([1,0,2,3])
# singleton for compatibility
feats = feats[None,...]
# [BC+N,M,h,w] -> [BC+N,h,w,M]
lbls = lbls.permute([0,2,3,1])
n_context = self.n_context
torch.cuda.empty_cache()
# Prepare source (keys) and target (query) frame features
key_indices = context_index_bank(n_context, self.long_mem, N)
key_indices = torch.cat(key_indices, dim=-1)
keys = feats[:, :, key_indices]
query = feats[:, :, n_context:]
# Make spatial radius mask TODO use torch.sparse
if self.mask is None or self.mask_hw != (h, w):
restrict = MaskedAttention(self.radius, flat=False)
D = restrict.mask(h, w)[None]
D = D.flatten(-4, -3).flatten(-2)
D[D==0] = -1e10; D[D==1] = 0
self.mask = D.cuda()
self.mask_hw = (h, w)
# Flatten source frame features to make context feature set
keys, query = keys.flatten(-2), query.flatten(-2)
Ws, Is = mem_efficient_batched_affinity(query, keys, self.mask, \
self.temperature, self.topk, self.long_mem)
##################################################################
# Propagate Labels and Save Predictions
###################################################################
masks_idx = torch.LongTensor(N,H,W)
masks_prob = torch.FloatTensor(N,H,W)
for t in range(key_indices.shape[0]):
# Soft labels of source nodes
ctx_lbls = lbls[key_indices[t]].cuda()
ctx_lbls = ctx_lbls.flatten(0, 2).transpose(0, 1)
# Weighted sum of top-k neighbours (Is is index, Ws is weight)
pred = (ctx_lbls[:, Is[t]] * Ws[t][None].cuda()).sum(1)
pred = pred.view(-1, h, w)
pred = pred.permute(1,2,0)
if t > 0:
lbls[t + n_context] = pred
else:
pred = lbls[0]
lbls[t + n_context] = pred
if self.norm_mask:
pred[:, :, :] -= pred.min(-1)[0][:, :, None]
pred[:, :, :] /= pred.max(-1)[0][:, :, None]
# Adding Predictions
pred_ = pred.permute([2,0,1])[None, ...]
pred_up = F.interpolate(pred_, (H,W), mode="bilinear", align_corners=True)
pred_up = pred_up[0].cpu()
masks_idx[t] = pred_up.argmax(0)
masks_prob[t] = pred_up[1]
out = {}
out["masks_pred_idx"] = masks_idx
out["masks_pred_conf"] = masks_prob
return out
def context_index_bank(n_context, long_mem, N):
'''
Construct bank of source frames indices, for each target frame
'''
ll = [] # "long term" context (i.e. first frame)
for t in long_mem:
assert 0 <= t < N, 'context frame out of bounds'
idx = torch.zeros(N, 1).long()
if t > 0:
idx += t + (n_context+1)
idx[:n_context+t+1] = 0
ll.append(idx)
# "short" context
ss = [(torch.arange(n_context)[None].repeat(N, 1) + torch.arange(N)[:, None])[:, :]]
return ll + ss
def batched_affinity(query, keys, mask, temperature, topk, long_mem, device):
'''
Mini-batched computation of affinity, for memory efficiency
(less aggressively mini-batched)
'''
A = torch.einsum('ijklm,ijkn->iklmn', keys, query)
# Mask
A[0, :, len(long_mem):] += mask.to(device)
_, N, T, h1w1, hw = A.shape
A = A.view(N, T*h1w1, hw)
A /= temperature
weights, ids = torch.topk(A, topk, dim=-2)
weights = F.softmax(weights, dim=-2)
Ws = [w for w in weights]
Is = [ii for ii in ids]
return Ws, Is
def mem_efficient_batched_affinity(query, keys, mask, temperature, topk, long_mem):
'''
Mini-batched computation of affinity, for memory efficiency
'''
bsize, pbsize = 2, 100
Ws, Is = [], []
for b in range(0, keys.shape[2], bsize):
_k, _q = keys[:, :, b:b+bsize].cuda(), query[:, :, b:b+bsize].cuda()
w_s, i_s = [], []
for pb in range(0, _k.shape[-1], pbsize):
A = torch.einsum('ijklm,ijkn->iklmn', _k, _q[..., pb:pb+pbsize])
A[0, :, len(long_mem):] += mask[..., pb:pb+pbsize]
_, N, T, h1w1, hw = A.shape
A = A.view(N, T*h1w1, hw)
A /= temperature
weights, ids = torch.topk(A, topk, dim=-2)
weights = F.softmax(weights, dim=-2)
w_s.append(weights)
i_s.append(ids)
weights = torch.cat(w_s, dim=-1)
ids = torch.cat(i_s, dim=-1)
Ws += [w for w in weights]
Is += [ii for ii in ids]
return Ws, Is
class MaskedAttention(nn.Module):
'''
A module that implements masked attention based on spatial locality
TODO implement in a more efficient way (torch sparse or correlation filter)
'''
def __init__(self, radius, flat=True):
super(MaskedAttention, self).__init__()
self.radius = radius
self.flat = flat
self.masks = {}
self.index = {}
def mask(self, H, W):
if not ('%s-%s' %(H,W) in self.masks):
self.make(H, W)
return self.masks['%s-%s' %(H,W)]
def index(self, H, W):
if not ('%s-%s' %(H,W) in self.index):
self.make_index(H, W)
return self.index['%s-%s' %(H,W)]
def make(self, H, W):
if self.flat:
H = int(H**0.5)
W = int(W**0.5)
gx, gy = torch.meshgrid(torch.arange(0, H), torch.arange(0, W))
D = ( (gx[None, None, :, :] - gx[:, :, None, None])**2 + (gy[None, None, :, :] - gy[:, :, None, None])**2 ).float() ** 0.5
D = (D < self.radius)[None].float()
if self.flat:
D = self.flatten(D)
self.masks['%s-%s' %(H,W)] = D
return D
def flatten(self, D):
return torch.flatten(torch.flatten(D, 1, 2), -2, -1)
def make_index(self, H, W, pad=False):
mask = self.mask(H, W).view(1, -1).byte()
idx = torch.arange(0, mask.numel())[mask[0]][None]
self.index['%s-%s' %(H,W)] = idx
return idx
def forward(self, x):
H, W = x.shape[-2:]
sid = '%s-%s' % (H,W)
if sid not in self.masks:
self.masks[sid] = self.make(H, W).to(x.device)
mask = self.masks[sid]
return x * mask[0]