-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathslidingchunk_2d.py
368 lines (337 loc) · 15.2 KB
/
slidingchunk_2d.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
# Copyright (c) 2021 Microsoft Corporation. Licensed under the MIT license.
# Written by Pengchuan Zhang, [email protected]
# See https://github.com/microsoft/vision-longformer/blob/main/Implementation.md
# for an intuitive explanation of the implementation
from functools import lru_cache
import torch
from torch import einsum
from torch.cuda.amp import autocast
class SlidingChunk2D(torch.autograd.Function):
"""
Class to encapsulate for sliding chunk implementation of vision longformer
"""
mode_dict = {
1: (1, 1), # -1, -1
2: (1, 0), # -1, 0
3: (1, -1), # -1, 1
4: (0, 1), # 0, -1
5: (0, -1), # 0, 1
6: (-1, 1), # 1, -1
7: (-1, 0), # 1, 0
8: (-1, -1), # 1, 1
}
@staticmethod
def slidingchunk_qk(q_img: torch.Tensor, k_img: torch.Tensor, mode: int):
'''
q_img x k_img = attn11 ==> Useful for query x key = attention_scores
The cyclic padding strategy
q_img, k_img: (B * H, M, mx, my, W**2)
attn11: (B*H, mx, my, W**2, 9*W**2), mode=0
(B*H, mx, my, W**2, W**2), mode=-1
(B*H, mx, my, W**2, 2*W**2), mode=i>0
mode: 0 -> full, -1 -> only self, i (>0) -> self+block_i
'''
if mode == 0:
return torch.cat([
# -1, -1
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=(1, 1), dims=(2, 3))),
# -1, 0
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=1, dims=2)),
# -1, 1
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=(1, -1), dims=(2, 3))),
# 0, -1
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=1, dims=3)),
# 0, 0
einsum('b c m n l, b c m n t -> b m n l t', q_img,
k_img),
# 0, 1
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=-1, dims=3)),
# 1, -1
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=(-1, 1), dims=(2, 3))),
# 1, 0
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=-1, dims=2)),
# 1, 1
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=(-1, -1), dims=(2, 3))),
], dim=-1)
elif mode == -1:
return einsum(
'b c m n l, b c m n t -> b m n l t', q_img, k_img
) * 1.0
else:
shift = SlidingChunk2D.mode_dict[mode]
return torch.cat([
# 0, 0
einsum('b c m n l, b c m n t -> b m n l t', q_img, k_img),
# x, x
einsum('b c m n l, b c m n t -> b m n l t', q_img,
torch.roll(k_img, shifts=shift, dims=(2, 3))),
], dim=-1)
@staticmethod
def slidingchunk_av(attn: torch.Tensor, v_img: torch.Tensor, mode: int):
'''
attn x v_img = x ==> Useful for attn x value = context
The cyclic padding strategy
v_img, context: (B * H, M, mx, my, W**2)
attn: (B*H, mx, my, W**2, 9*W**2), mode=0
(B*H, mx, my, W**2, W**2), mode=-1
(B*H, mx, my, W**2, 2*W**2), mode=i>0
mode: 0 -> full, -1 -> only self, i (>0) -> self+block_i
'''
w2 = v_img.shape[-1]
if mode == 0:
attnn1n1, attnn10, attnn11, attn0n1, attn00, attn01, attn1n1, attn10, attn11 = torch.split(
attn, w2, dim=-1
)
elif mode == -1:
attn00 = attn
else:
attn00, attnxx = torch.split(
attn, w2, dim=-1
)
output = einsum('b m n l t, b c m n t -> b c m n l', attn00, v_img) # 0,0
if mode == 0:
output = output + einsum('b m n l t, b c m n t -> b c m n l', attnn1n1,
torch.roll(v_img, shifts=(1, 1), dims=(2, 3))) # -1,-1
output = output + einsum('b m n l t, b c m n t -> b c m n l', attnn10,
torch.roll(v_img, shifts=1, dims=2)) # -1,0
output = output + einsum('b m n l t, b c m n t -> b c m n l', attnn11,
torch.roll(v_img, shifts=(1, -1), dims=(2, 3))) # -1,1
output = output + einsum('b m n l t, b c m n t -> b c m n l', attn0n1,
torch.roll(v_img, shifts=1, dims=3)) # 0,-1
output = output + einsum('b m n l t, b c m n t -> b c m n l', attn01,
torch.roll(v_img, shifts=-1, dims=3)) # 0,1
output = output + einsum('b m n l t, b c m n t -> b c m n l', attn1n1,
torch.roll(v_img, shifts=(-1, 1), dims=(2, 3))) # 1,-1
output = output + einsum('b m n l t, b c m n t -> b c m n l', attn10,
torch.roll(v_img, shifts=-1, dims=2)) # 1,0
output = output + einsum('b m n l t, b c m n t -> b c m n l', attn11,
torch.roll(v_img, shifts=(-1, -1), dims=(2, 3))) # 1,1
elif mode > 0:
shift = SlidingChunk2D.mode_dict[mode]
output = output + einsum('b m n l t, b c m n t -> b c m n l', attnxx,
torch.roll(v_img, shifts=shift, dims=(2, 3))) # 1,1
else:
output = output * 1.0
return output
@staticmethod
def slidingchunk_agrad(attn: torch.Tensor, grad_x: torch.Tensor, mode: int):
'''
attn.t() x grad_x = grad_v ==> Useful for attn.t() x grad_x = grad_v
The cyclic padding strategy
grad_x, grad_v: (B * H, M, mx, my, W**2)
attn: (B*H, mx, my, W**2, 9*W**2), mode=0
(B*H, mx, my, W**2, W**2), mode=-1
(B*H, mx, my, W**2, 2*W**2), mode=i>0
mode: 0 -> full, -1 -> only self, i (>0) -> self+block_i
'''
w2 = grad_x.shape[-1]
if mode == 0:
attnn1n1, attnn10, attnn11, attn0n1, attn00, attn01, attn1n1, attn10, attn11 = torch.split(
attn, w2, dim=-1
)
elif mode == -1:
attn00 = attn
else:
attn00, attnxx = torch.split(
attn, w2, dim=-1
)
# 0,0
output = einsum('b m n l t, b c m n l -> b c m n t', attn00, grad_x)
if mode == 0:
# -1,-1
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attnn1n1, grad_x),
shifts=(-1, -1), dims=(2, 3))
# -1,0
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attnn10, grad_x),
shifts=-1, dims=2)
# -1,1
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attnn11, grad_x),
shifts=(-1, 1), dims=(2, 3))
# 0,-1
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attn0n1, grad_x),
shifts=-1, dims=3)
# 0,1
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attn01, grad_x),
shifts=1, dims=3)
# 1,-1
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attn1n1, grad_x),
shifts=(1, -1), dims=(2, 3))
# 1,0
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attn10, grad_x),
shifts=1, dims=2)
# 1,1
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attn11, grad_x),
shifts=(1, 1), dims=(2, 3))
elif mode > 0:
shift = SlidingChunk2D.mode_dict[mode]
shift = (-shift[0], -shift[1])
output = output + torch.roll(
einsum('b m n l t, b c m n l -> b c m n t', attnxx, grad_x),
shifts=shift, dims=(2, 3))
else:
output = output * 1.0
return output
@staticmethod
@autocast() # comment this out if AMP is not used
def forward(ctx, t1: torch.Tensor, t2: torch.Tensor,
is_t1_diagonaled: bool = False, mode: int = 0) -> torch.Tensor:
"""Compuates sliding chunk mm of t1 and t2.
args:
t1: torch.Tensor = (B * H, M, mx, my, W**2) if is_t1_diagonaled = false,
= (B*H, mx, my, W**2, 9*W**2) if is_t1_diagonaled = true, mode=0.
= (B*H, mx, my, W**2, W**2) if is_t1_diagonaled = true, mode=-1.
= (B*H, mx, my, W**2, 2*W**2) if is_t1_diagonaled = true, mode=i>0.
t2: torch.Tensor = (B * H, M, mx, my, W**2). This is always a
non-diagonaled tensor, e.g. `key_layer` or `value_layer`
is_t1_diagonaled: is t1 a diagonaled or a regular tensor
mode: 0 -> full, -1 -> only self, i (>0) -> self+block_i
returns:
is_t1_diagonaled = true:
torch.Tensor = (B * H, M, mx, my, W**2)
mode=0, is_t1_diagonaled = false:
torch.Tensor = (B*H, mx, my, W**2, 9*W**2)
mode=-1, is_t1_diagonaled = false:
torch.Tensor = (B*H, mx, my, W**2, W**2)
mode=i>0, is_t1_diagonaled = false:
torch.Tensor = (B*H, mx, my, W**2, W**2)
"""
ctx.save_for_backward(t1, t2)
ctx.is_t1_diagonaled = is_t1_diagonaled
ctx.mode = mode
if is_t1_diagonaled:
return SlidingChunk2D.slidingchunk_av(t1, t2, mode)
else:
return SlidingChunk2D.slidingchunk_qk(t1, t2, mode)
@staticmethod
@autocast() # comment this out if AMP is not used
def backward(ctx, grad_output):
t1, t2 = ctx.saved_tensors
is_t1_diagonaled = ctx.is_t1_diagonaled
mode = ctx.mode
if is_t1_diagonaled:
grad_t1 = SlidingChunk2D.slidingchunk_qk(grad_output, t2, mode)
grad_t2 = SlidingChunk2D.slidingchunk_agrad(t1, grad_output, mode)
else:
grad_t1 = SlidingChunk2D.slidingchunk_av(grad_output, t2, mode)
grad_t2 = SlidingChunk2D.slidingchunk_agrad(grad_output, t1, mode)
return grad_t1, grad_t2, None, None
@lru_cache()
def _get_invalid_locations_mask_cyclic(nx: int, ny: int, padx: int, pady: int,
w: int, device: str):
w2 = w ** 2
mask = torch.BoolTensor([
[
(i // ny + (j // w2) // 3 == nx and
(nx - 1) * w + (j % w2) // w >= nx * w - padx) or
(i % ny + (j // w2) % 3 == ny and
(ny - 1) * w + (j % w2) % w >= ny * w - pady)
for j in range(9 * w2)
]
for i in range(nx * ny)
], device='cpu')
# We should count the w2 in the query here
num_invalid = w2 * mask.sum()
return mask.to(device), num_invalid.to(device)
@lru_cache()
def _get_invalid_locations_mask_zero(nx: int, ny: int, padx: int, pady: int,
w: int, device: str):
w2 = w ** 2
mask = torch.BoolTensor([
[
i // ny + (j // w2) // 3 - 1 < 0 or
i // ny + (j // w2) // 3 - 1 >= nx or
(i // ny + (j // w2) // 3 - 1) * w + (j % w2) // w >= nx * w - padx or
i % ny + (j // w2) % 3 - 1 < 0 or
i % ny + (j // w2) % 3 - 1 >= ny or
(i % ny + (j // w2) % 3 - 1) * w + (j % w2) % w >= ny * w - pady
for j in range(9 * w2)
]
for i in range(nx * ny)
], device='cpu')
# We should count the w2 in the query here
num_invalid = w2 * mask.sum()
return mask.to(device), num_invalid.to(device)
@lru_cache()
def _get_invalid_locations_mask_exact(nx: int, ny: int, padx: int, pady: int,
w: int, device: str):
w2 = w ** 2
nx_max = nx * w - 1 - padx
ny_max = ny * w - 1 - pady
mask = torch.BoolTensor([
[
[
(i // ny + (j // w2) // 3 - 1) * w + (j % w2) // w < max(0, (
i // ny - 1) * w + l // w) or
(i // ny + (j // w2) // 3 - 1) * w + (j % w2) // w > min(
nx_max, (i // ny + 1) * w + l // w) or
(i % ny + (j // w2) % 3 - 1) * w + (j % w2) % w < max(0, (
i % ny - 1) * w + l % w) or
(i % ny + (j // w2) % 3 - 1) * w + (j % w2) % w > min(
ny_max, (i % ny + 1) * w + l % w)
for j in range(9 * w2)
]
for l in range(w2)
]
for i in range(nx * ny)
], device='cpu')
num_invalid = mask.sum()
return mask.to(device), num_invalid.to(device)
def mask_invalid_locations(input_tensor: torch.Tensor, nx: int, ny: int,
padx: int, pady: int, w: int,
exact: int, mode: int = 0) -> torch.Tensor:
"""exact
1: exact sliding window
0: blockwise sliding chunk with zero padding
-1: blockwise sliding chunk with cyclic padding
mode: 0 -> full, -1 -> only self, i (>0) -> self+block_i
"""
w2 = w ** 2
if exact == 1 and mode == 0:
mask, num_invalid = _get_invalid_locations_mask_exact(
nx, ny, padx, pady, w, input_tensor.device)
mask = mask.view(1, nx, ny, w2, -1).expand(input_tensor.size())
else:
if exact == 0:
mask, num_invalid = _get_invalid_locations_mask_zero(
nx, ny, padx, pady, w, input_tensor.device)
elif exact == -1:
mask, num_invalid = _get_invalid_locations_mask_cyclic(
nx, ny, padx, pady, w, input_tensor.device)
else:
raise ValueError("longsc exact should be in [0,1,-1]!")
if mode == -1:
mask = mask[:, 4 * w2:5 * w2]
num_invalid = w2 * mask.sum()
elif mode > 0:
chunk_id = mode if mode > 4 else mode - 1
mask = torch.cat([
mask[:, 4 * w2:5 * w2],
mask[:, chunk_id * w2:(chunk_id+1) * w2],
], dim=-1)
num_invalid = w2 * mask.sum()
mask = mask.view(1, nx, ny, 1, -1).expand(input_tensor.size())
input_tensor.masked_fill_(mask, -float('inf'))
return num_invalid
def slidingchunk_2dautograd(t1: torch.Tensor, t2: torch.Tensor,
is_t1_diagonaled: bool = False, mode: int = 0) -> torch.Tensor:
if is_t1_diagonaled:
return SlidingChunk2D.slidingchunk_av(t1, t2, mode)
else:
return SlidingChunk2D.slidingchunk_qk(t1, t2, mode)
slidingchunk_2d = SlidingChunk2D.apply