roi_align.cpp 6.28 KB
Newer Older
1
2
#include "roi_align.h"
#include <torch/extension.h>
3

4
5
#if defined(WITH_CUDA) || defined(WITH_HIP)
#include <ATen/autocast_mode.h>
6
#endif
7

8
9
namespace vision {
namespace ops {
10
11

at::Tensor roi_align(
12
13
    const at::Tensor& input, // Input feature map.
    const at::Tensor& rois, // List of ROIs to pool over.
14
    double spatial_scale, // The scale of the image features. ROIs will be
15
    // scaled to this.
16
17
18
19
    int64_t pooled_height, // The height of the pooled feature map.
    int64_t pooled_width, // The width of the pooled feature
    int64_t sampling_ratio, // The number of points to sample in each bin
    bool aligned) // The flag for pixel shift
20
21
// along each axis.
{
22
23
24
25
  static auto op = c10::Dispatcher::singleton()
                       .findSchemaOrThrow("torchvision::roi_align", "")
                       .typed<decltype(roi_align)>();
  return op.call(
Francisco Massa's avatar
Francisco Massa committed
26
27
28
29
30
31
32
      input,
      rois,
      spatial_scale,
      pooled_height,
      pooled_width,
      sampling_ratio,
      aligned);
33
34
}

35
#if defined(WITH_CUDA) || defined(WITH_HIP)
36
at::Tensor roi_align_autocast(
37
38
    const at::Tensor& input,
    const at::Tensor& rois,
39
40
41
42
43
    double spatial_scale,
    int64_t pooled_height,
    int64_t pooled_width,
    int64_t sampling_ratio,
    bool aligned) {
44
45
  c10::impl::ExcludeDispatchKeyGuard no_autocast(c10::DispatchKey::Autocast);
  return roi_align(
mcarilli's avatar
mcarilli committed
46
47
             at::autocast::cached_cast(at::kFloat, input),
             at::autocast::cached_cast(at::kFloat, rois),
48
49
50
51
52
53
54
55
56
             spatial_scale,
             pooled_height,
             pooled_width,
             sampling_ratio,
             aligned)
      .to(input.scalar_type());
}
#endif

57
at::Tensor _roi_align_backward(
58
59
    const at::Tensor& grad,
    const at::Tensor& rois,
60
61
62
63
64
65
66
67
68
    double spatial_scale,
    int64_t pooled_height,
    int64_t pooled_width,
    int64_t batch_size,
    int64_t channels,
    int64_t height,
    int64_t width,
    int64_t sampling_ratio,
    bool aligned) {
69
70
71
72
73
  static auto op =
      c10::Dispatcher::singleton()
          .findSchemaOrThrow("torchvision::_roi_align_backward", "")
          .typed<decltype(_roi_align_backward)>();
  return op.call(
74
75
76
77
78
79
80
81
82
      grad,
      rois,
      spatial_scale,
      pooled_height,
      pooled_width,
      batch_size,
      channels,
      height,
      width,
AhnDW's avatar
AhnDW committed
83
84
      sampling_ratio,
      aligned);
85
}
86

87
88
namespace {

89
90
class ROIAlignFunction : public torch::autograd::Function<ROIAlignFunction> {
 public:
91
92
  static torch::autograd::variable_list forward(
      torch::autograd::AutogradContext* ctx,
93
94
95
96
97
98
99
      const torch::autograd::Variable& input,
      const torch::autograd::Variable& rois,
      double spatial_scale,
      int64_t pooled_height,
      int64_t pooled_width,
      int64_t sampling_ratio,
      bool aligned) {
100
101
102
103
    ctx->saved_data["spatial_scale"] = spatial_scale;
    ctx->saved_data["pooled_height"] = pooled_height;
    ctx->saved_data["pooled_width"] = pooled_width;
    ctx->saved_data["sampling_ratio"] = sampling_ratio;
AhnDW's avatar
AhnDW committed
104
    ctx->saved_data["aligned"] = aligned;
105
106
    ctx->saved_data["input_shape"] = input.sizes();
    ctx->save_for_backward({rois});
107
108
    at::AutoNonVariableTypeMode g;
    auto result = roi_align(
109
110
111
112
113
        input,
        rois,
        spatial_scale,
        pooled_height,
        pooled_width,
AhnDW's avatar
AhnDW committed
114
115
        sampling_ratio,
        aligned);
116
117
118
    return {result};
  }

119
120
  static torch::autograd::variable_list backward(
      torch::autograd::AutogradContext* ctx,
121
      const torch::autograd::variable_list& grad_output) {
122
123
124
125
    // Use data saved in forward
    auto saved = ctx->get_saved_variables();
    auto rois = saved[0];
    auto input_shape = ctx->saved_data["input_shape"].toIntList();
126
    auto grad_in = _roi_align_backward(
127
128
129
130
131
132
133
134
135
        grad_output[0],
        rois,
        ctx->saved_data["spatial_scale"].toDouble(),
        ctx->saved_data["pooled_height"].toInt(),
        ctx->saved_data["pooled_width"].toInt(),
        input_shape[0],
        input_shape[1],
        input_shape[2],
        input_shape[3],
AhnDW's avatar
AhnDW committed
136
137
        ctx->saved_data["sampling_ratio"].toInt(),
        ctx->saved_data["aligned"].toBool());
Francisco Massa's avatar
Francisco Massa committed
138
    return {grad_in,
139
140
141
142
143
144
            torch::autograd::Variable(),
            torch::autograd::Variable(),
            torch::autograd::Variable(),
            torch::autograd::Variable(),
            torch::autograd::Variable(),
            torch::autograd::Variable()};
145
146
147
  }
};

148
149
150
151
152
153
// TODO: There should be an easier way to do this
class ROIAlignBackwardFunction
    : public torch::autograd::Function<ROIAlignBackwardFunction> {
 public:
  static torch::autograd::variable_list forward(
      torch::autograd::AutogradContext* ctx,
154
155
156
157
158
159
160
161
162
163
164
      const torch::autograd::Variable& grad,
      const torch::autograd::Variable& rois,
      double spatial_scale,
      int64_t pooled_height,
      int64_t pooled_width,
      int64_t batch_size,
      int64_t channels,
      int64_t height,
      int64_t width,
      int64_t sampling_ratio,
      bool aligned) {
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    at::AutoNonVariableTypeMode g;
    auto result = _roi_align_backward(
        grad,
        rois,
        spatial_scale,
        pooled_height,
        pooled_width,
        batch_size,
        channels,
        height,
        width,
        sampling_ratio,
        aligned);
    return {result};
  }

  static torch::autograd::variable_list backward(
      torch::autograd::AutogradContext* ctx,
183
      const torch::autograd::variable_list& grad_output) {
184
185
186
187
    TORCH_CHECK(0, "double backwards on roi_align not supported");
  }
};

188
189
190
} // namespace

at::Tensor roi_align_autograd(
191
192
    const at::Tensor& input,
    const at::Tensor& rois,
193
194
195
196
197
    double spatial_scale,
    int64_t pooled_height,
    int64_t pooled_width,
    int64_t sampling_ratio,
    bool aligned) {
198
199
200
201
202
203
  return ROIAlignFunction::apply(
      input,
      rois,
      spatial_scale,
      pooled_height,
      pooled_width,
AhnDW's avatar
AhnDW committed
204
205
      sampling_ratio,
      aligned)[0];
206
}
207

208
at::Tensor roi_align_backward_autograd(
209
210
    const at::Tensor& grad,
    const at::Tensor& rois,
211
212
213
214
215
216
217
218
219
    double spatial_scale,
    int64_t pooled_height,
    int64_t pooled_width,
    int64_t batch_size,
    int64_t channels,
    int64_t height,
    int64_t width,
    int64_t sampling_ratio,
    bool aligned) {
220
221
222
223
224
225
226
227
228
229
230
231
232
  return ROIAlignBackwardFunction::apply(
      grad,
      rois,
      spatial_scale,
      pooled_height,
      pooled_width,
      batch_size,
      channels,
      height,
      width,
      sampling_ratio,
      aligned)[0];
}
233
234
235

} // namespace ops
} // namespace vision