collect_fpn_proposals_op.cu 11.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
  Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

12
#ifdef __NVCC__
13
#include "cub/cub.cuh"
14 15 16
#endif
#ifdef __HIPCC__
#include <hipcub/hipcub.hpp>
17
namespace cub = hipcub;
18 19 20
#endif

#include <paddle/fluid/memory/allocation/allocator.h>
21

22 23 24 25 26 27
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/memory/memcpy.h"
#include "paddle/fluid/operators/detection/bbox_util.h"
#include "paddle/fluid/operators/detection/collect_fpn_proposals_op.h"
#include "paddle/fluid/operators/math/concat_and_split.h"
#include "paddle/fluid/platform/for_range.h"
28
#include "paddle/phi/backends/gpu/gpu_primitives.h"
H
Huang Jiyi 已提交
29
#include "paddle/phi/core/mixed_vector.h"
30
#include "paddle/phi/kernels/funcs/gather.cu.h"
31
#include "paddle/phi/kernels/funcs/strided_memcpy.h"
32 33 34 35 36 37 38 39 40 41 42 43 44 45

namespace paddle {
namespace operators {

static constexpr int kNumCUDAThreads = 64;
static constexpr int kNumMaxinumNumBlocks = 4096;

const int kBBoxSize = 4;

static inline int NumBlocks(const int N) {
  return std::min((N + kNumCUDAThreads - 1) / kNumCUDAThreads,
                  kNumMaxinumNumBlocks);
}

46 47
static __global__ void GetLengthLoD(const int nthreads,
                                    const int* batch_ids,
48
                                    int* length_lod) {
49
  CUDA_KERNEL_LOOP(i, nthreads) {
50
    phi::CudaAtomicAdd(length_lod + batch_ids[i], 1);
51 52 53 54 55 56 57
  }
}

template <typename DeviceContext, typename T>
class GPUCollectFpnProposalsOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
58 59 60
    const auto roi_ins = ctx.MultiInput<phi::DenseTensor>("MultiLevelRois");
    const auto score_ins = ctx.MultiInput<phi::DenseTensor>("MultiLevelScores");
    auto fpn_rois = ctx.Output<phi::DenseTensor>("FpnRois");
61 62 63 64 65 66 67 68 69 70 71 72 73 74
    auto& dev_ctx = ctx.template device_context<DeviceContext>();

    const int post_nms_topN = ctx.Attr<int>("post_nms_topN");

    // concat inputs along axis = 0
    int roi_offset = 0;
    int score_offset = 0;
    int total_roi_num = 0;
    for (size_t i = 0; i < roi_ins.size(); ++i) {
      total_roi_num += roi_ins[i]->dims()[0];
    }

    int real_post_num = min(post_nms_topN, total_roi_num);
    fpn_rois->mutable_data<T>({real_post_num, kBBoxSize}, dev_ctx.GetPlace());
75 76
    phi::DenseTensor concat_rois;
    phi::DenseTensor concat_scores;
77 78 79 80
    T* concat_rois_data = concat_rois.mutable_data<T>(
        {total_roi_num, kBBoxSize}, dev_ctx.GetPlace());
    T* concat_scores_data =
        concat_scores.mutable_data<T>({total_roi_num, 1}, dev_ctx.GetPlace());
81
    phi::DenseTensor roi_batch_id_list;
82 83 84 85 86
    roi_batch_id_list.Resize({total_roi_num});
    int* roi_batch_id_data =
        roi_batch_id_list.mutable_data<int>(platform::CPUPlace());
    int index = 0;
    int lod_size;
87
    auto place = dev_ctx.GetPlace();
88

89
    auto multi_rois_num = ctx.MultiInput<phi::DenseTensor>("MultiLevelRoIsNum");
90 91 92
    for (size_t i = 0; i < roi_ins.size(); ++i) {
      auto roi_in = roi_ins[i];
      auto score_in = score_ins[i];
93
      if (multi_rois_num.size() > 0) {
94
        phi::DenseTensor temp;
95 96
        paddle::framework::TensorCopySync(
            *multi_rois_num[i], platform::CPUPlace(), &temp);
97 98 99 100 101 102 103 104 105 106 107 108 109 110
        const int* length_in = temp.data<int>();
        lod_size = multi_rois_num[i]->numel();
        for (size_t n = 0; n < lod_size; ++n) {
          for (size_t j = 0; j < length_in[n]; ++j) {
            roi_batch_id_data[index++] = n;
          }
        }
      } else {
        auto length_in = roi_in->lod().back();
        lod_size = length_in.size() - 1;
        for (size_t n = 0; n < lod_size; ++n) {
          for (size_t j = length_in[n]; j < length_in[n + 1]; ++j) {
            roi_batch_id_data[index++] = n;
          }
111 112 113
        }
      }

114 115 116 117 118
      memory::Copy(place,
                   concat_rois_data + roi_offset,
                   place,
                   roi_in->data<T>(),
                   roi_in->numel() * sizeof(T),
119
                   dev_ctx.stream());
120 121 122 123 124
      memory::Copy(place,
                   concat_scores_data + score_offset,
                   place,
                   score_in->data<T>(),
                   score_in->numel() * sizeof(T),
125 126 127 128 129 130
                   dev_ctx.stream());
      roi_offset += roi_in->numel();
      score_offset += score_in->numel();
    }

