File size: 14,591 Bytes
e05eed1 98a67a0 |
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 |
// SPDX-FileCopyrightText: Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
#include "non_maximal_suppression.h"
#include <algorithm>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
#include <chrono>
#include <cuda_runtime.h>
#include <fstream>
#include "../geometry.h"
#include "../common.h"
#include "nms_kd_tree.h"
using namespace std;
namespace ix = torch::indexing;
typedef EmbedQuad_<float> EFQuad;
nms_result_t quad_non_maximal_suppression_cpu_impl(
torch::Tensor tQuads, torch::Tensor tProbs,
float probThreshold, float iouThreshold,
int64_t kernelHeight, int64_t kernelWidth,
int64_t maxRegions,
bool verbose)
{
tQuads = tQuads.to(torch::kFloat32).to(torch::kCPU, /*non_blocking=*/ true);
tProbs = tProbs.to(torch::kFloat32).to(torch::kCPU, /*non_blocking=*/ true);
auto tStart = chrono::high_resolution_clock::now();
cudaDeviceSynchronize();
auto tData = chrono::high_resolution_clock::now();
if (maxRegions == 0) {
maxRegions = numeric_limits<int64_t>::max();
}
// B,H,W,4,2
auto quadsAccess = tQuads.accessor<float, 5>();
// B,H,W
auto probsAccess = tProbs.accessor<float, 3>();
const int64_t B = probsAccess.size(0);
vector<vector<EFQuad>> allQuads{ (unsigned int)B };
vector<vector<EFQuad>> batchQuads{ (unsigned int)B };
vector<vector<vector<size_t>>> batchAdjIdxs{ (unsigned int)B };
vector<unordered_set<size_t>> batchVisited{ (unsigned int)B };
vector<NMS_KDTree<EFQuad>> batchKDTrees{ (unsigned int)B };
decltype(tData) tRowSpan, tBuildKD, tAdjacent;
// Only enable parallelism if release mode
#ifndef NDEBUG
#pragma omp parallel num_threads (8)
#endif
{
// Step 1: Combine quads by row
// Parallelize on both batch and rows
#ifndef NDEBUG
#pragma omp for collapse (2)
#endif
for (int64_t batchIdx = 0; batchIdx < B; ++batchIdx) {
for (int64_t row = 0; row < probsAccess.size(1); ++row) {
vector<EFQuad>& quads = batchQuads[batchIdx];
EFQuad currQuad;
auto commitQuad = [&]() {
if (currQuad.NumQuads > 0) {
#pragma omp critical
{
if (quads.size() < maxRegions) {
quads.push_back(currQuad);
}
}
currQuad.Reset();
}
};
for (int64_t col = 0; col < probsAccess.size(2); ++col) {
Quad_<float> predQuad{ quadsAccess[batchIdx][row][col].data() };
float predConf = probsAccess[batchIdx][row][col];
// If we're currently in a span, then merge
if (predConf >= probThreshold) {
auto iou = currQuad.NumQuads > 0 ? predQuad.IOU_UpperBound(currQuad) : 0;
// These two regions aren't mergable. Finalize the current quad, and start a new one
if (iou < iouThreshold) {
commitQuad();
}
currQuad.Append(predQuad, predConf);
}
// Otherwise, commit it if valid
else {
commitQuad();
}
}
// Capture any dangling span
commitQuad();
}
}
#ifndef NDEBUG
#pragma omp single
#endif
{
tRowSpan = chrono::high_resolution_clock::now();
}
#ifndef NDEBUG
#pragma omp for
#endif
for (int64_t batchIdx = 0; batchIdx < B; ++batchIdx) {
batchKDTrees[batchIdx].Build(batchQuads[batchIdx]);
}
static const int64_t TASK_SIZE = 2;
// Step 2: At this point, we have the set of row-merged quads, so now we
// apply the real merge algorithm. For this, we start with an adjacency matrix.
//
// OMP note: "single" means that only one of the threads in the parallel group will execute this block.
// We're using tasking here to add a bunch of work to the thread pool that will be processed concurrently.
#ifndef NDEBUG
#pragma omp single
#endif
{
tBuildKD = chrono::high_resolution_clock::now();
for (int64_t batchIdx = 0; batchIdx < B; ++batchIdx) {
int64_t numQuads = batchQuads[batchIdx].size();
batchAdjIdxs[batchIdx].resize(numQuads);
for (int64_t q = 0; q < numQuads; q += TASK_SIZE) {
// This defines a task that will be executed in parallel by the pool
// OMP note:
// "shared" essentially means that we're capturing these variables by reference
// "firstprivate" means that we're capturing these variables by value
#ifndef NDEBUG
#pragma omp task default(none) shared(batchAdjIdxs, batchQuads, batchKDTrees, batchVisited, iouThreshold) firstprivate(batchIdx, numQuads, q)
#endif
{
vector<EFQuad>& quads = batchQuads[batchIdx];
auto& kdTree = batchKDTrees[batchIdx];
unordered_set<size_t>& visited = batchVisited[batchIdx];
for (int64_t n = q, nend = min(numQuads, q + TASK_SIZE); n < nend; ++n) {
vector<size_t>& adjIdxs = batchAdjIdxs[batchIdx][n];
kdTree.FindIntersections(n,
[n, iouThreshold, &quads, &visited, &adjIdxs](size_t m, float bdsPctN, float bdsPctM, float bdsIOU) {
float pctN, pctM, iou;
tie(pctN, pctM, iou) = geometry_region_sizes(quads[n], quads[m]);
// Merge
if (iou >= iouThreshold) {
adjIdxs.push_back(m);
// The next two cases are when one region envelops the other. In this case, take the larger region.
// If iou > 0, then they overlap at least somewhat
}
else if (pctN > 0.8 || pctM > 0.8) {
float nHeight = quads[n].Height();
float mHeight = quads[m].Height();
float ratio = nHeight > mHeight ? mHeight / nHeight : nHeight / mHeight;
// If the two quads are roughly the same height (within 90% of each other), then eliminate the smaller region
if (ratio > 0.9) {
if (pctN > 0.8) {
// M envelops N
#pragma omp critical
// Marking a node as visited will prevent it from being processed during the adjacency collapse phase
visited.insert(n);
}
else if (pctM > 0.8) {
// N envelops M
#pragma omp critical
visited.insert(m);
}
}
}
}
);
}
}
}
}
#ifndef NDEBUG
#pragma omp taskwait
#endif
tAdjacent = chrono::high_resolution_clock::now();
}
#ifndef NDEBUG
#pragma omp for
#endif
for (int64_t batchIdx = 0; batchIdx < B; ++batchIdx) {
vector<vector<size_t>>& adjIdxs = batchAdjIdxs[batchIdx];
vector<EFQuad>& quads = batchQuads[batchIdx];
vector<EFQuad>& finalQuads = allQuads[batchIdx];
unordered_set<size_t>& visited = batchVisited[batchIdx];
// Step 3: Using depth first search, merge the regions
for (int64_t n = 0; n < quads.size(); ++n) {
EFQuad currQuad;
visit_node(quads, n, adjIdxs, currQuad, visited);
if (currQuad.NumQuads > 0) {
currQuad.Prepare();
finalQuads.push_back(currQuad);
}
}
}
} // End parallel
auto tMerge = chrono::high_resolution_clock::now();
int64_t numOutQuads = 0;
for (int64_t batchIdx = 0; batchIdx < B; ++batchIdx) {
numOutQuads += allQuads[batchIdx].size();
}
// Allocate the output tensors in pinned memory because they will be immediately sent back to the GPU
auto pinnedOpt = torch::TensorOptions().pinned_memory(true);
// Step 4: Convert the quads into tensor representation
auto outQuadTensor = torch::empty({ numOutQuads, 4, 2 }, pinnedOpt.dtype(torch::kFloat32));
auto outConfTensor = torch::empty({ numOutQuads }, pinnedOpt.dtype(torch::kFloat32));
auto outCountTensor = torch::empty({ (int)allQuads.size() }, pinnedOpt.dtype(torch::kInt64));
auto outQuadAccess = outQuadTensor.accessor<float, 3>();
auto outConfAccess = outConfTensor.accessor<float, 1>();
auto outCountAccess = outCountTensor.accessor<int64_t, 1>();
int64_t offset = 0;
for (int64_t batchIdx = 0; batchIdx < allQuads.size(); ++batchIdx) {
vector<EFQuad>& exQuads = allQuads[batchIdx];
outCountAccess[batchIdx] = exQuads.size();
for (int64_t qIdx = 0; qIdx < exQuads.size(); ++qIdx, ++offset) {
copy_quad(exQuads[qIdx], outQuadAccess[offset].data());
outConfAccess[offset] = exQuads[qIdx].Confidence;
}
}
if (verbose) {
auto tWrite = chrono::high_resolution_clock::now();
typedef chrono::duration<double, std::milli> tp_t;
tp_t dataElapsed = tData - tStart;
tp_t rowSpanElapsed = tRowSpan - tData;
tp_t buildKDElapsed = tBuildKD - tRowSpan;
tp_t adjacentElapsed = tAdjacent - tBuildKD;
tp_t mergeElapsed = tMerge - tAdjacent;
tp_t writeElapsed = tWrite - tMerge;
tp_t totalElapsed = tWrite - tStart;
// print_tensor(outCountTensor);
cout << "NMS " << numOutQuads
<< " - Wait for data: " << dataElapsed.count() << "ms"
<< ", Row Span: " << rowSpanElapsed.count() << "ms"
<< ", Build KD: " << buildKDElapsed.count() << "ms"
<< ", Adjacency: " << adjacentElapsed.count() << "ms"
<< ", Merge: " << mergeElapsed.count() << "ms"
<< ", Write: " << writeElapsed.count() << "ms"
<< ", Total: " << totalElapsed.count() << "ms"
<< endl;
}
return { outQuadTensor, outConfTensor, outCountTensor };
}
nms_result_t quad_non_maximal_suppression(
torch::Tensor tQuads, torch::Tensor tProbs,
float probThreshold, float iouThreshold,
int64_t kernelHeight, int64_t kernelWidth,
int64_t maxRegions,
bool verbose)
{
auto nmsFn = tQuads.is_cuda() ?
cuda_quad_non_maximal_suppression :
quad_non_maximal_suppression_cpu_impl;
torch::Tensor quads, confidence, regionCounts;
tie(quads, confidence, regionCounts) = nmsFn(
tQuads, tProbs,
probThreshold, iouThreshold,
kernelHeight, kernelWidth,
maxRegions, verbose
);
#ifndef NDEBUG
// In debug mode, do cell sorting so that it's easier to see where the quads are
auto cells = get<0>(quads.min(1)).div_(10).floor_();
auto maxX = cells.index({ ix::Slice(), 0 }).max();
cells = maxX * cells.select(1, 1) + cells.select(1, 0);
// Ensure that we keep them ordered by example
auto regionIdxs = torch::arange(regionCounts.size(0), cells.options()).repeat_interleave(regionCounts);
auto cellMax = cells.max();
cells += cellMax * regionIdxs;
auto order = torch::argsort(cells);
quads = quads.index({ order });
confidence = confidence.index({ order });
#endif
return { quads, confidence, regionCounts };
}
vector<TEFQuad> reduced_quad_non_maximal_suppression(
const vector<TIPQuad> &rowQuads, float iouThreshold, int64_t imageHeight, int64_t imageWidth)
{
// auto tStart = chrono::high_resolution_clock::now();
vector<TEFQuad> allQuads;
TEFQuad currQuad;
auto commitQuad = [&] () {
if (currQuad.NumQuads > 0) {
allQuads.push_back(move(currQuad));
}
currQuad.Reset();
};
for (const auto &thisQuad : rowQuads) {
auto iou = currQuad.NumQuads > 0 ? thisQuad.IOU_UpperBound(currQuad) : 0;
// These two regions aren't mergeable. Finalize the current quad, and start a new one
if (iou < iouThreshold) {
commitQuad();
}
currQuad.Append(thisQuad, 1);
}
// Capture any dangling span
commitQuad();
const int64_t numQuads = allQuads.size();
vector<TEFQuad> mergeQuads;
vector<bool> visited;
visited.resize(numQuads, false);
NMS_KDTree<TEFQuad> kdTree;
kdTree.Build(allQuads);
for (int64_t row = 0; row < numQuads; ++row) {
if (visited[row]) continue;
TEFQuad &rowQuad = allQuads[row];
kdTree.FindIntersections(row,
[row, iouThreshold, &rowQuad, &allQuads, &visited] (size_t col, float pctN, float pctM, float iou) {
if (iou >= iouThreshold && ! visited[col]) {
rowQuad.Append(move(allQuads[col]));
visited[col] = true;
}
}
);
mergeQuads.push_back(move(rowQuad));
}
// auto tEnd = chrono::high_resolution_clock::now();
// chrono::duration<double, std::milli> totalElapsed = tEnd - tStart;
// cout << "Row NMS " << mergeQuads.size() << " - Time: " << totalElapsed.count() << "ms" << endl;
return mergeQuads;
}
|