deform_conv.py 6.6 KB
Newer Older
yhcao6's avatar
yhcao6 committed
1
2
3
4
import torch
from torch.autograd import Function
from torch.nn.modules.utils import _pair

yhcao6's avatar
yhcao6 committed
5
from .. import deform_conv_cuda
6
from .. import modulated_dcn_cuda as _backend
yhcao6's avatar
yhcao6 committed
7
8
9
10


class DeformConvFunction(Function):

yhcao6's avatar
yhcao6 committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    @staticmethod
    def forward(ctx,
                input,
                offset,
                weight,
                stride=1,
                padding=0,
                dilation=1,
                deformable_groups=1,
                im2col_step=64):
        if input is not None and input.dim() != 4:
            raise ValueError(
                "Expected 4D tensor as input, got {}D tensor instead.".format(
                    input.dim()))
        ctx.stride = _pair(stride)
        ctx.padding = _pair(padding)
        ctx.dilation = _pair(dilation)
        ctx.deformable_groups = deformable_groups
        ctx.im2col_step = im2col_step
yhcao6's avatar
yhcao6 committed
30

yhcao6's avatar
yhcao6 committed
31
        ctx.save_for_backward(input, offset, weight)
yhcao6's avatar
yhcao6 committed
32

yhcao6's avatar
yhcao6 committed
33
34
        output = input.new(*DeformConvFunction._output_size(
            input, weight, ctx.padding, ctx.dilation, ctx.stride))
yhcao6's avatar
yhcao6 committed
35

yhcao6's avatar
yhcao6 committed
36
        ctx.bufs_ = [input.new(), input.new()]  # columns, ones
yhcao6's avatar
yhcao6 committed
37
38
39
40

        if not input.is_cuda:
            raise NotImplementedError
        else:
yhcao6's avatar
yhcao6 committed
41
            cur_im2col_step = min(ctx.im2col_step, input.shape[0])
yhcao6's avatar
yhcao6 committed
42
43
            assert (input.shape[0] %
                    cur_im2col_step) == 0, 'im2col step must divide batchsize'
yhcao6's avatar
yhcao6 committed
44
45
46
47
48
            deform_conv_cuda.deform_conv_forward_cuda(
                input, weight, offset, output, ctx.bufs_[0], ctx.bufs_[1],
                weight.size(3), weight.size(2), ctx.stride[1], ctx.stride[0],
                ctx.padding[1], ctx.padding[0], ctx.dilation[1],
                ctx.dilation[0], ctx.deformable_groups, cur_im2col_step)
yhcao6's avatar
yhcao6 committed
49
50
        return output

yhcao6's avatar
yhcao6 committed
51
52
53
    @staticmethod
    def backward(ctx, grad_output):
        input, offset, weight = ctx.saved_tensors
yhcao6's avatar
yhcao6 committed
54
55
56
57
58
59

        grad_input = grad_offset = grad_weight = None

        if not grad_output.is_cuda:
            raise NotImplementedError
        else:
yhcao6's avatar
yhcao6 committed
60
            cur_im2col_step = min(ctx.im2col_step, input.shape[0])
yhcao6's avatar
yhcao6 committed
61
62
63
            assert (input.shape[0] %
                    cur_im2col_step) == 0, 'im2col step must divide batchsize'

yhcao6's avatar
yhcao6 committed
64
65
66
67
            if ctx.needs_input_grad[0] or ctx.needs_input_grad[1]:
                grad_input = torch.zeros_like(input)
                grad_offset = torch.zeros_like(offset)
                deform_conv_cuda.deform_conv_backward_input_cuda(
yhcao6's avatar
yhcao6 committed
68
                    input, offset, grad_output, grad_input,
yhcao6's avatar
yhcao6 committed
69
70
71
72
73
74
75
76
                    grad_offset, weight, ctx.bufs_[0], weight.size(3),
                    weight.size(2), ctx.stride[1], ctx.stride[0],
                    ctx.padding[1], ctx.padding[0], ctx.dilation[1],
                    ctx.dilation[0], ctx.deformable_groups, cur_im2col_step)

            if ctx.needs_input_grad[2]:
                grad_weight = torch.zeros_like(weight)
                deform_conv_cuda.deform_conv_backward_parameters_cuda(
yhcao6's avatar
yhcao6 committed
77
                    input, offset, grad_output,
yhcao6's avatar
yhcao6 committed
78
79
80
81
                    grad_weight, ctx.bufs_[0], ctx.bufs_[1], weight.size(3),
                    weight.size(2), ctx.stride[1], ctx.stride[0],
                    ctx.padding[1], ctx.padding[0], ctx.dilation[1],
                    ctx.dilation[0], ctx.deformable_groups, 1, cur_im2col_step)