    // copy batch id list to GPU
131
    phi::DenseTensor roi_batch_id_list_gpu;
132 133
    framework::TensorCopy(
        roi_batch_id_list, dev_ctx.GetPlace(), &roi_batch_id_list_gpu);
134

135
    phi::DenseTensor index_in_t;
136 137
    int* idx_in =
        index_in_t.mutable_data<int>({total_roi_num}, dev_ctx.GetPlace());
L
Leo Chen 已提交
138
    platform::ForRange<phi::GPUContext> for_range_total(dev_ctx, total_roi_num);
139 140
    for_range_total(RangeInitFunctor{0, 1, idx_in});

141
    phi::DenseTensor keys_out_t;
142 143
    T* keys_out =
        keys_out_t.mutable_data<T>({total_roi_num}, dev_ctx.GetPlace());
144
    phi::DenseTensor index_out_t;
145 146 147 148 149
    int* idx_out =
        index_out_t.mutable_data<int>({total_roi_num}, dev_ctx.GetPlace());

    // Determine temporary device storage requirements
    size_t temp_storage_bytes = 0;
150 151 152 153 154 155 156 157 158 159
    cub::DeviceRadixSort::SortPairsDescending<T, int>(nullptr,
                                                      temp_storage_bytes,
                                                      concat_scores.data<T>(),
                                                      keys_out,
                                                      idx_in,
                                                      idx_out,
                                                      total_roi_num,
                                                      0,
                                                      sizeof(T) * 8,
                                                      dev_ctx.stream());
160
    // Allocate temporary storage
161
    auto d_temp_storage = memory::Alloc(place, temp_storage_bytes);
162

163 164
    // Run sorting operation
    // sort score to get corresponding index
165 166 167 168 169 170 171 172 173 174
    cub::DeviceRadixSort::SortPairsDescending<T, int>(d_temp_storage->ptr(),
                                                      temp_storage_bytes,
                                                      concat_scores.data<T>(),
                                                      keys_out,
                                                      idx_in,
                                                      idx_out,
                                                      total_roi_num,
                                                      0,
                                                      sizeof(T) * 8,
                                                      dev_ctx.stream());
175
    index_out_t.Resize({real_post_num});
176
    phi::DenseTensor sorted_rois;
177
    sorted_rois.mutable_data<T>({real_post_num, kBBoxSize}, dev_ctx.GetPlace());
178
    phi::DenseTensor sorted_batch_id;
179
    sorted_batch_id.mutable_data<int>({real_post_num}, dev_ctx.GetPlace());
180
    phi::funcs::GPUGather<T>(dev_ctx, concat_rois, index_out_t, &sorted_rois);
181 182
    phi::funcs::GPUGather<int>(
        dev_ctx, roi_batch_id_list_gpu, index_out_t, &sorted_batch_id);
183

184
    phi::DenseTensor batch_index_t;
185 186
    int* batch_idx_in =
        batch_index_t.mutable_data<int>({real_post_num}, dev_ctx.GetPlace());
L
Leo Chen 已提交
187
    platform::ForRange<phi::GPUContext> for_range_post(dev_ctx, real_post_num);
188 189
    for_range_post(RangeInitFunctor{0, 1, batch_idx_in});

190
    phi::DenseTensor out_id_t;
191 192 193 194
    int* out_id_data =
        out_id_t.mutable_data<int>({real_post_num}, dev_ctx.GetPlace());
    // Determine temporary device storage requirements
    temp_storage_bytes = 0;
195 196 197 198 199 200 201 202 203 204
    cub::DeviceRadixSort::SortPairs<int, int>(nullptr,
                                              temp_storage_bytes,
                                              sorted_batch_id.data<int>(),
                                              out_id_data,
                                              batch_idx_in,
                                              index_out_t.data<int>(),
                                              real_post_num,
                                              0,
                                              sizeof(int) * 8,
                                              dev_ctx.stream());
205
    // Allocate temporary storage
206
    d_temp_storage = memory::Alloc(place, temp_storage_bytes);
207

208 209
    // Run sorting operation
    // sort batch_id to get corresponding index
210 211 212 213 214 215 216 217 218 219
    cub::DeviceRadixSort::SortPairs<int, int>(d_temp_storage->ptr(),
                                              temp_storage_bytes,
                                              sorted_batch_id.data<int>(),
                                              out_id_data,
                                              batch_idx_in,
                                              index_out_t.data<int>(),
                                              real_post_num,
                                              0,
                                              sizeof(int) * 8,
                                              dev_ctx.stream());
220

221
    phi::funcs::GPUGather<T>(dev_ctx, sorted_rois, index_out_t, fpn_rois);
222

223
    phi::DenseTensor length_lod;
224 225
    int* length_lod_data =
        length_lod.mutable_data<int>({lod_size}, dev_ctx.GetPlace());
L
Leo Chen 已提交
226
    phi::funcs::SetConstant<phi::GPUContext, int> set_zero;
227 228 229 230 231 232
    set_zero(dev_ctx, &length_lod, static_cast<int>(0));

