Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

ps_roi_align_kernel.cu 14 KB

You have to be logged in to leave a comment. Sign In
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
  1. #include <ATen/ATen.h>
  2. #include <ATen/cuda/CUDAContext.h>
  3. #include <c10/cuda/CUDAGuard.h>
  4. #include <torch/library.h>
  5. #include <ATen/native/cuda/KernelUtils.cuh>
  6. #include "cuda_helpers.h"
  7. namespace vision {
  8. namespace ops {
  9. namespace {
  10. template <typename T>
  11. __device__ T bilinear_interpolate(
  12. const T* input,
  13. int height,
  14. int width,
  15. T y,
  16. T x,
  17. int index /* index for debug only*/) {
  18. // deal with cases that inverse elements are out of feature map boundary
  19. if (y < -1.0 || y > height || x < -1.0 || x > width) {
  20. // empty
  21. return 0;
  22. }
  23. if (y <= 0)
  24. y = 0;
  25. if (x <= 0)
  26. x = 0;
  27. int y_low = (int)y;
  28. int x_low = (int)x;
  29. int y_high;
  30. int x_high;
  31. if (y_low >= height - 1) {
  32. y_high = y_low = height - 1;
  33. y = (T)y_low;
  34. } else {
  35. y_high = y_low + 1;
  36. }
  37. if (x_low >= width - 1) {
  38. x_high = x_low = width - 1;
  39. x = (T)x_low;
  40. } else {
  41. x_high = x_low + 1;
  42. }
  43. T ly = y - y_low;
  44. T lx = x - x_low;
  45. T hy = 1. - ly, hx = 1. - lx;
  46. // do bilinear interpolation
  47. T v1 = input[y_low * width + x_low];
  48. T v2 = input[y_low * width + x_high];
  49. T v3 = input[y_high * width + x_low];
  50. T v4 = input[y_high * width + x_high];
  51. T w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx;
  52. T val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
  53. return val;
  54. }
  55. template <typename T>
  56. __global__ void ps_roi_align_forward_kernel_impl(
  57. int nthreads,
  58. const T* input,
  59. const T spatial_scale,
  60. int channels,
  61. int height,
  62. int width,
  63. int pooled_height,
  64. int pooled_width,
  65. int sampling_ratio,
  66. const T* rois,
  67. int channels_out,
  68. T* output,
  69. int* channel_mapping) {
  70. CUDA_1D_KERNEL_LOOP(index, nthreads) {
  71. // (n, c_out, ph, pw) is an element in the pooled output
  72. int pw = index % pooled_width;
  73. int ph = (index / pooled_width) % pooled_height;
  74. int c_out = (index / pooled_width / pooled_height) % channels_out;
  75. int n = index / pooled_width / pooled_height / channels_out;
  76. // (n, c_in, ph, pw) is the associated element in the input
  77. int c_in = (c_out * pooled_height + ph) * pooled_width + pw;
  78. // [start, end) interval for spatial sampling
  79. const T* offset_rois = rois + n * 5;
  80. int roi_batch_ind = offset_rois[0];
  81. // Do not using rounding; this implementation detail is critical
  82. T roi_start_w = offset_rois[1] * spatial_scale - static_cast<T>(0.5);
  83. T roi_start_h = offset_rois[2] * spatial_scale - static_cast<T>(0.5);
  84. T roi_end_w = offset_rois[3] * spatial_scale - static_cast<T>(0.5);
  85. T roi_end_h = offset_rois[4] * spatial_scale - static_cast<T>(0.5);
  86. T roi_width = roi_end_w - roi_start_w;
  87. T roi_height = roi_end_h - roi_start_h;
  88. T bin_size_h = static_cast<T>(roi_height) / static_cast<T>(pooled_height);
  89. T bin_size_w = static_cast<T>(roi_width) / static_cast<T>(pooled_width);
  90. // Do not using floor/ceil; this implementation detail is critical
  91. T hstart = static_cast<T>(ph) * bin_size_h + roi_start_h;
  92. T wstart = static_cast<T>(pw) * bin_size_w + roi_start_w;
  93. // We use roi_bin_grid to sample the grid and mimic integral
  94. int roi_bin_grid_h = (sampling_ratio > 0)
  95. ? sampling_ratio
  96. : ceil(roi_height / pooled_height);
  97. int roi_bin_grid_w =
  98. (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width);
  99. const T count = roi_bin_grid_h * roi_bin_grid_w;
  100. const T* offset_input =
  101. input + (roi_batch_ind * channels + c_in) * height * width;
  102. T out_sum = 0;
  103. for (int iy = 0; iy < roi_bin_grid_h; iy++) {
  104. const T y = hstart +
  105. static_cast<T>(iy + .5f) * bin_size_h /
  106. static_cast<T>(roi_bin_grid_h);
  107. for (int ix = 0; ix < roi_bin_grid_w; ix++) {
  108. const T x = wstart +
  109. static_cast<T>(ix + .5f) * bin_size_w /
  110. static_cast<T>(roi_bin_grid_w);
  111. T val = bilinear_interpolate(offset_input, height, width, y, x, index);
  112. out_sum += val;
  113. }
  114. }
  115. out_sum /= count;
  116. output[index] = out_sum;
  117. channel_mapping[index] = c_in;
  118. }
  119. }
  120. template <typename T>
  121. __device__ void bilinear_interpolate_gradient(
  122. int height,
  123. int width,
  124. T y,
  125. T x,
  126. T& w1,
  127. T& w2,
  128. T& w3,
  129. T& w4,
  130. int& x_low,
  131. int& x_high,
  132. int& y_low,
  133. int& y_high,
  134. int index /* index for debug only*/) {
  135. // deal with cases that inverse elements are out of feature map boundary
  136. if (y < -1.0 || y > height || x < -1.0 || x > width) {
  137. // empty
  138. w1 = w2 = w3 = w4 = 0.;
  139. x_low = x_high = y_low = y_high = -1;
  140. return;
  141. }
  142. if (y <= 0)
  143. y = 0;
  144. if (x <= 0)
  145. x = 0;
  146. y_low = (int)y;
  147. x_low = (int)x;
  148. if (y_low >= height - 1) {
  149. y_high = y_low = height - 1;
  150. y = (T)y_low;
  151. } else {
  152. y_high = y_low + 1;
  153. }
  154. if (x_low >= width - 1) {
  155. x_high = x_low = width - 1;
  156. x = (T)x_low;
  157. } else {
  158. x_high = x_low + 1;
  159. }
  160. T ly = y - y_low;
  161. T lx = x - x_low;
  162. T hy = 1. - ly, hx = 1. - lx;
  163. // reference in forward
  164. // T v1 = input[y_low * width + x_low];
  165. // T v2 = input[y_low * width + x_high];
  166. // T v3 = input[y_high * width + x_low];
  167. // T v4 = input[y_high * width + x_high];
  168. // T val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
  169. w1 = hy * hx, w2 = hy * lx, w3 = ly * hx, w4 = ly * lx;
  170. }
  171. template <typename T>
  172. __global__ void ps_roi_align_backward_kernel_impl(
  173. int nthreads,
  174. const T* grad_output,
  175. const int* channel_mapping,
  176. const T spatial_scale,
  177. int channels,
  178. int height,
  179. int width,
  180. int pooled_height,
  181. int pooled_width,
  182. int sampling_ratio,
  183. int channels_out,
  184. T* grad_input,
  185. const T* rois,
  186. const int memory_span) {
  187. CUDA_1D_KERNEL_LOOP(index, nthreads) {
  188. // (n, *, ph, pw) is an element in the pooled output
  189. int pw = index % pooled_width;
  190. int ph = (index / pooled_width) % pooled_height;
  191. int n = index / pooled_width / pooled_height / channels_out;
  192. const T* offset_rois = rois + n * 5;
  193. int roi_batch_ind = offset_rois[0];
  194. // Do not using rounding; this implementation detail is critical
  195. T roi_start_w = offset_rois[1] * spatial_scale - static_cast<T>(0.5);
  196. T roi_start_h = offset_rois[2] * spatial_scale - static_cast<T>(0.5);
  197. T roi_end_w = offset_rois[3] * spatial_scale - static_cast<T>(0.5);
  198. T roi_end_h = offset_rois[4] * spatial_scale - static_cast<T>(0.5);
  199. // Force too small ROIs to be 1x1
  200. T roi_width = roi_end_w - roi_start_w;
  201. T roi_height = roi_end_h - roi_start_h;
  202. T bin_size_h = roi_height / static_cast<T>(pooled_height);
  203. T bin_size_w = roi_width / static_cast<T>(pooled_width);
  204. int c_in = channel_mapping[index];
  205. // Do not using floor/ceil; this implementation detail is critical
  206. T hstart = static_cast<T>(ph) * bin_size_h + roi_start_h;
  207. T wstart = static_cast<T>(pw) * bin_size_w + roi_start_w;
  208. const T grad_output_this_bin = grad_output[index];
  209. // We use roi_bin_grid to sample the grid and mimic integral
  210. int roi_bin_grid_h = (sampling_ratio > 0)
  211. ? sampling_ratio
  212. : ceil(roi_height / pooled_height); // e.g., = 2
  213. int roi_bin_grid_w =
  214. (sampling_ratio > 0) ? sampling_ratio : ceil(roi_width / pooled_width);
  215. const T count = roi_bin_grid_h * roi_bin_grid_w;
  216. const int offset = (roi_batch_ind * channels + c_in) * height * width;
  217. for (int iy = 0; iy < roi_bin_grid_h; iy++) {
  218. const T y = hstart +
  219. static_cast<T>(iy + .5f) * bin_size_h /
  220. static_cast<T>(roi_bin_grid_h);
  221. for (int ix = 0; ix < roi_bin_grid_w; ix++) {
  222. const T x = wstart +
  223. static_cast<T>(ix + .5f) * bin_size_w /
  224. static_cast<T>(roi_bin_grid_w);
  225. T w1, w2, w3, w4;
  226. int x_low, x_high, y_low, y_high;
  227. bilinear_interpolate_gradient(
  228. height,
  229. width,
  230. y,
  231. x,
  232. w1,
  233. w2,
  234. w3,
  235. w4,
  236. x_low,
  237. x_high,
  238. y_low,
  239. y_high,
  240. index);
  241. T g1 = grad_output_this_bin * w1 / count;
  242. T g2 = grad_output_this_bin * w2 / count;
  243. T g3 = grad_output_this_bin * w3 / count;
  244. T g4 = grad_output_this_bin * w4 / count;
  245. if (x_low >= 0 && x_high >= 0 && y_low >= 0 && y_high >= 0) {
  246. at::native::fastAtomicAdd(
  247. grad_input,
  248. offset + y_low * width + x_low,
  249. memory_span,
  250. static_cast<T>(g1),
  251. true);
  252. at::native::fastAtomicAdd(
  253. grad_input,
  254. offset + y_low * width + x_high,
  255. memory_span,
  256. static_cast<T>(g2),
  257. true);
  258. at::native::fastAtomicAdd(
  259. grad_input,
  260. offset + y_high * width + x_low,
  261. memory_span,
  262. static_cast<T>(g3),
  263. true);
  264. at::native::fastAtomicAdd(
  265. grad_input,
  266. offset + y_high * width + x_high,
  267. memory_span,
  268. static_cast<T>(g4),
  269. true);
  270. } // if
  271. } // ix
  272. } // iy
  273. }
  274. }
  275. std::tuple<at::Tensor, at::Tensor> ps_roi_align_forward_kernel(
  276. const at::Tensor& input,
  277. const at::Tensor& rois,
  278. double spatial_scale,
  279. int64_t pooled_height,
  280. int64_t pooled_width,
  281. int64_t sampling_ratio) {
  282. // Check if input tensors are CUDA tensors
  283. TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor");
  284. TORCH_CHECK(rois.is_cuda(), "rois must be a CUDA tensor");
  285. TORCH_CHECK(
  286. rois.size(1) == 5, "Tensor rois should have shape as Tensor[K, 5]");
  287. at::TensorArg input_t{input, "input", 1}, rois_t{rois, "rois", 2};
  288. at::CheckedFrom c = "ps_roi_align_forward_kernel";
  289. at::checkAllSameGPU(c, {input_t, rois_t});
  290. at::checkAllSameType(c, {input_t, rois_t});
  291. at::cuda::CUDAGuard device_guard(input.device());
  292. auto num_rois = rois.size(0);
  293. auto channels = input.size(1);
  294. auto height = input.size(2);
  295. auto width = input.size(3);
  296. TORCH_CHECK(
  297. channels % (pooled_height * pooled_width) == 0,
  298. "input channels must be a multiple of pooling height * pooling width");
  299. int channels_out = channels / (pooled_height * pooled_width);
  300. auto output = at::zeros(
  301. {num_rois, channels_out, pooled_height, pooled_width}, input.options());
  302. auto channel_mapping =
  303. at::zeros(output.sizes(), input.options().dtype(at::kInt));
  304. auto output_size = output.numel();
  305. if (output_size == 0) {
  306. AT_CUDA_CHECK(cudaGetLastError());
  307. return std::make_tuple(output, channel_mapping);
  308. }
  309. cudaStream_t stream = at::cuda::getCurrentCUDAStream();
  310. dim3 grid(std::min(
  311. ceil_div(static_cast<int64_t>(output_size), static_cast<int64_t>(512)),
  312. static_cast<int64_t>(4096)));
  313. dim3 block(512);
  314. auto input_ = input.contiguous(), rois_ = rois.contiguous();
  315. AT_DISPATCH_FLOATING_TYPES_AND_HALF(
  316. input.scalar_type(), "ps_roi_align_forward_kernel", [&] {
  317. ps_roi_align_forward_kernel_impl<scalar_t><<<grid, block, 0, stream>>>(
  318. output_size,
  319. input_.data_ptr<scalar_t>(),
  320. spatial_scale,
  321. channels,
  322. height,
  323. width,
  324. pooled_height,
  325. pooled_width,
  326. sampling_ratio,
  327. rois_.data_ptr<scalar_t>(),
  328. channels_out,
  329. output.data_ptr<scalar_t>(),
  330. channel_mapping.data_ptr<int>());
  331. });
  332. AT_CUDA_CHECK(cudaGetLastError());
  333. cudaDeviceSynchronize();
  334. return std::make_tuple(output, channel_mapping);
  335. }
  336. at::Tensor ps_roi_align_backward_kernel(
  337. const at::Tensor& grad,
  338. const at::Tensor& rois,
  339. const at::Tensor& channel_mapping,
  340. double spatial_scale,
  341. int64_t pooled_height,
  342. int64_t pooled_width,
  343. int64_t sampling_ratio,
  344. int64_t batch_size,
  345. int64_t channels,
  346. int64_t height,
  347. int64_t width) {
  348. // Check if input tensors are CUDA tensors
  349. TORCH_CHECK(grad.is_cuda(), "grad must be a CUDA tensor");
  350. TORCH_CHECK(rois.is_cuda(), "rois must be a CUDA tensor");
  351. TORCH_CHECK(
  352. channel_mapping.is_cuda(), "channel_mapping must be a CUDA tensor");
  353. at::TensorArg grad_t{grad, "grad", 1}, rois_t{rois, "rois", 2},
  354. channel_mapping_t{channel_mapping, "channel_mapping", 3};
  355. at::CheckedFrom c = "ps_roi_align_backward_kernel";
  356. at::checkAllSameGPU(c, {grad_t, rois_t, channel_mapping_t});
  357. at::checkAllSameType(c, {grad_t, rois_t});
  358. at::cuda::CUDAGuard device_guard(grad.device());
  359. auto grad_input =
  360. at::zeros({batch_size, channels, height, width}, grad.options());
  361. cudaStream_t stream = at::cuda::getCurrentCUDAStream();
  362. dim3 grid(std::min(
  363. ceil_div(static_cast<int64_t>(grad.numel()), static_cast<int64_t>(512)),
  364. static_cast<int64_t>(4096)));
  365. dim3 block(512);
  366. // handle possibly empty gradients
  367. if (grad.numel() == 0) {
  368. AT_CUDA_CHECK(cudaGetLastError());
  369. return grad_input;
  370. }
  371. int channels_out = channels / (pooled_height * pooled_width);
  372. at::globalContext().alertNotDeterministic("ps_roi_align_backward_kernel");
  373. auto grad_ = grad.contiguous(), rois_ = rois.contiguous();
  374. AT_DISPATCH_FLOATING_TYPES_AND_HALF(
  375. grad.scalar_type(), "ps_roi_align_backward_kernel", [&] {
  376. ps_roi_align_backward_kernel_impl<scalar_t><<<grid, block, 0, stream>>>(
  377. grad.numel(),
  378. grad_.data_ptr<scalar_t>(),
  379. channel_mapping.data_ptr<int>(),
  380. spatial_scale,
  381. channels,
  382. height,
  383. width,
  384. pooled_height,
  385. pooled_width,
  386. sampling_ratio,
  387. channels_out,
  388. grad_input.data_ptr<scalar_t>(),
  389. rois_.data_ptr<scalar_t>(),
  390. grad_input.numel());
  391. });
  392. AT_CUDA_CHECK(cudaGetLastError());
  393. return grad_input;
  394. }
  395. } // namespace
  396. TORCH_LIBRARY_IMPL(torchvision, CUDA, m) {
  397. m.impl(
  398. TORCH_SELECTIVE_NAME("torchvision::ps_roi_align"),
  399. TORCH_FN(ps_roi_align_forward_kernel));
  400. m.impl(
  401. TORCH_SELECTIVE_NAME("torchvision::_ps_roi_align_backward"),
  402. TORCH_FN(ps_roi_align_backward_kernel));
  403. }
  404. } // namespace ops
  405. } // namespace vision
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...