Scrappy-Doo commited on
Commit
a4c70b9
·
verified ·
1 Parent(s): 03bc764

Upload 2 files

Browse files
basicsr/ops/dcn/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .deform_conv import (DeformConv, DeformConvPack, ModulatedDeformConv, ModulatedDeformConvPack, deform_conv,
2
+ modulated_deform_conv)
3
+
4
+ __all__ = [
5
+ 'DeformConv', 'DeformConvPack', 'ModulatedDeformConv', 'ModulatedDeformConvPack', 'deform_conv',
6
+ 'modulated_deform_conv'
7
+ ]
basicsr/ops/dcn/deform_conv.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ from torch import nn as nn
4
+ from torch.autograd import Function
5
+ from torch.autograd.function import once_differentiable
6
+ from torch.nn import functional as F
7
+ from torch.nn.modules.utils import _pair, _single
8
+
9
+ try:
10
+ from . import deform_conv_ext
11
+ except ImportError:
12
+ import os
13
+ BASICSR_JIT = os.getenv('BASICSR_JIT')
14
+ if BASICSR_JIT == 'True':
15
+ from torch.utils.cpp_extension import load
16
+ module_path = os.path.dirname(__file__)
17
+ deform_conv_ext = load(
18
+ 'deform_conv',
19
+ sources=[
20
+ os.path.join(module_path, 'src', 'deform_conv_ext.cpp'),
21
+ os.path.join(module_path, 'src', 'deform_conv_cuda.cpp'),
22
+ os.path.join(module_path, 'src', 'deform_conv_cuda_kernel.cu'),
23
+ ],
24
+ )
25
+
26
+
27
+ class DeformConvFunction(Function):
28
+
29
+ @staticmethod
30
+ def forward(ctx,
31
+ input,
32
+ offset,
33
+ weight,
34
+ stride=1,
35
+ padding=0,
36
+ dilation=1,
37
+ groups=1,
38
+ deformable_groups=1,
39
+ im2col_step=64):
40
+ if input is not None and input.dim() != 4:
41
+ raise ValueError(f'Expected 4D tensor as input, got {input.dim()}' 'D tensor instead.')
42
+ ctx.stride = _pair(stride)
43
+ ctx.padding = _pair(padding)
44
+ ctx.dilation = _pair(dilation)
45
+ ctx.groups = groups
46
+ ctx.deformable_groups = deformable_groups
47
+ ctx.im2col_step = im2col_step
48
+
49
+ ctx.save_for_backward(input, offset, weight)
50
+
51
+ output = input.new_empty(DeformConvFunction._output_size(input, weight, ctx.padding, ctx.dilation, ctx.stride))
52
+
53
+ ctx.bufs_ = [input.new_empty(0), input.new_empty(0)] # columns, ones
54
+
55
+ if not input.is_cuda:
56
+ raise NotImplementedError
57
+ else:
58
+ cur_im2col_step = min(ctx.im2col_step, input.shape[0])
59
+ assert (input.shape[0] % cur_im2col_step) == 0, 'im2col step must divide batchsize'
60
+ deform_conv_ext.deform_conv_forward(input, weight,
61
+ offset, output, ctx.bufs_[0], ctx.bufs_[1], weight.size(3),
62
+ weight.size(2), ctx.stride[1], ctx.stride[0], ctx.padding[1],
63
+ ctx.padding[0], ctx.dilation[1], ctx.dilation[0], ctx.groups,
64
+ ctx.deformable_groups, cur_im2col_step)
65
+ return output
66
+
67
+ @staticmethod
68
+ @once_differentiable
69
+ def backward(ctx, grad_output):
70
+ input, offset, weight = ctx.saved_tensors
71
+
72
+ grad_input = grad_offset = grad_weight = None
73
+
74
+ if not grad_output.is_cuda:
75
+ raise NotImplementedError
76
+ else:
77
+ cur_im2col_step = min(ctx.im2col_step, input.shape[0])
78
+ assert (input.shape[0] % cur_im2col_step) == 0, 'im2col step must divide batchsize'
79
+
80
+ if ctx.needs_input_grad[0] or ctx.needs_input_grad[1]:
81
+ grad_input = torch.zeros_like(input)
82
+ grad_offset = torch.zeros_like(offset)
83
+ deform_conv_ext.deform_conv_backward_input(input, offset, grad_output, grad_input,
84
+ grad_offset, weight, ctx.bufs_[0], weight.size(3),
85
+ weight.size(2), ctx.stride[1], ctx.stride[0], ctx.padding[1],
86
+ ctx.padding[0], ctx.dilation[1], ctx.dilation[0], ctx.groups,
87
+ ctx.deformable_groups, cur_im2col_step)
88
+
89
+ if ctx.needs_input_grad[2]:
90
+ grad_weight = torch.zeros_like(weight)
91
+ deform_conv_ext.deform_conv_backward_parameters(input, offset, grad_output, grad_weight,
92
+ ctx.bufs_[0], ctx.bufs_[1], weight.size(3),
93
+ weight.size(2), ctx.stride[1], ctx.stride[0],
94
+ ctx.padding[1], ctx.padding[0], ctx.dilation[1],
95
+ ctx.dilation[0], ctx.groups, ctx.deformable_groups, 1,
96
+ cur_im2col_step)
97
+
98
+ return (grad_input, grad_offset, grad_weight, None, None, None, None, None)
99
+
100
+ @staticmethod
101
+ def _output_size(input, weight, padding, dilation, stride):
102
+ channels = weight.size(0)
103
+ output_size = (input.size(0), channels)
104
+ for d in range(input.dim() - 2):
105
+ in_size = input.size(d + 2)
106
+ pad = padding[d]
107
+ kernel = dilation[d] * (weight.size(d + 2) - 1) + 1
108
+ stride_ = stride[d]
109
+ output_size += ((in_size + (2 * pad) - kernel) // stride_ + 1, )
110
+ if not all(map(lambda s: s > 0, output_size)):
111
+ raise ValueError('convolution input is too small (output would be ' f'{"x".join(map(str, output_size))})')
112
+ return output_size
113
+
114
+
115
+ class ModulatedDeformConvFunction(Function):
116
+
117
+ @staticmethod
118
+ def forward(ctx,
119
+ input,
120
+ offset,
121
+ mask,
122
+ weight,
123
+ bias=None,
124
+ stride=1,
125
+ padding=0,
126
+ dilation=1,
127
+ groups=1,
128
+ deformable_groups=1):
129
+ ctx.stride = stride
130
+ ctx.padding = padding
131
+ ctx.dilation = dilation
132
+ ctx.groups = groups
133
+ ctx.deformable_groups = deformable_groups
134
+ ctx.with_bias = bias is not None
135
+ if not ctx.with_bias:
136
+ bias = input.new_empty(1) # fake tensor
137
+ if not input.is_cuda:
138
+ raise NotImplementedError
139
+ if weight.requires_grad or mask.requires_grad or offset.requires_grad \
140
+ or input.requires_grad:
141
+ ctx.save_for_backward(input, offset, mask, weight, bias)
142
+ output = input.new_empty(ModulatedDeformConvFunction._infer_shape(ctx, input, weight))
143
+ ctx._bufs = [input.new_empty(0), input.new_empty(0)]
144
+ deform_conv_ext.modulated_deform_conv_forward(input, weight, bias, ctx._bufs[0], offset, mask, output,
145
+ ctx._bufs[1], weight.shape[2], weight.shape[3], ctx.stride,
146
+ ctx.stride, ctx.padding, ctx.padding, ctx.dilation, ctx.dilation,
147
+ ctx.groups, ctx.deformable_groups, ctx.with_bias)
148
+ return output
149
+
150
+ @staticmethod
151
+ @once_differentiable
152
+ def backward(ctx, grad_output):
153
+ if not grad_output.is_cuda:
154
+ raise NotImplementedError
155
+ input, offset, mask, weight, bias = ctx.saved_tensors
156
+ grad_input = torch.zeros_like(input)
157
+ grad_offset = torch.zeros_like(offset)
158
+ grad_mask = torch.zeros_like(mask)
159
+ grad_weight = torch.zeros_like(weight)
160
+ grad_bias = torch.zeros_like(bias)
161
+ deform_conv_ext.modulated_deform_conv_backward(input, weight, bias, ctx._bufs[0], offset, mask, ctx._bufs[1],
162
+ grad_input, grad_weight, grad_bias, grad_offset, grad_mask,
163
+ grad_output, weight.shape[2], weight.shape[3], ctx.stride,
164
+ ctx.stride, ctx.padding, ctx.padding, ctx.dilation, ctx.dilation,
165
+ ctx.groups, ctx.deformable_groups, ctx.with_bias)
166
+ if not ctx.with_bias:
167
+ grad_bias = None
168
+
169
+ return (grad_input, grad_offset, grad_mask, grad_weight, grad_bias, None, None, None, None, None)
170
+
171
+ @staticmethod
172
+ def _infer_shape(ctx, input, weight):
173
+ n = input.size(0)
174
+ channels_out = weight.size(0)
175
+ height, width = input.shape[2:4]
176
+ kernel_h, kernel_w = weight.shape[2:4]
177
+ height_out = (height + 2 * ctx.padding - (ctx.dilation * (kernel_h - 1) + 1)) // ctx.stride + 1
178
+ width_out = (width + 2 * ctx.padding - (ctx.dilation * (kernel_w - 1) + 1)) // ctx.stride + 1
179
+ return n, channels_out, height_out, width_out
180
+
181
+
182
+ deform_conv = DeformConvFunction.apply
183
+ modulated_deform_conv = ModulatedDeformConvFunction.apply
184
+
185
+
186
+ class DeformConv(nn.Module):
187
+
188
+ def __init__(self,
189
+ in_channels,
190
+ out_channels,
191
+ kernel_size,
192
+ stride=1,
193
+ padding=0,
194
+ dilation=1,
195
+ groups=1,
196
+ deformable_groups=1,
197
+ bias=False):
198
+ super(DeformConv, self).__init__()
199
+
200
+ assert not bias
201
+ assert in_channels % groups == 0, \
202
+ f'in_channels {in_channels} is not divisible by groups {groups}'
203
+ assert out_channels % groups == 0, \
204
+ f'out_channels {out_channels} is not divisible ' \
205
+ f'by groups {groups}'
206
+
207
+ self.in_channels = in_channels
208
+ self.out_channels = out_channels
209
+ self.kernel_size = _pair(kernel_size)
210
+ self.stride = _pair(stride)
211
+ self.padding = _pair(padding)
212
+ self.dilation = _pair(dilation)
213
+ self.groups = groups
214
+ self.deformable_groups = deformable_groups
215
+ # enable compatibility with nn.Conv2d
216
+ self.transposed = False
217
+ self.output_padding = _single(0)
218
+
219
+ self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels // self.groups, *self.kernel_size))
220
+
221
+ self.reset_parameters()
222
+
223
+ def reset_parameters(self):
224
+ n = self.in_channels
225
+ for k in self.kernel_size:
226
+ n *= k
227
+ stdv = 1. / math.sqrt(n)
228
+ self.weight.data.uniform_(-stdv, stdv)
229
+
230
+ def forward(self, x, offset):
231
+ # To fix an assert error in deform_conv_cuda.cpp:128
232
+ # input image is smaller than kernel
233
+ input_pad = (x.size(2) < self.kernel_size[0] or x.size(3) < self.kernel_size[1])
234
+ if input_pad:
235
+ pad_h = max(self.kernel_size[0] - x.size(2), 0)
236
+ pad_w = max(self.kernel_size[1] - x.size(3), 0)
237
+ x = F.pad(x, (0, pad_w, 0, pad_h), 'constant', 0).contiguous()
238
+ offset = F.pad(offset, (0, pad_w, 0, pad_h), 'constant', 0).contiguous()
239
+ out = deform_conv(x, offset, self.weight, self.stride, self.padding, self.dilation, self.groups,
240
+ self.deformable_groups)
241
+ if input_pad:
242
+ out = out[:, :, :out.size(2) - pad_h, :out.size(3) - pad_w].contiguous()
243
+ return out
244
+
245
+
246
+ class DeformConvPack(DeformConv):
247
+ """A Deformable Conv Encapsulation that acts as normal Conv layers.
248
+
249
+ Args:
250
+ in_channels (int): Same as nn.Conv2d.
251
+ out_channels (int): Same as nn.Conv2d.
252
+ kernel_size (int or tuple[int]): Same as nn.Conv2d.
253
+ stride (int or tuple[int]): Same as nn.Conv2d.
254
+ padding (int or tuple[int]): Same as nn.Conv2d.
255
+ dilation (int or tuple[int]): Same as nn.Conv2d.
256
+ groups (int): Same as nn.Conv2d.
257
+ bias (bool or str): If specified as `auto`, it will be decided by the
258
+ norm_cfg. Bias will be set as True if norm_cfg is None, otherwise
259
+ False.
260
+ """
261
+
262
+ _version = 2
263
+
264
+ def __init__(self, *args, **kwargs):
265
+ super(DeformConvPack, self).__init__(*args, **kwargs)
266
+
267
+ self.conv_offset = nn.Conv2d(
268
+ self.in_channels,
269
+ self.deformable_groups * 2 * self.kernel_size[0] * self.kernel_size[1],
270
+ kernel_size=self.kernel_size,
271
+ stride=_pair(self.stride),
272
+ padding=_pair(self.padding),
273
+ dilation=_pair(self.dilation),
274
+ bias=True)
275
+ self.init_offset()
276
+
277
+ def init_offset(self):
278
+ self.conv_offset.weight.data.zero_()
279
+ self.conv_offset.bias.data.zero_()
280
+
281
+ def forward(self, x):
282
+ offset = self.conv_offset(x)
283
+ return deform_conv(x, offset, self.weight, self.stride, self.padding, self.dilation, self.groups,
284
+ self.deformable_groups)
285
+
286
+
287
+ class ModulatedDeformConv(nn.Module):
288
+
289
+ def __init__(self,
290
+ in_channels,
291
+ out_channels,
292
+ kernel_size,
293
+ stride=1,
294
+ padding=0,
295
+ dilation=1,
296
+ groups=1,
297
+ deformable_groups=1,
298
+ bias=True):
299
+ super(ModulatedDeformConv, self).__init__()
300
+ self.in_channels = in_channels
301
+ self.out_channels = out_channels
302
+ self.kernel_size = _pair(kernel_size)
303
+ self.stride = stride
304
+ self.padding = padding
305
+ self.dilation = dilation
306
+ self.groups = groups
307
+ self.deformable_groups = deformable_groups
308
+ self.with_bias = bias
309
+ # enable compatibility with nn.Conv2d
310
+ self.transposed = False
311
+ self.output_padding = _single(0)
312
+
313
+ self.weight = nn.Parameter(torch.Tensor(out_channels, in_channels // groups, *self.kernel_size))
314
+ if bias:
315
+ self.bias = nn.Parameter(torch.Tensor(out_channels))
316
+ else:
317
+ self.register_parameter('bias', None)
318
+ self.init_weights()
319
+
320
+ def init_weights(self):
321
+ n = self.in_channels
322
+ for k in self.kernel_size:
323
+ n *= k
324
+ stdv = 1. / math.sqrt(n)
325
+ self.weight.data.uniform_(-stdv, stdv)
326
+ if self.bias is not None:
327
+ self.bias.data.zero_()
328
+
329
+ def forward(self, x, offset, mask):
330
+ return modulated_deform_conv(x, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation,
331
+ self.groups, self.deformable_groups)
332
+
333
+
334
+ class ModulatedDeformConvPack(ModulatedDeformConv):
335
+ """A ModulatedDeformable Conv Encapsulation that acts as normal Conv layers.
336
+
337
+ Args:
338
+ in_channels (int): Same as nn.Conv2d.
339
+ out_channels (int): Same as nn.Conv2d.
340
+ kernel_size (int or tuple[int]): Same as nn.Conv2d.
341
+ stride (int or tuple[int]): Same as nn.Conv2d.
342
+ padding (int or tuple[int]): Same as nn.Conv2d.
343
+ dilation (int or tuple[int]): Same as nn.Conv2d.
344
+ groups (int): Same as nn.Conv2d.
345
+ bias (bool or str): If specified as `auto`, it will be decided by the
346
+ norm_cfg. Bias will be set as True if norm_cfg is None, otherwise
347
+ False.
348
+ """
349
+
350
+ _version = 2
351
+
352
+ def __init__(self, *args, **kwargs):
353
+ super(ModulatedDeformConvPack, self).__init__(*args, **kwargs)
354
+
355
+ self.conv_offset = nn.Conv2d(
356
+ self.in_channels,
357
+ self.deformable_groups * 3 * self.kernel_size[0] * self.kernel_size[1],
358
+ kernel_size=self.kernel_size,
359
+ stride=_pair(self.stride),
360
+ padding=_pair(self.padding),
361
+ dilation=_pair(self.dilation),
362
+ bias=True)
363
+ self.init_weights()
364
+
365
+ def init_weights(self):
366
+ super(ModulatedDeformConvPack, self).init_weights()
367
+ if hasattr(self, 'conv_offset'):
368
+ self.conv_offset.weight.data.zero_()
369
+ self.conv_offset.bias.data.zero_()
370
+
371
+ def forward(self, x):
372
+ out = self.conv_offset(x)
373
+ o1, o2, mask = torch.chunk(out, 3, dim=1)
374
+ offset = torch.cat((o1, o2), dim=1)
375
+ mask = torch.sigmoid(mask)
376
+ return modulated_deform_conv(x, offset, mask, self.weight, self.bias, self.stride, self.padding, self.dilation,
377
+ self.groups, self.deformable_groups)