    int blocks = NumBlocks(real_post_num);
    int threads = kNumCUDAThreads;

    // get length-based lod by batch ids
233 234
    GetLengthLoD<<<blocks, threads, 0, dev_ctx.stream()>>>(
        real_post_num, out_id_data, length_lod_data);
235
    std::vector<int> length_lod_cpu(lod_size);
236 237 238 239 240 241
    memory::Copy(platform::CPUPlace(),
                 length_lod_cpu.data(),
                 place,
                 length_lod_data,
                 sizeof(int) * lod_size,
                 dev_ctx.stream());
242 243 244 245 246 247 248
    dev_ctx.Wait();

    std::vector<size_t> offset(1, 0);
    for (int i = 0; i < lod_size; ++i) {
      offset.emplace_back(offset.back() + length_lod_cpu[i]);
    }

249
    if (ctx.HasOutput("RoisNum")) {
250
      auto* rois_num = ctx.Output<phi::DenseTensor>("RoisNum");
251
      int* rois_num_data = rois_num->mutable_data<int>({lod_size}, place);
252 253 254 255 256 257
      memory::Copy(place,
                   rois_num_data,
                   place,
                   length_lod_data,
                   lod_size * sizeof(int),
                   dev_ctx.stream());
258 259
    }

260 261 262 263 264 265 266 267 268 269 270 271
    framework::LoD lod;
    lod.emplace_back(offset);
    fpn_rois->set_lod(lod);
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OP_CUDA_KERNEL(
    collect_fpn_proposals,
L
Leo Chen 已提交
272 273
    ops::GPUCollectFpnProposalsOpKernel<phi::GPUContext, float>,
    ops::GPUCollectFpnProposalsOpKernel<phi::GPUContext, double>);