From a06a29dc4115457c9df134a4c554caad3acdf488 Mon Sep 17 00:00:00 2001 From: pbkx <93405617+pbkx@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:57:19 -0800 Subject: [PATCH] dnn: fix NonZero output for grouped parallel ranges (#31009) Incorrect prefix offsets can be generated when different partitions are used for counting and emission, leading to some coordinates being overwritten or not written at all. Despite this, the output shape remains correct. Each logical stripe is counted independently. We have added a parameterized test for dense and sparse inputs. It covers three different counting partitions and tests that all coordinates are correctly generated in row-major order. The test also verifies that the output shape and type are correct, that output memory was reused and that input data was preserved. --- modules/dnn/src/layers/nonzero_layer.cpp | 15 +++--- modules/dnn/test/test_layers.cpp | 64 ++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/modules/dnn/src/layers/nonzero_layer.cpp b/modules/dnn/src/layers/nonzero_layer.cpp index 7353ccc612..9cc0997152 100644 --- a/modules/dnn/src/layers/nonzero_layer.cpp +++ b/modules/dnn/src/layers/nonzero_layer.cpp @@ -28,12 +28,15 @@ static size_t computeNonZeroCountsPerStripe(const T* data, size_t total, int nst if (total == 0) return 0; cv::parallel_for_(cv::Range(0, nstripes), [&](const cv::Range& range) { - const size_t i0 = total * (size_t)range.start / (size_t)nstripes; - const size_t i1 = total * (size_t)range.end / (size_t)nstripes; - size_t nz = 0; - for (size_t i = i0; i < i1; ++i) - nz += isNonZero(data[i]); - nzcounts[(size_t)range.start] = nz; + for (int stripe = range.start; stripe < range.end; ++stripe) + { + const size_t i0 = total * (size_t)stripe / (size_t)nstripes; + const size_t i1 = total * (size_t)(stripe + 1) / (size_t)nstripes; + size_t nz = 0; + for (size_t i = i0; i < i1; ++i) + nz += isNonZero(data[i]); + nzcounts[(size_t)stripe] = nz; + } }); size_t total_nz = 0; diff --git a/modules/dnn/test/test_layers.cpp b/modules/dnn/test/test_layers.cpp index 42564c0090..831de9b290 100644 --- a/modules/dnn/test/test_layers.cpp +++ b/modules/dnn/test/test_layers.cpp @@ -42,6 +42,7 @@ #include "test_precomp.hpp" #include #include +#include #include "npy_blob.hpp" #include #include @@ -63,6 +64,69 @@ static String _tf(TString filename) return (basetestdir + "dnn/layers/") + filename; } +#if GTEST_HAS_DEATH_TEST +class NonZeroGroupingBackend CV_FINAL : public cv::parallel::ParallelForAPI +{ +public: + NonZeroGroupingBackend() : calls(0) {} + + void parallel_for(int tasks, FN_parallel_for_body_cb_t callback, void* data) CV_OVERRIDE + { + const int firstEnd = calls++ == 0 ? std::min(2, tasks) : 1; + callback(0, firstEnd, data); + for (int stripe = firstEnd; stripe < tasks; ++stripe) + callback(stripe, stripe + 1, data); + } + + int getThreadNum() const CV_OVERRIDE { return 0; } + int getNumThreads() const CV_OVERRIDE { return 4; } + int setNumThreads(int) CV_OVERRIDE { return 4; } + const char* getName() const CV_OVERRIDE { return "NonZeroGrouping"; } + + int calls; +}; +#endif + +TEST(Layer_NonZeroDeathTest, partition_independence) +{ +#if GTEST_HAS_DEATH_TEST + // Re-execution needs GTest's saved working directory; otherwise use fork on POSIX. + const bool canReexec = ::testing::UnitTest::GetInstance()->original_working_dir()[0] != '\0'; +#if defined(_WIN32) + if (!canReexec) + throw SkipTestException("NonZero partition test requires GTest subprocess support"); +#endif + ::testing::GTEST_FLAG(death_test_style) = canReexec ? "threadsafe" : "fast"; + // Keep the process-global backend override in the child, including on assertion failure. + EXPECT_EXIT(([] { + Mat input(4, 8, CV_32F, Scalar(1)); + LayerParams params; + Ptr layer = NonZeroLayer::create(params); + std::vector inputs{input}, internals; + std::vector outputs{Mat(2, (int)input.total(), CV_64S, Scalar(-999))}; + auto backend = std::make_shared(); + cv::parallel::setParallelForBackend(backend, false); + cv::setNumThreads(4); + layer->forward(inputs, outputs, internals); + + ASSERT_EQ(2, backend->calls); + ASSERT_EQ((size_t)1, outputs.size()); + ASSERT_EQ(2, outputs[0].dims); + ASSERT_EQ(input.dims, outputs[0].rows); + ASSERT_EQ((int)input.total(), outputs[0].cols); + ASSERT_EQ(CV_64SC1, outputs[0].type()); + for (int i = 0; i < (int)input.total(); ++i) + { + EXPECT_EQ(i / input.cols, outputs[0].ptr(0)[i]) << "column " << i; + EXPECT_EQ(i % input.cols, outputs[0].ptr(1)[i]) << "column " << i; + } + std::exit(::testing::Test::HasFailure() ? EXIT_FAILURE : EXIT_SUCCESS); + }()), ::testing::ExitedWithCode(EXIT_SUCCESS), ""); +#else + throw SkipTestException("NonZero partition test requires Google Test process isolation"); +#endif +} + void testReshape(const MatShape& inputShape, const MatShape& targetShape, int axis = 0, int num_axes = -1, MatShape mask = MatShape())