yhcao6's avatar
yhcao6 committed
82

yhcao6's avatar
yhcao6 committed
83
        return grad_input, grad_offset, grad_weight, None, None, None, None
yhcao6's avatar
yhcao6 committed
84

yhcao6's avatar
yhcao6 committed
85
86
    @staticmethod
    def _output_size(input, weight, padding, dilation, stride):
yhcao6's avatar
yhcao6 committed
87
88
89
90
        channels = weight.size(0)
        output_size = (input.size(0), channels)
        for d in range(input.dim() - 2):
            in_size = input.size(d + 2)
yhcao6's avatar
yhcao6 committed
91
92
93
94
            pad = padding[d]
            kernel = dilation[d] * (weight.size(d + 2) - 1) + 1
            stride_ = stride[d]
            output_size += ((in_size + (2 * pad) - kernel) // stride_ + 1, )
yhcao6's avatar
yhcao6 committed
95
96
97
98
99
        if not all(map(lambda s: s > 0, output_size)):
            raise ValueError(
                "convolution input is too small (output would be {})".format(
                    'x'.join(map(str, output_size))))
        return output_size
yhcao6's avatar
yhcao6 committed
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
class ModulatedDeformConvFunction(Function):

    @staticmethod
    def forward(ctx,
                input,
                offset,
                mask,
                weight,
                bias,
                stride,
                padding,
                dilation=1,
                deformable_groups=1):
        ctx.stride = stride
        ctx.padding = padding
        ctx.dilation = dilation
        ctx.deformable_groups = deformable_groups
        if not input.is_cuda:
            raise NotImplementedError
        if weight.requires_grad or mask.requires_grad or offset.requires_grad \
                or input.requires_grad:
            ctx.save_for_backward(input, offset, mask, weight, bias)
        output = input.new(
            *ModulatedDeformConvFunction._infer_shape(ctx, input, weight))
        ctx._bufs = [input.new(), input.new()]
        _backend.modulated_deform_conv_cuda_forward(
            input, weight, bias, ctx._bufs[0], offset, mask, output,
            ctx._bufs[1], weight.shape[2], weight.shape[3], ctx.stride,
            ctx.stride, ctx.padding, ctx.padding, ctx.dilation, ctx.dilation,
            ctx.deformable_groups)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        if not grad_output.is_cuda:
            raise NotImplementedError
        input, offset, mask, weight, bias = ctx.saved_tensors
        grad_input = torch.zeros_like(input)
        grad_offset = torch.zeros_like(offset)
        grad_mask = torch.zeros_like(mask)
        grad_weight = torch.zeros_like(weight)
        grad_bias = torch.zeros_like(bias)
        _backend.modulated_deform_conv_cuda_backward(
            input, weight, bias, ctx._bufs[0], offset, mask, ctx._bufs[1],
            grad_input, grad_weight, grad_bias, grad_offset, grad_mask,
            grad_output, weight.shape[2], weight.shape[3], ctx.stride,
            ctx.stride, ctx.padding, ctx.padding, ctx.dilation, ctx.dilation,
            ctx.deformable_groups)

        return (grad_input, grad_offset, grad_mask, grad_weight, grad_bias,
                None, None, None, None)

    @staticmethod
    def _infer_shape(ctx, input, weight):
        n = input.size(0)
        channels_out = weight.size(0)
        height, width = input.shape[2:4]
        kernel_h, kernel_w = weight.shape[2:4]
        height_out = (height + 2 * ctx.padding -
                      (ctx.dilation * (kernel_h - 1) + 1)) // ctx.stride + 1
        width_out = (width + 2 * ctx.padding -
                     (ctx.dilation * (kernel_w - 1) + 1)) // ctx.stride + 1
        return n, channels_out, height_out, width_out


yhcao6's avatar
yhcao6 committed
167
deform_conv = DeformConvFunction.apply
168
modulated_deform_conv = ModulatedDeformConvFunction.apply