diff --git a/modules/core/include/opencv2/core.hpp b/modules/core/include/opencv2/core.hpp index b8efd1c5ba..59cfbcfa8e 100644 --- a/modules/core/include/opencv2/core.hpp +++ b/modules/core/include/opencv2/core.hpp @@ -165,7 +165,12 @@ enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/column REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix. REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix. REDUCE_MIN = 3, //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix. - REDUCE_SUM2 = 4 //!< the output is the sum of all squared rows/columns of the matrix. + REDUCE_SUM2 = 4, //!< the output is the sum of all squared rows/columns of the matrix. + REDUCE_PROD = 5, //!< the output is the product of the elements. + REDUCE_L1 = 6, //!< the output is the sum of the absolute values. + REDUCE_L2 = 7, //!< the output is the square root of the sum of the squares. + REDUCE_LOG_SUM = 8, //!< the output is the logarithm of the sum. + REDUCE_LOG_SUM_EXP = 9 //!< the output is log(sum(exp(x))), computed without overflow. }; /** @brief Swaps two matrices @@ -892,7 +897,8 @@ The following code demonstrates its usage for a single channel matrix. And the following code demonstrates its usage for a two-channel matrix. @snippet snippets/core_reduce.cpp example2 -@param src input 2D matrix. +@param src input matrix. It may also be n-dimensional, then @p dim is the axis to reduce and the +output keeps it with size 1 (see the cv::ReduceParams overload). @param dst output vector. Its size and type is defined by dim and dtype parameters. @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row. 1 means that the matrix is reduced to a single column. @@ -903,6 +909,53 @@ otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). */ CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1); +/** @brief The reduction that the n-dimensional #reduce performs. + +Everything the call needs besides the input and the output arrays, in one struct, so that further +options can be added without changing the signature. + +@sa reduce +*/ +struct CV_EXPORTS_W_SIMPLE ReduceParams +{ + CV_WRAP ReduceParams(int rtype = REDUCE_SUM, const std::vector& axes = std::vector(), + bool keepdims = true, int dtype = -1); + + //! reduction operation, one of #ReduceTypes. + CV_PROP_RW int rtype; + //! axes to reduce; negative values count from the end; an empty vector means all the axes. + CV_PROP_RW std::vector axes; + //! whether to keep the reduced axes as axes of size 1. + CV_PROP_RW bool keepdims; + //! depth of the output; when negative, the output has the depth of the input. The result is + //! converted to it with saturation. + CV_PROP_RW int dtype; +}; + +/** @brief Reduces an n-dimensional array over the given axes. + +Every output element is the reduction (see #ReduceTypes) of the input elements that differ only in +the reduced axes. The channels are reduced independently, so the output has as many channels as the +input. The input may be non-continuous (e.g. a sub-array) and of any depth. + +The accumulation is done in the source type for #REDUCE_MAX and #REDUCE_MIN (in float for 16-bit +floating-point types) and in float or double for the other operations (double for 32- and 64-bit +integers, for CV_64F, and when the output depth is CV_64F). + +@code{.cpp} + Mat blob(std::vector{1, 256, 80, 80}, CV_32F), channelMeans; + cv::reduce(blob, channelMeans, {REDUCE_AVG, {2, 3}}); // -> 1x256x1x1 +@endcode + +@param src input array. +@param dst output array. With ReduceParams::keepdims, it has the shape of src with the reduced axes +set to 1; otherwise the reduced axes are removed (reducing all the axes then gives a 0-dimensional +array). +@param params the reduction operation and the axes to reduce over, see cv::ReduceParams. +@sa ReduceParams, sum, mean, minMaxIdx +*/ +CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, const ReduceParams& params); + /** @brief Creates one multi-channel array out of several single-channel ones. The function cv::merge merges several arrays to make a single multi-channel array. That is, each diff --git a/modules/core/perf/perf_reduce_nd.cpp b/modules/core/perf/perf_reduce_nd.cpp new file mode 100644 index 0000000000..93b9710d76 --- /dev/null +++ b/modules/core/perf/perf_reduce_nd.cpp @@ -0,0 +1,48 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +#include "perf_precomp.hpp" + +namespace opencv_test { +using namespace perf; + +CV_ENUM(ReduceNDOp, REDUCE_SUM, REDUCE_AVG, REDUCE_MAX, REDUCE_L2, REDUCE_LOG_SUM_EXP) + +typedef tuple, std::vector, ReduceNDOp, perf::MatType> ReduceNDPerfParams; +typedef TestBaseWithParam ReduceNDPerf; + +PERF_TEST_P_(ReduceNDPerf, reduce) +{ + const std::vector shape = get<0>(GetParam()), axes = get<1>(GetParam()); + const int op = get<2>(GetParam()), type = get<3>(GetParam()); + Mat src(shape, type), dst; + Mat bytes(1, (int)(src.total()*src.elemSize()), CV_8U, src.data); + randu(bytes, 0, 100); // declare.in() only handles 2D arrays + if (CV_MAT_DEPTH(type) == CV_32F) + randu(Mat(1, (int)src.total(), CV_32F, src.data), -1, 1); + const ReduceParams params(op, axes); + cv::reduce(src, dst, params); + + TEST_CYCLE() cv::reduce(src, dst, params); + + SANITY_CHECK_NOTHING(); +} + +INSTANTIATE_TEST_CASE_P(/**/, ReduceNDPerf, testing::Combine( + testing::Values(std::vector{1, 256, 80, 80}), + testing::Values(std::vector{1}, std::vector{2, 3}, std::vector{}), + ReduceNDOp::all(), + testing::Values(perf::MatType(CV_32FC1), CV_8UC1) +)); + +INSTANTIATE_TEST_CASE_P(Rows, ReduceNDPerf, testing::Combine( + testing::Values(std::vector{4096, 768}), + testing::Values(std::vector{0}, std::vector{1}), + testing::Values(ReduceNDOp(REDUCE_SUM), ReduceNDOp(REDUCE_MAX)), + testing::Values(perf::MatType(CV_32FC1), CV_16FC1) +)); + +} // namespace diff --git a/modules/core/src/matrix_operations.cpp b/modules/core/src/matrix_operations.cpp index dae9682193..d03570a767 100644 --- a/modules/core/src/matrix_operations.cpp +++ b/modules/core/src/matrix_operations.cpp @@ -765,7 +765,13 @@ void cv::reduce(InputArray _src, OutputArray _dst, int dim, int op, int dtype) { CV_INSTRUMENT_REGION(); - CV_Assert( _src.dims() <= 2 ); + if (_src.dims() > 2 || op > REDUCE_SUM2) + { + CV_CheckGE(dim, -_src.dims(), "reduce: dim is out of range"); + CV_CheckLT(dim, _src.dims(), "reduce: dim is out of range"); + cv::reduce(_src, _dst, cv::ReduceParams(op, {dim}, true, dtype < 0 && _dst.fixedType() ? _dst.depth() : dtype)); + return; + } int op0 = op; int stype = _src.type(), sdepth = CV_MAT_DEPTH(stype), cn = CV_MAT_CN(stype); if( dtype < 0 ) diff --git a/modules/core/src/mean.dispatch.cpp b/modules/core/src/mean.dispatch.cpp index 98ff2483a1..d62b77973e 100644 --- a/modules/core/src/mean.dispatch.cpp +++ b/modules/core/src/mean.dispatch.cpp @@ -6,6 +6,7 @@ #include "precomp.hpp" #include "opencl_kernels_core.hpp" #include "stat.hpp" +#include "stat_parallel.hpp" #include "mean.simd.hpp" #include "mean.simd_declarations.hpp" // defines CV_CPU_DISPATCH_MODES_ALL=AVX2,...,BASELINE based on CMakeLists.txt content @@ -13,13 +14,9 @@ namespace cv { -Scalar mean(InputArray _src, InputArray _mask) +// serial implementation, also used for the pieces of the parallel version +static Scalar mean_(const Mat& src, const Mat& mask) { - CV_INSTRUMENT_REGION(); - - Mat src = _src.getMat(), mask = _mask.getMat(); - CV_Assert( mask.empty() || mask.type() == CV_8U || mask.type() == CV_8S || mask.type() == CV_Bool); - int k, cn = src.channels(), depth = src.depth(); Scalar s = Scalar::all(0.0); @@ -97,6 +94,44 @@ Scalar mean(InputArray _src, InputArray _mask) return s*(nz0 ? 1./nz0 : 0); } +// number of elements a piece contributes to the mean +static double statCount(const StatChunk& c) +{ + return c.mask.empty() ? (double)c.src.total() : (double)countNonZero(c.mask); +} + +Scalar mean(InputArray _src, InputArray _mask) +{ + CV_INSTRUMENT_REGION(); + + Mat src = _src.getMat(), mask = _mask.getMat(); + CV_Assert( mask.empty() || mask.type() == CV_8U || mask.type() == CV_8S || mask.type() == CV_Bool); + + std::vector chunks; + if (src.channels() > 4 || !splitForParallelStat(src, mask, chunks)) + return mean_(src, mask); + + const int n = (int)chunks.size(); + std::vector part(n); + std::vector cnt(n); + parallel_for_(Range(0, n), [&](const Range& r) + { + for (int i = r.start; i < r.end; i++) + { + part[i] = mean_(chunks[i].src, chunks[i].mask); + cnt[i] = statCount(chunks[i]); + } + }); + Scalar s = Scalar::all(0.0); + double total = 0; + for (int i = 0; i < n; i++) + { + s += part[i]*cnt[i]; + total += cnt[i]; + } + return s*(total > 0 ? 1./total : 0); +} + static SumSqrFunc getSumSqrFunc(int depth) { CV_INSTRUMENT_REGION(); @@ -224,10 +259,9 @@ static bool ocl_meanStdDev( InputArray _src, OutputArray _mean, OutputArray _sdv } #endif -void meanStdDev(InputArray _src, OutputArray _mean, OutputArray _sdv, InputArray _mask) +// serial implementation, also used for the pieces of the parallel version +static void meanStdDev_(InputArray _src, OutputArray _mean, OutputArray _sdv, InputArray _mask) { - CV_INSTRUMENT_REGION(); - CV_Assert(!_src.empty()); CV_Assert( _mask.empty() || _mask.type() == CV_8U || _mask.type() == CV_8S || _mask.type() == CV_Bool ); @@ -386,4 +420,76 @@ void meanStdDev(InputArray _src, OutputArray _mean, OutputArray _sdv, InputArray } } +static void writeStatResult(OutputArray _dst, int cn, const Scalar& v) +{ + if (!_dst.needed()) + return; + if (!_dst.fixedSize()) + _dst.create(cn, 1, CV_64F, -1, true); + Mat d = _dst.getMat(); + int dcn = (int)d.total(); + CV_Assert( d.type() == CV_64F && d.isContinuous() && (d.cols == 1 || d.rows == 1) && dcn >= cn ); + double* p = d.ptr(); + for (int k = 0; k < dcn; k++) + p[k] = k < cn ? v[k] : 0; +} + +void meanStdDev(InputArray _src, OutputArray _mean, OutputArray _sdv, InputArray _mask) +{ + CV_INSTRUMENT_REGION(); + + std::vector chunks; + if (!_src.isUMat() && !_src.empty()) + { + Mat src = _src.getMat(), mask = _mask.getMat(); + const int cn = src.channels(); + const bool maskOk = mask.empty() || ((mask.type() == CV_8U || mask.type() == CV_8S || mask.type() == CV_Bool) && + src.size == mask.size); + if (cn <= 4 && maskOk && splitForParallelStat(src, mask, chunks)) + { + const int n = (int)chunks.size(); + std::vector m(n), sd(n); + std::vector cnt(n); + parallel_for_(Range(0, n), [&](const Range& r) + { + for (int i = r.start; i < r.end; i++) + { + Mat mi, si; + meanStdDev_(chunks[i].src, mi, si, chunks[i].mask); + for (int k = 0; k < cn; k++) + { + m[i][k] = mi.at(k); + sd[i][k] = si.at(k); + } + cnt[i] = statCount(chunks[i]); + } + }); + // combine the pieces: the variance is the mean of the piece variances plus the + // variance of the piece means, both weighted by the piece sizes + double total = 0; + Scalar M = Scalar::all(0.0), V = Scalar::all(0.0); + for (int i = 0; i < n; i++) + { + M += m[i]*cnt[i]; + total += cnt[i]; + } + if (total > 0) + M *= 1./total; + for (int i = 0; i < n; i++) + for (int k = 0; k < cn; k++) + { + double dm = m[i][k] - M[k]; + V[k] += cnt[i]*(sd[i][k]*sd[i][k] + dm*dm); + } + Scalar SD; + for (int k = 0; k < cn; k++) + SD[k] = total > 0 ? std::sqrt(std::max(V[k]/total, 0.)) : 0; + writeStatResult(_mean, cn, M); + writeStatResult(_sdv, cn, SD); + return; + } + } + meanStdDev_(_src, _mean, _sdv, _mask); +} + } // namespace diff --git a/modules/core/src/minmax.dispatch.cpp b/modules/core/src/minmax.dispatch.cpp index b411850973..c70ed0facb 100644 --- a/modules/core/src/minmax.dispatch.cpp +++ b/modules/core/src/minmax.dispatch.cpp @@ -6,6 +6,7 @@ #include "precomp.hpp" #include "opencl_kernels_core.hpp" #include "stat.hpp" +#include "stat_parallel.hpp" #include "opencv2/core/detail/dispatch_helper.impl.hpp" #include @@ -297,12 +298,12 @@ bool ocl_minMaxIdx( InputArray _src, double* minVal, double* maxVal, int* minLoc } -void cv::minMaxIdx(InputArray _src, double* minVal, - double* maxVal, int* minIdx, int* maxIdx, - InputArray _mask) +// serial implementation, also used for the pieces of the parallel version +static void minMaxIdx_(cv::InputArray _src, double* minVal, + double* maxVal, int* minIdx, int* maxIdx, + cv::InputArray _mask) { - CV_INSTRUMENT_REGION(); - + using namespace cv; int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); CV_Assert( (cn == 1 && (_mask.empty() || _mask.type() == CV_8U || _mask.type() == CV_8S || _mask.type() == CV_Bool)) || (cn > 1 && _mask.empty() && !minIdx && !maxIdx) ); @@ -390,6 +391,61 @@ void cv::minMaxIdx(InputArray _src, double* minVal, ofs2idx(src, maxidx, maxIdx); } +void cv::minMaxIdx(InputArray _src, double* minVal, + double* maxVal, int* minIdx, int* maxIdx, + InputArray _mask) +{ + CV_INSTRUMENT_REGION(); + + std::vector chunks; + if (!_src.isUMat()) + { + Mat src = _src.getMat(), mask = _mask.getMat(); + const int cn = src.channels(); + const bool argsOk = (cn == 1 && (mask.empty() || ((mask.type() == CV_8U || mask.type() == CV_8S || + mask.type() == CV_Bool) && src.size == mask.size))) || + (cn > 1 && mask.empty() && !minIdx && !maxIdx); + if (argsOk && splitForParallelStat(src, mask, chunks)) + { + const int n = (int)chunks.size(); + std::vector mn(n), mx(n); + std::vector imn(n, 0), imx(n, 0); // 1-based row-major indices, 0 = no element + parallel_for_(Range(0, n), [&](const Range& r) + { + for (int i = r.start; i < r.end; i++) + { + int a[2] = {-1, -1}, b[2] = {-1, -1}; + minMaxIdx_(chunks[i].src, &mn[i], &mx[i], cn == 1 ? a : nullptr, cn == 1 ? b : nullptr, + chunks[i].mask); + if (cn > 1) + imn[i] = imx[i] = 1; + else if (a[0] >= 0) + { + imn[i] = chunkIndexToElem(chunks[i], a) + 1; + imx[i] = chunkIndexToElem(chunks[i], b) + 1; + } + } + }); + // pieces are in memory order, so taking the first strict improvement keeps the + // first occurrence, as in the serial version + int bmin = -1, bmax = -1; + for (int i = 0; i < n; i++) + { + if (imn[i] == 0) + continue; + if (bmin < 0 || mn[i] < mn[bmin]) bmin = i; + if (bmax < 0 || mx[i] > mx[bmax]) bmax = i; + } + if (minVal) *minVal = bmin >= 0 ? mn[bmin] : 0; + if (maxVal) *maxVal = bmax >= 0 ? mx[bmax] : 0; + if (minIdx) ofs2idx(src, bmin >= 0 ? imn[bmin] : 0, minIdx); + if (maxIdx) ofs2idx(src, bmax >= 0 ? imx[bmax] : 0, maxIdx); + return; + } + } + minMaxIdx_(_src, minVal, maxVal, minIdx, maxIdx, _mask); +} + void cv::minMaxLoc( InputArray _img, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc, InputArray mask ) { diff --git a/modules/core/src/reduce_nd.cpp b/modules/core/src/reduce_nd.cpp new file mode 100644 index 0000000000..b50941f751 --- /dev/null +++ b/modules/core/src/reduce_nd.cpp @@ -0,0 +1,760 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +// cv::reduce: reduction of an n-dimensional array over any set of axes. + +#include "precomp.hpp" +#include "opencv2/core/hal/intrin.hpp" + +#include +#include +#include + +namespace cv { + +namespace { + +enum +{ + RND_MAX_DIMS = CV_MAX_DIM + 1, // + the channel axis + RND_BLOCK = 1024, // elements converted per call when the source needs conversion + RND_VCHUNK = 1024, // innermost-axis chunk in the vertical kernel + RND_SERIAL_WORK = 64*1024, // below this (source elements) everything runs in one thread + RND_STRIPE_WORK = 64*1024 +}; + +//////////////////////////////// vector traits //////////////////////////////// + +template struct VecT { enum { ok = 0 }; typedef T vtype; }; +#if (CV_SIMD || CV_SIMD_SCALABLE) +#define CV_RND_VEC(T, V) template<> struct VecT { enum { ok = 1 }; typedef V vtype; }; +CV_RND_VEC(uchar, v_uint8) +CV_RND_VEC(schar, v_int8) +CV_RND_VEC(ushort, v_uint16) +CV_RND_VEC(short, v_int16) +CV_RND_VEC(unsigned, v_uint32) +CV_RND_VEC(int, v_int32) +CV_RND_VEC(float, v_float32) +#if (CV_SIMD_64F || CV_SIMD_SCALABLE_64F) +CV_RND_VEC(double, v_float64) +#endif +#undef CV_RND_VEC +#endif + +//////////////////////////////// operations //////////////////////////////// +// apply() folds one element into an accumulator, combine() merges two accumulators, +// finalize() turns an accumulator into the result. The vector versions are only used +// for the accumulator types that have them (see VecT). + +template struct OpSum +{ + static A init() { return A(0); } + static A apply(A a, A x) { return a + x; } + static A combine(A a, A b) { return a + b; } + static A finalize(A a, int64) { return a; } + template static V vapply(const V& a, const V& x) { return v_add(a, x); } + template static V vcombine(const V& a, const V& b) { return v_add(a, b); } +}; + +template struct OpAvg : OpSum +{ + static A finalize(A a, int64 n) { return n > 0 ? A(a/(double)n) : A(0); } +}; + +template struct OpLogSum : OpSum +{ + static A finalize(A a, int64) { return A(std::log(a)); } +}; + +template struct OpSum2 : OpSum +{ + static A apply(A a, A x) { return a + x*x; } + template static V vapply(const V& a, const V& x) { return v_add(a, v_mul(x, x)); } +}; + +template struct OpL2 : OpSum2 +{ + static A finalize(A a, int64) { return A(std::sqrt(a)); } +}; + +template struct OpL1 : OpSum +{ + static A apply(A a, A x) { return a + (x < A(0) ? -x : x); } + template static V vapply(const V& a, const V& x) { return v_add(a, v_abs(x)); } +}; + +template struct OpProd +{ + static A init() { return A(1); } + static A apply(A a, A x) { return a*x; } + static A combine(A a, A b) { return a*b; } + static A finalize(A a, int64) { return a; } + template static V vapply(const V& a, const V& x) { return v_mul(a, x); } + template static V vcombine(const V& a, const V& b) { return v_mul(a, b); } +}; + +// Identity elements of max and min. A trait rather than a ternary on has_infinity, so that the +// unary minus is never compiled for an unsigned A (MSVC C4146). +template::has_infinity> struct Extremes +{ + static A low() { return std::numeric_limits::lowest(); } + static A high() { return std::numeric_limits::max(); } +}; + +template struct Extremes +{ + static A low() { return -std::numeric_limits::infinity(); } + static A high() { return std::numeric_limits::infinity(); } +}; + +template struct OpMax +{ + static A init() { return Extremes::low(); } + static A apply(A a, A x) { return a < x ? x : a; } + static A combine(A a, A b) { return a < b ? b : a; } + static A finalize(A a, int64) { return a; } + template static V vapply(const V& a, const V& x) { return v_max(a, x); } + template static V vcombine(const V& a, const V& b) { return v_max(a, b); } +}; + +template struct OpMin +{ + static A init() { return Extremes::high(); } + static A apply(A a, A x) { return x < a ? x : a; } + static A combine(A a, A b) { return b < a ? b : a; } + static A finalize(A a, int64) { return a; } + template static V vapply(const V& a, const V& x) { return v_min(a, x); } + template static V vcombine(const V& a, const V& b) { return v_min(a, b); } +}; + +// second pass of log-sum-exp: sum(exp(x - m)), then m + log(sum), where m is the maximum +template struct OpSumExpShifted +{ + static A init() { return A(0); } + static A apply(A a, A x, A m) { return a + A(std::exp(x - m)); } + static A combine(A a, A b) { return a + b; } + static A finalize(A a, A m) { return std::isinf(m) ? m : m + A(std::log(a)); } +}; + +//////////////////////////////// row kernels //////////////////////////////// + +// horizontal: fold n contiguous elements into a scalar accumulator +template::ok != 0)> struct HRow +{ + static A run(A acc, const A* x, int64 n) + { + for (int64 i = 0; i < n; i++) + acc = Op::apply(acc, x[i]); + return acc; + } +}; + +// vertical: acc[i] = apply(acc[i], x[i]) +template::ok != 0)> struct VRow +{ + static void run(A* acc, const A* x, int64 n) + { + for (int64 i = 0; i < n; i++) + acc[i] = Op::apply(acc[i], x[i]); + } +}; + +#if (CV_SIMD || CV_SIMD_SCALABLE) +template struct HRow +{ + static A run(A acc, const A* x, int64 n) + { + typedef typename VecT::vtype V; + const int L = VTraits::vlanes(); + int64 i = 0; + if (n >= 2*L) + { + A buf[VTraits::max_nlanes]; + for (int k = 0; k < L; k++) + buf[k] = Op::init(); + V a0 = vx_load(buf), a1 = a0; + for (; i + 2*L <= n; i += 2*L) + { + a0 = Op::vapply(a0, vx_load(x + i)); + a1 = Op::vapply(a1, vx_load(x + i + L)); + } + v_store(buf, Op::vcombine(a0, a1)); + for (int k = 0; k < L; k++) + acc = Op::combine(acc, buf[k]); + } + for (; i < n; i++) + acc = Op::apply(acc, x[i]); + return acc; + } +}; + +template struct VRow +{ + static void run(A* acc, const A* x, int64 n) + { + typedef typename VecT::vtype V; + const int L = VTraits::vlanes(); + int64 i = 0; + for (; i + L <= n; i += L) + v_store(acc + i, Op::vapply(vx_load(acc + i), vx_load(x + i))); + for (; i < n; i++) + acc[i] = Op::apply(acc[i], x[i]); + } +}; +#endif + +//////////////////////////////// plan //////////////////////////////// + +struct Plan +{ + // kept axes (outer first); ksstep in bytes, kdstep in result elements + int nk; + int ksize[RND_MAX_DIMS]; + ptrdiff_t ksstep[RND_MAX_DIMS], kdstep[RND_MAX_DIMS]; + // reduced axes (outer first), steps in bytes + int nr; + int rsize[RND_MAX_DIMS]; + ptrdiff_t rsstep[RND_MAX_DIMS]; + bool innerReduced; // the innermost axis is reduced (horizontal mode) + + const uchar* src; + int sdepth, adepth; // source depth and accumulator depth + size_t sesz1; + int64 count; // reduced elements per output + int64 nout; // number of outputs + BinaryFunc cvt; // source -> accumulator conversion, or nullptr +}; + +// iterator over the flat index space of some axes, tracking a byte offset and an element offset +struct Iter +{ + int n = 0; + const int* size = nullptr; + const ptrdiff_t* s = nullptr; + const ptrdiff_t* d = nullptr; + int64 idx[RND_MAX_DIMS]; + ptrdiff_t soff = 0, doff = 0; + + void init(int n_, const int* size_, const ptrdiff_t* s_, const ptrdiff_t* d_, int64 flat) + { + n = n_; size = size_; s = s_; d = d_; + soff = doff = 0; + for (int k = n - 1; k >= 0; k--) + { + int64 q = flat / size[k]; + idx[k] = flat - q*size[k]; + soff += (ptrdiff_t)idx[k]*s[k]; + if (d) + doff += (ptrdiff_t)idx[k]*d[k]; + flat = q; + } + } + + void next() + { + for (int k = n - 1; k >= 0; k--) + { + soff += s[k]; + if (d) + doff += d[k]; + if (++idx[k] < size[k]) + return; + soff -= (ptrdiff_t)size[k]*s[k]; + if (d) + doff -= (ptrdiff_t)size[k]*d[k]; + idx[k] = 0; + } + } +}; + +// `len` accumulator-typed elements of the source row at `p`: `p` itself when it is already +// contiguous and of the accumulator type, otherwise `tmp`/`buf`. +template static const A* loadRow(const Plan& pl, const uchar* p, ptrdiff_t step, int64 len, + A* buf, uchar* tmp) +{ + if (step != (ptrdiff_t)pl.sesz1) + { + for (int64 i = 0; i < len; i++, p += step) + memcpy(tmp + i*pl.sesz1, p, pl.sesz1); + p = tmp; + } + if (!pl.cvt) + return (const A*)p; + pl.cvt(p, 0, 0, 0, (uchar*)buf, 0, Size((int)len, 1), 0); + return buf; +} + +// Row loop with conversion blocking: calls f(x, len) on consecutive pieces of the row. +template static void forRow(const Plan& pl, const uchar* p, ptrdiff_t step, + int64 n, A* buf, uchar* tmp, F f) +{ + const bool direct = !pl.cvt && step == (ptrdiff_t)pl.sesz1; + const int64 blk = direct ? n : (int64)RND_BLOCK; + for (int64 e = 0; e < n; e += blk) + { + int64 len = std::min(blk, n - e); + f(loadRow(pl, p + e*step, step, len, buf, tmp), len); + } +} + +//////////////////////////////// drivers //////////////////////////////// + +// Parallel-split bookkeeping shared by both modes: nsplit partial results per output. +struct Work +{ + int64 nitems, nsplit; + double nstripes; + bool serial; +}; + +// Horizontal mode: outputs are the kept axes, each one folds `count` elements; the flat reduced +// index space [0, count) is split into nsplit ranges when there are too few outputs. +template static void runHorizontal(const Plan& pl, const Work& w, A* res, + const A* mbuf, A* partial) +{ + const int nr = pl.nr; + const int64 n = pl.rsize[nr - 1]; // innermost reduced axis + const ptrdiff_t rstep = pl.rsstep[nr - 1]; + const int64 nsplit = w.nsplit; + + auto body = [&](const Range& range) + { + AutoBuffer bufA(RND_BLOCK); + AutoBuffer bufT(RND_BLOCK*pl.sesz1); + Iter ko, ro; + int64 it = range.start; + if (nsplit == 1) + ko.init(pl.nk, pl.ksize, pl.ksstep, pl.kdstep, it); + while (it < range.end) + { + const int64 o = it / nsplit, s = it - o*nsplit; + if (nsplit > 1) + ko.init(pl.nk, pl.ksize, pl.ksstep, pl.kdstep, o); + const uchar* base = pl.src + ko.soff; + const A m = mbuf ? mbuf[ko.doff] : A(0); + int64 a = s*pl.count/nsplit, b = (s + 1)*pl.count/nsplit; + A acc = Op::init(); + if (a < b) + { + ro.init(nr - 1, pl.rsize, pl.rsstep, nullptr, a / n); + int64 e = a % n; + while (a < b) + { + int64 len = std::min(n - e, b - a); + forRow(pl, base + ro.soff + e*rstep, rstep, len, bufA.data(), bufT.data(), + [&](const A* x, int64 l) { acc = OpM::run(acc, x, l, m); }); + a += len; + e = 0; + ro.next(); + } + } + if (nsplit == 1) + { + res[ko.doff] = OpM::finalize(acc, pl.count, m); + ko.next(); + } + else + partial[s*pl.nout + ko.doff] = acc; + it++; + } + }; + + if (w.serial) + body(Range(0, (int)w.nitems)); + else + parallel_for_(Range(0, (int)w.nitems), body, w.nstripes); +} + +// Vertical mode: the innermost axis is kept; each item accumulates whole rows of a chunk of it. +template static void runVertical(const Plan& pl, const Work& w, A* res, + const A* mbuf, A* partial) +{ + const int nk = pl.nk; + const int64 m = pl.ksize[nk - 1]; + const ptrdiff_t kstep = pl.ksstep[nk - 1], kdstep = pl.kdstep[nk - 1]; + const int64 nch = (m + RND_VCHUNK - 1)/RND_VCHUNK; + const int64 nsplit = w.nsplit; + int64 rcount = 1; + for (int i = 0; i < pl.nr; i++) + rcount *= pl.rsize[i]; + + auto body = [&](const Range& range) + { + AutoBuffer bufA(RND_BLOCK), accBuf(RND_VCHUNK); + AutoBuffer bufT(RND_BLOCK*pl.sesz1); + A* acc = accBuf.data(); + Iter ko, ro; + for (int64 it = range.start; it < range.end; it++) + { + int64 s = it % nsplit, q = it / nsplit; + int64 ch = q % nch, o = q / nch; + ko.init(nk - 1, pl.ksize, pl.ksstep, pl.kdstep, o); + const int64 e0 = ch*RND_VCHUNK, len = std::min((int64)RND_VCHUNK, m - e0); + const ptrdiff_t soff = ko.soff + (ptrdiff_t)e0*kstep, doff = ko.doff + (ptrdiff_t)e0*kdstep; + const A* mrow = mbuf ? mbuf + doff : nullptr; // kdstep == 1 for the innermost kept axis + for (int64 i = 0; i < len; i++) + acc[i] = Op::init(); + + int64 a = s*rcount/nsplit, b = (s + 1)*rcount/nsplit; + if (a < b) + { + ro.init(pl.nr, pl.rsize, pl.rsstep, nullptr, a); + for (; a < b; a++, ro.next()) + { + const uchar* p = pl.src + soff + ro.soff; + const A* x = loadRow(pl, p, kstep, len, bufA.data(), bufT.data()); + OpM::vrun(acc, x, len, mrow); + } + } + if (nsplit == 1) + for (int64 i = 0; i < len; i++) + res[doff + i] = OpM::finalize(acc[i], pl.count, mrow ? mrow[i] : A(0)); + else + for (int64 i = 0; i < len; i++) + partial[s*pl.nout + doff + i] = acc[i]; + } + }; + + if (w.serial) + body(Range(0, (int)w.nitems)); + else + parallel_for_(Range(0, (int)w.nitems), body, w.nstripes); +} + +// Adapters that give the plain operations and the shifted-exp pass one interface. +template struct Plain +{ + static A run(A acc, const A* x, int64 n, A) { return HRow::run(acc, x, n); } + static void vrun(A* acc, const A* x, int64 n, const A*) { VRow::run(acc, x, n); } + static A finalize(A a, int64 count, A) { return Op::finalize(a, count); } +}; + +template struct ShiftedExp +{ + typedef OpSumExpShifted Op; + static A run(A acc, const A* x, int64 n, A m) + { + for (int64 i = 0; i < n; i++) + acc = Op::apply(acc, x[i], m); + return acc; + } + static void vrun(A* acc, const A* x, int64 n, const A* m) + { + for (int64 i = 0; i < n; i++) + acc[i] = Op::apply(acc[i], x[i], m[i]); + } + static A finalize(A a, int64, A m) { return Op::finalize(a, m); } +}; + +template static void runPass(const Plan& pl, A* res, const A* mbuf) +{ + const int nthreads = getNumThreads(); + const double work = (double)pl.nout*(double)std::max(pl.count, (int64)1); + Work w; + w.serial = work < RND_SERIAL_WORK || nthreads <= 1; + w.nsplit = 1; + int64 items; + if (pl.innerReduced) + items = pl.nout; + else + { + int64 nouter = pl.nout/pl.ksize[pl.nk - 1]; + items = nouter*((pl.ksize[pl.nk - 1] + RND_VCHUNK - 1)/RND_VCHUNK); + } + // too few outputs to keep all the threads busy: split the reduction as well + const int64 want = 4*(int64)nthreads; + if (!w.serial && items < want && pl.count > 1) + { + int64 rows = pl.innerReduced ? pl.count/4096 : pl.count/16; + w.nsplit = std::max((int64)1, std::min((want + items - 1)/items, std::min(rows, (int64)256))); + w.nsplit = std::min(w.nsplit, std::max((int64)1, (int64)(4 << 20)/std::max(pl.nout, (int64)1))); + } + w.nitems = items*w.nsplit; + w.nstripes = std::min((double)w.nitems, std::max(1.0, work/RND_STRIPE_WORK)); + CV_Assert(w.nitems <= INT_MAX); + + AutoBuffer partial(w.nsplit > 1 ? (size_t)(w.nsplit*pl.nout) : 1); + if (pl.innerReduced) + runHorizontal(pl, w, res, mbuf, partial.data()); + else + runVertical(pl, w, res, mbuf, partial.data()); + + if (w.nsplit > 1) + { + for (int64 o = 0; o < pl.nout; o++) + { + A acc = partial[(size_t)o]; + for (int64 s = 1; s < w.nsplit; s++) + acc = Op::combine(acc, partial[(size_t)(s*pl.nout + o)]); + res[o] = OpM::finalize(acc, pl.count, mbuf ? mbuf[o] : A(0)); + } + } +} + +template static void fillResult(A* res, int64 n, A v) +{ + for (int64 i = 0; i < n; i++) + res[i] = v; +} + +template static void runOp(const Plan& pl, int op, A* res) +{ + if (pl.count == 0) + { + // empty reduction: the identity of the operation + A v = op == REDUCE_MAX ? OpMax::init() : op == REDUCE_MIN ? OpMin::init() : + op == REDUCE_PROD ? A(1) : + op == REDUCE_LOG_SUM || op == REDUCE_LOG_SUM_EXP ? OpMax::init() : A(0); + fillResult(res, pl.nout, v); + return; + } + switch (op) + { + case REDUCE_SUM: runPass, Plain > >(pl, res, nullptr); break; + case REDUCE_AVG: runPass, Plain > >(pl, res, nullptr); break; + case REDUCE_SUM2: runPass, Plain > >(pl, res, nullptr); break; + case REDUCE_L1: runPass, Plain > >(pl, res, nullptr); break; + case REDUCE_L2: runPass, Plain > >(pl, res, nullptr); break; + case REDUCE_PROD: runPass, Plain > >(pl, res, nullptr); break; + case REDUCE_LOG_SUM: runPass, Plain > >(pl, res, nullptr); break; + case REDUCE_LOG_SUM_EXP: + { + AutoBuffer mbuf((size_t)pl.nout); + runPass, Plain > >(pl, mbuf.data(), nullptr); + runPass, ShiftedExp >(pl, res, mbuf.data()); + break; + } + default: + CV_Error(Error::StsBadArg, "reduce: unknown reduction operation"); + } +} + +template static void runMinMax(const Plan& pl, int op, A* res) +{ + if (pl.count == 0) + fillResult(res, pl.nout, op == REDUCE_MAX ? OpMax::init() : OpMin::init()); + else if (op == REDUCE_MAX) + runPass, Plain > >(pl, res, nullptr); + else + runPass, Plain > >(pl, res, nullptr); +} + +static void dispatch(const Plan& pl, int op, uchar* res) +{ + const bool minmax = op == REDUCE_MAX || op == REDUCE_MIN; + switch (pl.adepth) + { + case CV_32F: + if (minmax) runMinMax(pl, op, (float*)res); else runOp(pl, op, (float*)res); + break; + case CV_64F: + if (minmax) runMinMax(pl, op, (double*)res); else runOp(pl, op, (double*)res); + break; + case CV_8U: runMinMax(pl, op, (uchar*)res); break; + case CV_8S: runMinMax(pl, op, (schar*)res); break; + case CV_16U: runMinMax(pl, op, (ushort*)res); break; + case CV_16S: runMinMax(pl, op, (short*)res); break; + case CV_32U: runMinMax(pl, op, (unsigned*)res); break; + case CV_32S: runMinMax(pl, op, (int*)res); break; + case CV_64U: runMinMax(pl, op, (uint64_t*)res); break; + case CV_64S: runMinMax(pl, op, (int64_t*)res); break; + default: + CV_Error(Error::StsInternal, "reduce: unexpected accumulator depth"); + } +} + +static int accumulatorDepth(int sdepth, int ddepth, int op) +{ + if (op == REDUCE_MAX || op == REDUCE_MIN) + { + if (sdepth == CV_16F || sdepth == CV_16BF) + return CV_32F; + return sdepth == CV_Bool ? CV_8U : sdepth; + } + const bool wide = sdepth == CV_32S || sdepth == CV_32U || sdepth == CV_64S || sdepth == CV_64U || + sdepth == CV_64F || ddepth == CV_64F; + return wide ? CV_64F : CV_32F; +} + +} // namespace + +ReduceParams::ReduceParams(int _rtype, const std::vector& _axes, bool _keepdims, int _dtype) + : rtype(_rtype), axes(_axes), keepdims(_keepdims), dtype(_dtype) +{ +} + +void reduce(InputArray _src, OutputArray _dst, const ReduceParams& params) +{ + CV_INSTRUMENT_REGION(); + + const int op = params.rtype, dtype = params.dtype; + const bool keepdims = params.keepdims; + CV_Check(op, op >= REDUCE_SUM && op <= REDUCE_LOG_SUM_EXP, "reduce: unknown reduction operation"); + + Mat src = _src.getMat(); + const int dims = src.dims, cn = src.channels(); + const int sdepth = src.depth(); + int ddepth = dtype < 0 ? sdepth : CV_MAT_DEPTH(dtype); + if ((op == REDUCE_MAX || op == REDUCE_MIN) && sdepth == CV_Bool && ddepth != CV_Bool) + CV_Error(Error::StsBadArg, "reduce: the output of max/min over bool must be bool"); + + // which axes are reduced; empty means all of them + bool reduced[CV_MAX_DIM] = {false}; + if (params.axes.empty()) + std::fill(reduced, reduced + dims, true); + for (int a : params.axes) + { + CV_CheckGE(a, -dims, "reduce: axis is out of range"); + CV_CheckLT(a, dims, "reduce: axis is out of range"); + int ax = a < 0 ? a + dims : a; + CV_Check(a, !reduced[ax], "reduce: duplicate axis"); + reduced[ax] = true; + } + + int keepShape[CV_MAX_DIM], outShape[CV_MAX_DIM], nout = 0; + for (int i = 0; i < dims; i++) + { + keepShape[i] = reduced[i] ? 1 : src.size[i]; + if (!reduced[i] || keepdims) + outShape[nout++] = keepShape[i]; + } + const int dtype_ = CV_MAKETYPE(ddepth, cn); + _dst.create(nout, outShape, dtype_); + Mat dst = _dst.getMat(); + + // The results are computed into a contiguous accumulator-typed buffer laid out like the + // keepdims output (channels innermost), then converted into dst if needed. + Plan pl; + pl.src = src.data; + pl.sdepth = sdepth == CV_Bool ? CV_8U : sdepth; + pl.adepth = accumulatorDepth(sdepth, ddepth, op); + pl.sesz1 = CV_ELEM_SIZE1(sdepth); + pl.cvt = pl.sdepth == pl.adepth ? nullptr : getConvertFunc(pl.sdepth, pl.adepth); + CV_Assert(pl.sdepth == pl.adepth || pl.cvt); + + // gather the axes (+ the channel axis), outer first + int n = 0; + int size[RND_MAX_DIMS]; + ptrdiff_t sstep[RND_MAX_DIMS], dstep[RND_MAX_DIMS]; + bool red[RND_MAX_DIMS]; + ptrdiff_t dcur = cn; + ptrdiff_t dsteps[CV_MAX_DIM]; + for (int i = dims - 1; i >= 0; i--) + { + dsteps[i] = dcur; + dcur *= keepShape[i]; + } + pl.count = 1; + for (int i = 0; i < dims; i++) + { + if (reduced[i]) + pl.count *= src.size[i]; + size[n] = src.size[i]; + sstep[n] = (ptrdiff_t)src.step[i]; + dstep[n] = reduced[i] ? 0 : dsteps[i]; + red[n] = reduced[i]; + n++; + } + if (cn > 1) + { + size[n] = cn; + sstep[n] = (ptrdiff_t)pl.sesz1; + dstep[n] = 1; + red[n] = false; + n++; + } + + pl.nout = (int64)dst.total()*cn; + const bool direct = pl.adepth == ddepth && dst.isContinuous(); + Mat resMat; + uchar* res = dst.data; + if (!direct) + { + resMat.create(1, (int)std::max(pl.nout, (int64)1), CV_MAKETYPE(pl.adepth, 1)); + res = resMat.data; + } + if (pl.nout == 0) + return; + + // drop size-1 axes, then merge neighbours of the same kind that are contiguous in both views + int m = 0; + for (int i = 0; i < n; i++) + { + if (size[i] == 0) + { + // empty source along this axis + if (red[i]) + { + pl.count = 0; + continue; + } + return; + } + if (size[i] == 1) + continue; + if (m > 0 && red[m-1] == red[i] && sstep[m-1] == sstep[i]*size[i] && + dstep[m-1] == dstep[i]*size[i]) + { + size[m-1] *= size[i]; + sstep[m-1] = sstep[i]; + dstep[m-1] = dstep[i]; + } + else + { + size[m] = size[i]; + sstep[m] = sstep[i]; + dstep[m] = dstep[i]; + red[m] = red[i]; + m++; + } + } + if (m == 0) + { + // a single element + size[0] = 1; + sstep[0] = (ptrdiff_t)pl.sesz1; + dstep[0] = 1; + red[0] = false; + m = 1; + } + pl.innerReduced = red[m-1]; + pl.nk = pl.nr = 0; + for (int i = 0; i < m; i++) + { + if (red[i]) + { + pl.rsize[pl.nr] = size[i]; + pl.rsstep[pl.nr] = sstep[i]; + pl.nr++; + } + else + { + pl.ksize[pl.nk] = size[i]; + pl.ksstep[pl.nk] = sstep[i]; + pl.kdstep[pl.nk] = dstep[i]; + pl.nk++; + } + } + if (pl.nk == 0) + { + pl.ksize[0] = 1; + pl.ksstep[0] = 0; + pl.kdstep[0] = 0; + pl.nk = 1; + } + + dispatch(pl, op, res); + + if (!direct) + { + Mat r(dst.dims, dst.size.p, CV_MAKETYPE(pl.adepth, cn), resMat.data); + if (dst.dims == 0) + r = Mat(0, nullptr, CV_MAKETYPE(pl.adepth, cn), resMat.data); + r.convertTo(dst, ddepth); + } +} + +} // namespace cv diff --git a/modules/core/src/stat_parallel.hpp b/modules/core/src/stat_parallel.hpp new file mode 100644 index 0000000000..8f0f98cffb --- /dev/null +++ b/modules/core/src/stat_parallel.hpp @@ -0,0 +1,73 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +// Splitting of an array into pieces for the parallel versions of sum, mean, meanStdDev and minMaxIdx. +// Each piece is reduced by the existing serial code (including the HAL), and the results are +// combined in piece order. + +#ifndef OPENCV_CORE_STAT_PARALLEL_HPP +#define OPENCV_CORE_STAT_PARALLEL_HPP + +namespace cv { + +struct StatChunk +{ + Mat src, mask; + size_t firstElem; // row-major index of the first element of the piece in the whole array +}; + +// Returns false when the array is too small to be worth splitting, or cannot be split. +static inline bool splitForParallelStat(const Mat& src, const Mat& mask, std::vector& chunks) +{ + const size_t total = src.total(), work = total*src.channels(); + const int nthreads = getNumThreads(); + if (nthreads <= 1 || work < ((size_t)1 << 18)) + return false; + const int n = (int)std::min((size_t)nthreads*2, work >> 16); + if (n < 2) + return false; + + chunks.clear(); + if (src.dims <= 2 && src.rows >= n) + { + for (int i = 0; i < n; i++) + { + int r0 = (int)((int64)src.rows*i/n), r1 = (int)((int64)src.rows*(i + 1)/n); + StatChunk c; + c.src = src.rowRange(r0, r1); + if (!mask.empty()) + c.mask = mask.rowRange(r0, r1); + c.firstElem = (size_t)r0*src.cols; + chunks.push_back(c); + } + return true; + } + if (src.isContinuous() && (mask.empty() || mask.isContinuous()) && total <= (size_t)INT_MAX) + { + for (int i = 0; i < n; i++) + { + size_t e0 = total*i/n, e1 = total*(i + 1)/n; + StatChunk c; + c.src = Mat(1, (int)(e1 - e0), src.type(), (void*)(src.data + e0*src.elemSize())); + if (!mask.empty()) + c.mask = Mat(1, (int)(e1 - e0), mask.type(), (void*)(mask.data + e0*mask.elemSize())); + c.firstElem = e0; + chunks.push_back(c); + } + return true; + } + return false; +} + +// row-major index of an element given by the per-dimension indices of a 2D piece +static inline size_t chunkIndexToElem(const StatChunk& c, const int* idx) +{ + return c.firstElem + (size_t)idx[0]*c.src.cols + idx[1]; +} + +} // namespace cv + +#endif diff --git a/modules/core/src/sum.dispatch.cpp b/modules/core/src/sum.dispatch.cpp index 6d2aa0b188..d7a93cec97 100644 --- a/modules/core/src/sum.dispatch.cpp +++ b/modules/core/src/sum.dispatch.cpp @@ -7,6 +7,7 @@ #include "opencl_kernels_core.hpp" #include "stat.hpp" +#include "stat_parallel.hpp" #include "sum.simd.hpp" #include "sum.simd_declarations.hpp" // defines CV_CPU_DISPATCH_MODES_ALL=AVX2,...,BASELINE based on CMakeLists.txt content @@ -118,26 +119,17 @@ bool ocl_sum( InputArray _src, Scalar & res, int sum_op, InputArray _mask, #endif -Scalar sum(InputArray _src) +// serial implementation, also used for the pieces of the parallel version +static Scalar sum_(const Mat& src) { - CV_INSTRUMENT_REGION(); - Scalar _res; -#ifdef HAVE_OPENCL - CV_OCL_RUN_(OCL_PERFORMANCE_CHECK(_src.isUMat()) && _src.dims() <= 2, - ocl_sum(_src, _res, OCL_OP_SUM), - _res); -#endif - - Mat src = _src.getMat(); int cn = src.channels(); - CV_CheckLE( cn, 4, "cv::sum does not support more than 4 channels" ); - if (_src.dims() <= 2) + if (src.dims <= 2) { CALL_HAL_RET2(sum, cv_hal_sum, _res, src.data, src.step, src.type(), src.cols, src.rows, &_res[0]); } - else if (_src.isContinuous()) + else if (src.isContinuous()) { CALL_HAL_RET2(sum, cv_hal_sum, _res, src.data, 0, src.type(), (int)src.total(), 1, &_res[0]); } @@ -201,4 +193,33 @@ Scalar sum(InputArray _src) return _res; } +Scalar sum(InputArray _src) +{ + CV_INSTRUMENT_REGION(); + + Scalar _res; +#ifdef HAVE_OPENCL + CV_OCL_RUN_(OCL_PERFORMANCE_CHECK(_src.isUMat()) && _src.dims() <= 2, + ocl_sum(_src, _res, OCL_OP_SUM), + _res); +#endif + + Mat src = _src.getMat(); + CV_CheckLE( src.channels(), 4, "cv::sum does not support more than 4 channels" ); + + std::vector chunks; + if (!splitForParallelStat(src, Mat(), chunks)) + return sum_(src); + + std::vector part(chunks.size()); + parallel_for_(Range(0, (int)chunks.size()), [&](const Range& r) + { + for (int i = r.start; i < r.end; i++) + part[i] = sum_(chunks[i].src); + }); + for (const Scalar& v : part) + _res += v; + return _res; +} + } // namespace diff --git a/modules/core/test/test_reduce_nd.cpp b/modules/core/test/test_reduce_nd.cpp new file mode 100644 index 0000000000..6b6f36c959 --- /dev/null +++ b/modules/core/test/test_reduce_nd.cpp @@ -0,0 +1,338 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +#include "test_precomp.hpp" +#include +#include + +namespace opencv_test { namespace { + +static const int reduceOps[] = { REDUCE_SUM, REDUCE_AVG, REDUCE_MAX, REDUCE_MIN, REDUCE_SUM2, REDUCE_PROD, + REDUCE_L1, REDUCE_L2, REDUCE_LOG_SUM, REDUCE_LOG_SUM_EXP }; +static const int reduceDepths[] = { CV_8U, CV_8S, CV_16U, CV_16S, CV_32S, CV_32F, CV_64F, CV_16F, CV_64S }; + +static std::vector shapeOf(const Mat& m) { return std::vector(m.size.p, m.size.p + m.dims); } + +static double readAsDouble(const Mat& m, const int* idx, int c) +{ + const uchar* p = m.ptr(idx) + c*m.elemSize1(); + switch (m.depth()) + { + case CV_8U: return *p; + case CV_8S: return *(const schar*)p; + case CV_16U: return *(const ushort*)p; + case CV_16S: return *(const short*)p; + case CV_32S: return *(const int*)p; + case CV_32F: return *(const float*)p; + case CV_64F: return *(const double*)p; + case CV_16F: return (float)*(const hfloat*)p; + case CV_64S: return (double)*(const int64_t*)p; + } + CV_Error(Error::StsBadArg, "unsupported depth"); +} + +template static void forEachIndex(const std::vector& shape, F f) +{ + const int dims = (int)shape.size(); + for (int s : shape) + if (s == 0) + return; + std::vector idx(dims, 0); + for (;;) + { + f(idx.data()); + int k = dims - 1; + for (; k >= 0; k--) + { + if (++idx[k] < shape[k]) + break; + idx[k] = 0; + } + if (k < 0) + break; + } +} + +// Naive reference in double: a CV_64F array in the keepdims layout, src.channels() channels. +static Mat refReduce(const Mat& src, const std::vector& reduced, int op) +{ + const int dims = src.dims, cn = src.channels(); + std::vector outShape = shapeOf(src), redShape = shapeOf(src); + for (int i = 0; i < dims; i++) + { + if (reduced[i]) outShape[i] = 1; + else redShape[i] = 1; + } + Mat dst(outShape, CV_64FC(cn)); + std::vector sidx(dims); + forEachIndex(outShape, [&](const int* oidx) + { + for (int c = 0; c < cn; c++) + { + double acc = op == REDUCE_PROD ? 1 : op == REDUCE_MAX ? -INFINITY : op == REDUCE_MIN ? INFINITY : 0; + double mx = -INFINITY; + double count = 0; + if (op == REDUCE_LOG_SUM_EXP) + forEachIndex(redShape, [&](const int* ridx) + { + for (int i = 0; i < dims; i++) sidx[i] = reduced[i] ? ridx[i] : oidx[i]; + mx = std::max(mx, readAsDouble(src, sidx.data(), c)); + }); + forEachIndex(redShape, [&](const int* ridx) + { + for (int i = 0; i < dims; i++) sidx[i] = reduced[i] ? ridx[i] : oidx[i]; + double x = readAsDouble(src, sidx.data(), c); + count++; + switch (op) + { + case REDUCE_SUM: case REDUCE_AVG: case REDUCE_LOG_SUM: acc += x; break; + case REDUCE_SUM2: case REDUCE_L2: acc += x*x; break; + case REDUCE_L1: acc += std::abs(x); break; + case REDUCE_PROD: acc *= x; break; + case REDUCE_MAX: acc = std::max(acc, x); break; + case REDUCE_MIN: acc = std::min(acc, x); break; + case REDUCE_LOG_SUM_EXP: acc += std::exp(x - mx); break; + } + }); + if (op == REDUCE_AVG) acc = count > 0 ? acc/count : 0; + else if (op == REDUCE_L2) acc = std::sqrt(acc); + else if (op == REDUCE_LOG_SUM) acc = std::log(acc); + else if (op == REDUCE_LOG_SUM_EXP) acc = mx + std::log(acc); + ((double*)dst.ptr(oidx))[c] = acc; + } + }); + return dst; +} + +// values that keep every operation well-defined and finite +static void fillForOp(RNG& rng, Mat& m, int op) +{ + const int depth = m.depth(); + const bool isFloat = depth == CV_32F || depth == CV_64F || depth == CV_16F; + const bool isUnsigned = depth == CV_8U || depth == CV_16U; + double lo, hi; + if (op == REDUCE_PROD) { lo = isFloat ? 0.9 : 1; hi = isFloat ? 1.1 : 2; } + else if (op == REDUCE_LOG_SUM) { lo = isFloat ? 0.1 : 1; hi = isFloat ? 10 : 50; } + else if (op == REDUCE_LOG_SUM_EXP) { lo = -5; hi = 5; } + else if (isFloat) { lo = -10; hi = 10; } + else { lo = isUnsigned ? 0 : -100; hi = 100; } + Mat tmp(shapeOf(m), CV_64FC(m.channels())); + Mat flat(1, (int)(tmp.total()*tmp.channels()), CV_64F, tmp.data); + rng.fill(flat, RNG::UNIFORM, lo, hi); + if (!isFloat) + for (int i = 0; i < flat.cols; i++) + { + double& v = flat.at(i); + v = std::floor(v); + if (op == REDUCE_PROD) + v = std::min(std::max(v, 1.), 2.); + } + tmp.convertTo(m, depth); +} + +static void checkReduce(const Mat& src, const Mat& dst, const std::vector& reduced, int op, + bool keepdims, int ddepth, const std::string& info) +{ + Mat ref = refReduce(src, reduced, op); + std::vector keepShape = shapeOf(ref), outShape; + for (int i = 0; i < src.dims; i++) + if (!reduced[i] || keepdims) + outShape.push_back(keepShape[i]); + ASSERT_EQ(outShape, shapeOf(dst)) << info; + ASSERT_EQ(CV_MAKETYPE(ddepth, src.channels()), dst.type()) << info; + + Mat refD; + ref.convertTo(refD, ddepth); // the expected result, saturated like the output + auto flat64 = [](const Mat& m) { + Mat c = m.isContinuous() ? m : m.clone(), r; + Mat(1, (int)(c.total()*c.channels()), c.depth(), c.data).convertTo(r, CV_64F); + return r; + }; + Mat a = flat64(refD), b = flat64(dst), refRaw = flat64(ref); + + const bool exact = op == REDUCE_MAX || op == REDUCE_MIN; + const bool intOut = ddepth != CV_32F && ddepth != CV_64F && ddepth != CV_16F; + const double relTol = ddepth == CV_16F ? 2e-3 : ddepth == CV_64F ? 1e-9 : 2e-5; + for (int i = 0; i < a.cols; i++) + { + double e = a.at(i), v = b.at(i), raw = refRaw.at(i); + if (std::isnan(e) && std::isnan(v)) continue; + if (std::isinf(e) || std::isinf(v)) { ASSERT_EQ(e, v) << info << " at " << i; continue; } + double tol = exact ? 0 : intOut ? 1 : relTol*(std::abs(raw) + 1); + ASSERT_LE(std::abs(e - v), tol) << info << " at " << i << ": expected " << e << ", got " << v; + } +} + +static Mat randomArray(RNG& rng, const std::vector& shape, int type, bool roi) +{ + if (!roi) + return Mat(shape, type); + std::vector big = shape; + std::vector ranges; + for (size_t i = 0; i < shape.size(); i++) + { + int before = rng.uniform(0, 2); + big[i] += before + rng.uniform(0, 2); + ranges.push_back(Range(before, before + shape[i])); + } + return Mat(big, type)(ranges); +} + +TEST(Core_ReduceND, random) +{ + RNG& rng = theRNG(); + int checked = 0; + for (int iter = 0; iter < 400; iter++) + { + const int dims = rng.uniform(1, 6); + std::vector shape(dims); + for (int i = 0; i < dims; i++) + shape[i] = rng.uniform(1, dims <= 2 ? 30 : 7); + const int op = reduceOps[rng.uniform(0, 10)]; + const int depth = reduceDepths[rng.uniform(0, 9)]; + const int cn = rng.uniform(0, 4) == 0 ? rng.uniform(2, 4) : 1; + Mat src = randomArray(rng, shape, CV_MAKETYPE(depth, cn), rng.uniform(0, 2) != 0); + fillForOp(rng, src, op); + + std::vector reduced(dims, false); + std::vector axes; + const bool all = rng.uniform(0, 5) == 0; + for (int i = 0; i < dims; i++) + if (all || rng.uniform(0, 2)) + { + reduced[i] = true; + axes.push_back(rng.uniform(0, 2) ? i : i - dims); + } + if (all) + axes.clear(); + else if (axes.empty()) + { + reduced[0] = true; + axes.push_back(0); + } + std::shuffle(axes.begin(), axes.end(), std::mt19937(rng.next())); + if (op == REDUCE_PROD) + { + // keep integer products in range + int64 count = 1; + for (int i = 0; i < dims; i++) if (reduced[i]) count *= shape[i]; + if (count > 20 && depth != CV_32F && depth != CV_64F && depth != CV_16F) + continue; + } + const bool keepdims = rng.uniform(0, 2) != 0; + const int ddepth = rng.uniform(0, 3) == 0 ? (rng.uniform(0, 2) ? CV_32F : CV_64F) : depth; + + Mat dst; + cv::reduce(src, dst, ReduceParams(op, axes, keepdims, ddepth == depth ? -1 : ddepth)); + std::string info = cv::format("iter %d: %s %s cn=%d op=%d axes=%s keepdims=%d ddepth=%d%s", iter, + typeToString(depth).c_str(), MatShape(shape).str().c_str(), cn, op, + MatShape(axes).str().c_str(), (int)keepdims, ddepth, + src.isContinuous() ? "" : " roi"); + checkReduce(src, dst, reduced, op, keepdims, ddepth, info); + if (HasFatalFailure()) + return; + checked++; + } + EXPECT_GE(checked, 300); +} + +typedef testing::TestWithParam, std::vector, int> > Core_ReduceND_Large; + +// large enough for the parallel paths, including split reductions +TEST_P(Core_ReduceND_Large, accuracy) +{ + const std::vector shape = get<0>(GetParam()), axes = get<1>(GetParam()); + const int op = get<2>(GetParam()); + RNG& rng = theRNG(); + for (int depth : {CV_32F, CV_8U}) + { + Mat src(shape, depth); + fillForOp(rng, src, op); + std::vector reduced(shape.size(), axes.empty()); + for (int a : axes) reduced[a] = true; + Mat dst; + cv::reduce(src, dst, ReduceParams(op, axes, true, CV_64F)); + checkReduce(src, dst, reduced, op, true, CV_64F, typeToString(depth)); + } +} + +INSTANTIATE_TEST_CASE_P(/**/, Core_ReduceND_Large, testing::Values( + make_tuple(std::vector{1, 64, 80, 80}, std::vector{1}, (int)REDUCE_AVG), + make_tuple(std::vector{1, 64, 80, 80}, std::vector{2, 3}, (int)REDUCE_SUM), + make_tuple(std::vector{600, 700}, std::vector{}, (int)REDUCE_SUM), + make_tuple(std::vector{600, 700}, std::vector{}, (int)REDUCE_MAX), + make_tuple(std::vector{100000, 3}, std::vector{0}, (int)REDUCE_SUM2), + make_tuple(std::vector{3, 100000}, std::vector{1}, (int)REDUCE_L2), + make_tuple(std::vector{8, 50, 300}, std::vector{0, 2}, (int)REDUCE_LOG_SUM_EXP), + make_tuple(std::vector{8, 50, 300}, std::vector{1}, (int)REDUCE_MIN) +)); + +TEST(Core_ReduceND, reduce_matches_2d) +{ + RNG& rng = theRNG(); + Mat src(37, 53, CV_32FC2); + rng.fill(src, RNG::UNIFORM, -1, 1); + for (int op : {REDUCE_SUM, REDUCE_AVG, REDUCE_MAX, REDUCE_MIN, REDUCE_SUM2}) + for (int dim = 0; dim < 2; dim++) + { + // 2D cv::reduce keeps the input depth for max/min + const int ddepth = op == REDUCE_MAX || op == REDUCE_MIN ? -1 : CV_64F; + Mat a, b; + cv::reduce(src, a, dim, op, ddepth); + cv::reduce(src, b, ReduceParams(op, {dim}, true, ddepth)); + EXPECT_LE(cvtest::norm(a, b, NORM_INF), 1e-9) << op << " " << dim; + } +} + +TEST(Core_ReduceND, reduce_nd_input) +{ + RNG& rng = theRNG(); + Mat src({4, 5, 6}, CV_32F), a, b; + rng.fill(src, RNG::UNIFORM, -1, 1); + cv::reduce(src, a, 1, REDUCE_MAX); + cv::reduce(src, b, {REDUCE_MAX, {1}}); + ASSERT_EQ(std::vector({4, 1, 6}), shapeOf(a)); + EXPECT_EQ(0, cvtest::norm(a, b, NORM_INF)); + // the new operations also work through cv::reduce on 2D input + Mat c, d, m2(3, 4, CV_32F, Scalar(2)); + cv::reduce(m2, c, 1, REDUCE_PROD); + EXPECT_EQ(16.f, c.at(0)); +} + +TEST(Core_ReduceND, special_cases) +{ + Mat a({3, 0, 4}, CV_32F), d; + cv::reduce(a, d, {REDUCE_SUM, {1}}); // empty reduction -> identity + ASSERT_EQ(std::vector({3, 1, 4}), shapeOf(d)); + EXPECT_EQ(0, cvtest::norm(d, NORM_INF)); + cv::reduce(a, d, {REDUCE_PROD, {1}}); + EXPECT_EQ(1., cvtest::norm(d, NORM_INF)); + + Mat s(0, nullptr, CV_32F); // 0-dimensional input + s.at(0) = -3.f; + cv::reduce(s, d, {REDUCE_L1}); + EXPECT_EQ(0, d.dims); + EXPECT_EQ(3.f, d.at(0)); + + Mat m({2, 3}, CV_32F, Scalar(1)); + cv::reduce(m, d, {REDUCE_SUM, {}, false}); // all axes, no keepdims -> scalar + EXPECT_EQ(0, d.dims); + EXPECT_EQ(6.f, d.at(0)); + + Mat f({2, 3}, CV_32F); + f.setTo(-INFINITY); + cv::reduce(f, d, {REDUCE_LOG_SUM_EXP, {1}}); + EXPECT_TRUE(std::isinf(d.at(0)) && d.at(0) < 0); + f.setTo(1000.f); // would overflow exp() without the shift + cv::reduce(f, d, {REDUCE_LOG_SUM_EXP, {1}}); + EXPECT_NEAR(1000. + std::log(3.), d.at(0), 1e-3); + + EXPECT_ANY_THROW(cv::reduce(m, d, {REDUCE_SUM, {2}})); + EXPECT_ANY_THROW(cv::reduce(m, d, {REDUCE_SUM, {0, -2}})); + EXPECT_ANY_THROW(cv::reduce(m, d, {42, {0}})); +} + +}} // namespace diff --git a/modules/core/test/test_stat_parallel.cpp b/modules/core/test/test_stat_parallel.cpp new file mode 100644 index 0000000000..9a49349b7b --- /dev/null +++ b/modules/core/test/test_stat_parallel.cpp @@ -0,0 +1,137 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +// The parallel versions of sum, mean, meanStdDev and minMaxIdx must agree with the serial ones. + +#include "test_precomp.hpp" + +namespace opencv_test { namespace { + +static double relDiff(const Scalar& a, const Scalar& b) +{ + double d = 0; + for (int k = 0; k < 4; k++) + d = std::max(d, std::abs(a[k] - b[k])/(std::abs(b[k]) + 1)); + return d; +} + +typedef testing::TestWithParam > Core_StatParallel; + +TEST_P(Core_StatParallel, matches_serial) +{ + const int type = get<0>(GetParam()), variant = get<1>(GetParam()); + const int depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type); + RNG& rng = theRNG(); + + // variant 0: continuous 2D, 1: ROI, 2: continuous 3D, 3: 2D with a mask + Mat big(1100, 1300, type); + rng.fill(big, RNG::UNIFORM, depth == CV_8U ? 0 : -100, 100); + Mat src = variant == 1 ? big(Rect(7, 5, 1200, 1000)) : variant == 2 ? big.reshape(cn, std::vector{11, 100, 1300}) : big; + Mat mask; + if (variant == 3) + { + mask.create(src.size(), CV_8U); + rng.fill(mask, RNG::UNIFORM, 0, 2); + mask.rowRange(0, mask.rows*3/4).setTo(0); // most of the pieces see no elements + } + + Scalar s1, m1, mean1, sd1; + double mn1 = 0, mx1 = 0; + int imn1[3] = {-1, -1, -1}, imx1[3] = {-1, -1, -1}; + const bool withIdx = cn == 1; + Mat src1 = cn == 1 ? src : src.reshape(1); + s1 = cv::sum(src); + m1 = cv::mean(src, mask); + cv::meanStdDev(src, mean1, sd1, mask); + cv::minMaxIdx(src1, &mn1, &mx1, withIdx ? imn1 : 0, withIdx ? imx1 : 0, cn == 1 ? mask : noArray()); + + // Reference from per-row calls: every row is far below the size at which the work is split, + // so this runs the original serial code, and the rows are combined here in double. + Mat src2 = src.dims > 2 ? Mat(src.size[0]*src.size[1], src.size[2], src.type(), src.data) : src; + Mat src2s = src1.dims > 2 ? Mat(src1.size[0]*src1.size[1], src1.size[2], src1.type(), src1.data) : src1; + Scalar s0, sx, sxx; + double n0 = 0, mn0 = 0, mx0 = 0; + bool anyRow = false; + for (int r = 0; r < src2.rows; r++) + { + Mat row = src2.row(r), mrow = mask.empty() ? Mat() : mask.row(r), row64; + s0 += cv::sum(row); + row.convertTo(row64, CV_64F); + double cnt = mrow.empty() ? row.cols : cv::countNonZero(mrow); + if (cnt > 0) + { + sx += cv::mean(row64, mrow)*cnt; + sxx += cv::mean(row64.mul(row64), mrow)*cnt; + n0 += cnt; + } + double a, b; + int ia[2] = {-1, -1}, ib[2] = {-1, -1}; + cv::minMaxIdx(src2s.row(r), &a, &b, withIdx ? ia : 0, withIdx ? ib : 0, cn == 1 ? mrow : Mat()); + if (withIdx && ia[1] < 0) + continue; // the mask selects nothing in this row + if (!anyRow || a < mn0) mn0 = a; + if (!anyRow || b > mx0) mx0 = b; + anyRow = true; + } + Scalar m0 = n0 > 0 ? sx*(1./n0) : Scalar(), mean0 = m0, sd0; + for (int k = 0; k < 4; k++) + sd0[k] = n0 > 0 ? std::sqrt(std::max(sxx[k]/n0 - m0[k]*m0[k], 0.)) : 0; + + const double tol = depth == CV_32F ? 1e-6 : 1e-10; + EXPECT_LE(relDiff(s1, s0), tol); + EXPECT_LE(relDiff(m1, m0), tol); + EXPECT_LE(relDiff(mean1, mean0), tol); + EXPECT_LE(relDiff(sd1, sd0), 1e-6); + EXPECT_EQ(mn0, mn1); + EXPECT_EQ(mx0, mx1); + if (withIdx) + { + // Which of several equal extrema a piece reports is up to its (vectorized, possibly HAL) + // serial code, so check that the position holds the extremum rather than that it matches + // the reference; the ordering across pieces is covered by first_occurrence below. + auto valAt = [&](const int* idx) + { + Mat e(1, 1, src1.type(), src1.ptr(idx)), e64; + e.convertTo(e64, CV_64F); + return e64.at(0); + }; + ASSERT_GE(imn1[0], 0); + ASSERT_GE(imx1[0], 0); + EXPECT_EQ(mn1, valAt(imn1)); + EXPECT_EQ(mx1, valAt(imx1)); + if (!mask.empty()) + { + EXPECT_NE(0, mask.at(imn1[0], imn1[1])); + EXPECT_NE(0, mask.at(imx1[0], imx1[1])); + } + } +} + +INSTANTIATE_TEST_CASE_P(/**/, Core_StatParallel, testing::Combine( + testing::Values(perf::MatType(CV_8UC1), CV_8UC3, CV_16SC1, CV_32SC1, CV_32FC1, CV_32FC4, CV_64FC1), + testing::Values(0, 1, 2, 3) +)); + +// the first occurrence of the extremum wins, also across pieces +TEST(Core_StatParallelMinMax, first_occurrence) +{ + Mat a(1000, 1000, CV_32F, Scalar(0)); + a.at(300, 5) = -1; a.at(900, 7) = -1; + a.at(100, 9) = 2; a.at(700, 1) = 2; + double mn, mx; + Point pmn, pmx; + cv::minMaxLoc(a, &mn, &mx, &pmn, &pmx); + EXPECT_EQ(Point(5, 300), pmn); + EXPECT_EQ(Point(9, 100), pmx); + + Mat mask(a.size(), CV_8U, Scalar(0)); // nothing selected + cv::minMaxLoc(a, &mn, &mx, &pmn, &pmx, mask); + EXPECT_EQ(Point(-1, -1), pmn); + EXPECT_EQ(0., mn); + EXPECT_EQ(Scalar::all(0), cv::mean(a, mask)); +} + +}} // namespace diff --git a/modules/dnn/CMakeLists.txt b/modules/dnn/CMakeLists.txt index 62a5043ca2..1cb6df87e7 100644 --- a/modules/dnn/CMakeLists.txt +++ b/modules/dnn/CMakeLists.txt @@ -14,7 +14,6 @@ ocv_add_dispatched_file("layers/cpu_kernels/conv2_depthwise" AVX AVX2 NEON NEON_ ocv_add_dispatched_file("layers/cpu_kernels/conv2_kernels" AVX AVX2 NEON NEON_FP16) ocv_add_dispatched_file("int8layers/conv2_int8_kernels" AVX2 RVV AVX_VNNI) ocv_add_dispatched_file("layers/cpu_kernels/activation_kernels" AVX AVX2 NEON NEON_FP16) -ocv_add_dispatched_file_force_all("layers/cpu_kernels/reduce2_kernels" AVX AVX2 NEON RVV LASX) ocv_add_dispatched_file_force_all("layers/cpu_kernels/gridsample_kernels" AVX AVX2 NEON RVV LASX) ocv_add_module(dnn opencv_core opencv_imgproc opencv_geometry OPTIONAL opencv_imgcodecs WRAP python java objc js) diff --git a/modules/dnn/perf/perf_reduce2.cpp b/modules/dnn/perf/perf_reduce2.cpp new file mode 100644 index 0000000000..e138843e81 --- /dev/null +++ b/modules/dnn/perf/perf_reduce2.cpp @@ -0,0 +1,54 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +// Reduce2 (a layer of the new graph engine), called directly. + +#include "perf_precomp.hpp" + +namespace opencv_test { + +typedef tuple, std::vector, std::string, perf::MatType> Reduce2Params; +typedef TestBaseWithParam Layer_Reduce2; + +PERF_TEST_P_(Layer_Reduce2, reduce) +{ + const std::vector shape = get<0>(GetParam()), axes = get<1>(GetParam()); + const std::string op = get<2>(GetParam()); + const int type = get<3>(GetParam()); + + LayerParams lp; + lp.type = "Reduce2"; + lp.name = "testLayer"; + lp.set("reduce", op); + lp.set("keepdims", true); + lp.set("axes", DictValue::arrayInt(axes.data(), (int)axes.size())); + Ptr layer = LayerFactory::createLayerInstance("Reduce2", lp); + + Mat input(shape, type); + randu(input, 0, 10); + std::vector inputs{input}, outputs(1), internals; + layer->forward(inputs, outputs, internals); + TEST_CYCLE() + { + layer->forward(inputs, outputs, internals); + } + SANITY_CHECK_NOTHING(); +} + +INSTANTIATE_TEST_CASE_P(/**/, Layer_Reduce2, testing::Values( + make_tuple(std::vector{1, 256, 80, 80}, std::vector{1}, "mean", perf::MatType(CV_32F)), + make_tuple(std::vector{1, 256, 80, 80}, std::vector{2, 3}, "mean", perf::MatType(CV_32F)), + make_tuple(std::vector{1, 64, 160, 160}, std::vector{0, 1, 2, 3}, "sum", perf::MatType(CV_32F)), + make_tuple(std::vector{32, 1024, 256}, std::vector{0}, "max", perf::MatType(CV_32F)), + make_tuple(std::vector{4096, 768}, std::vector{1}, "l2", perf::MatType(CV_32F)), + make_tuple(std::vector{64, 1000}, std::vector{1}, "log_sum_exp", perf::MatType(CV_32F)), + make_tuple(std::vector{1, 256, 80, 80}, std::vector{1}, "sum", perf::MatType(CV_16F)), + make_tuple(std::vector{1, 3, 640, 640}, std::vector{2, 3}, "max", perf::MatType(CV_8U)), + make_tuple(std::vector{1, 256, 80, 80}, std::vector{1}, "sum", perf::MatType(CV_32S)), + make_tuple(std::vector{8, 196, 768}, std::vector{2}, "mean", perf::MatType(CV_32F)) +)); + +} // namespace opencv_test diff --git a/modules/dnn/src/layers/cpu_kernels/reduce2_kernels.simd.hpp b/modules/dnn/src/layers/cpu_kernels/reduce2_kernels.simd.hpp deleted file mode 100644 index fa26173b69..0000000000 --- a/modules/dnn/src/layers/cpu_kernels/reduce2_kernels.simd.hpp +++ /dev/null @@ -1,299 +0,0 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// Copyright (C) 2026, BigVision LLC, all rights reserved. -// Third party copyrights are property of their respective owners. - -#include -#include -#include -#include "opencv2/core/hal/intrin.hpp" -#include -#include -#include -#include - -namespace cv { namespace dnn { -CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN - -// Reduce-all over a contiguous CV_32F src -void reduceAllFloatParallel_(const Mat& src, Mat& dst, int reduce_type); - -// Reduce a contiguous trailing block of axes for CV_32F src. -void reduceLastAxesFloatParallel_(const Mat& src, Mat& dst, size_t innerLen, int reduce_type); - -CV_CPU_OPTIMIZATION_NAMESPACE_END -}} - -#ifndef CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY - -namespace cv { namespace dnn { -CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN - -void reduceAllFloatParallel_(const Mat& src, Mat& dst, int reduce_type_int) { - const Reduce2Layer::ReduceType rt = (Reduce2Layer::ReduceType)reduce_type_int; - const float* p = src.ptr(); - const size_t total = src.total(); - const int nThreads = std::max(1, cv::getNumThreads()); - const int stripes = std::max(1, std::min( - (int)((total + 16383) / 16384), nThreads)); - - float init_f = 0.0f; - if (rt == Reduce2Layer::ReduceType::MAX) init_f = -FLT_MAX; - else if (rt == Reduce2Layer::ReduceType::MIN) init_f = FLT_MAX; - else if (rt == Reduce2Layer::ReduceType::PROD) init_f = 1.0f; - - std::vector partial_f(stripes, init_f); - - parallel_for_(Range(0, stripes), [&](const Range& r) { - for (int s = r.start; s < r.end; s++) { - size_t start = (size_t)s * total / stripes; - size_t end = (size_t)(s + 1) * total / stripes; - const float* q = p + start; - size_t n = end - start, i = 0; -#if (CV_SIMD || CV_SIMD_SCALABLE) - const int L = VTraits::vlanes(); -#endif - switch (rt) { - case Reduce2Layer::ReduceType::MAX: { - float acc = -FLT_MAX; -#if (CV_SIMD || CV_SIMD_SCALABLE) - v_float32 va = vx_setall_f32(-FLT_MAX); - for (; i + L <= n; i += L) va = v_max(va, vx_load(q + i)); - acc = v_reduce_max(va); -#endif - for (; i < n; i++) acc = acc > q[i] ? acc : q[i]; - partial_f[s] = acc; - break; - } - case Reduce2Layer::ReduceType::MIN: { - float acc = FLT_MAX; -#if (CV_SIMD || CV_SIMD_SCALABLE) - v_float32 va = vx_setall_f32(FLT_MAX); - for (; i + L <= n; i += L) va = v_min(va, vx_load(q + i)); - acc = v_reduce_min(va); -#endif - for (; i < n; i++) acc = acc < q[i] ? acc : q[i]; - partial_f[s] = acc; - break; - } - case Reduce2Layer::ReduceType::SUM: - case Reduce2Layer::ReduceType::MEAN: - case Reduce2Layer::ReduceType::LOG_SUM: { - float acc = 0.0f; -#if (CV_SIMD || CV_SIMD_SCALABLE) - v_float32 va = vx_setzero_f32(); - for (; i + L <= n; i += L) va = v_add(va, vx_load(q + i)); - acc += v_reduce_sum(va); -#endif - for (; i < n; i++) acc += q[i]; - partial_f[s] = acc; - break; - } - case Reduce2Layer::ReduceType::L1: { - float acc = 0.0f; -#if (CV_SIMD || CV_SIMD_SCALABLE) - v_float32 va = vx_setzero_f32(); - for (; i + L <= n; i += L) va = v_add(va, v_abs(vx_load(q + i))); - acc += v_reduce_sum(va); -#endif - for (; i < n; i++) acc += std::fabs(q[i]); - partial_f[s] = acc; - break; - } - case Reduce2Layer::ReduceType::L2: - case Reduce2Layer::ReduceType::SUM_SQUARE: { - float acc = 0.0f; -#if (CV_SIMD || CV_SIMD_SCALABLE) - v_float32 va = vx_setzero_f32(); - for (; i + L <= n; i += L) { - v_float32 x = vx_load(q + i); - va = v_add(va, v_mul(x, x)); - } - acc += v_reduce_sum(va); -#endif - for (; i < n; i++) { float x = q[i]; acc += x * x; } - partial_f[s] = acc; - break; - } - case Reduce2Layer::ReduceType::PROD: { - float acc = 1.0f; -#if (CV_SIMD || CV_SIMD_SCALABLE) - v_float32 va = vx_setall_f32(1.0f); - for (; i + L <= n; i += L) va = v_mul(va, vx_load(q + i)); - float buf[VTraits::max_nlanes]; - v_store(buf, va); - for (int k = 0; k < L; k++) acc *= buf[k]; -#endif - for (; i < n; i++) acc *= q[i]; - partial_f[s] = acc; - break; - } - default: CV_Error(Error::StsInternal, "reduceAllFloatParallel_: unhandled type"); - } - } - }); - - float* out = dst.ptr(); - switch (rt) { - case Reduce2Layer::ReduceType::MAX: { - float m = -FLT_MAX; - for (int s = 0; s < stripes; s++) m = m > partial_f[s] ? m : partial_f[s]; - *out = m; - break; - } - case Reduce2Layer::ReduceType::MIN: { - float m = FLT_MAX; - for (int s = 0; s < stripes; s++) m = m < partial_f[s] ? m : partial_f[s]; - *out = m; - break; - } - case Reduce2Layer::ReduceType::SUM: { - float acc = 0.0f; for (int s = 0; s < stripes; s++) acc += partial_f[s]; - *out = acc; - break; - } - case Reduce2Layer::ReduceType::MEAN: { - float acc = 0.0f; for (int s = 0; s < stripes; s++) acc += partial_f[s]; - *out = total > 0 ? (float)((double)acc / (double)total) : 0.0f; - break; - } - case Reduce2Layer::ReduceType::L1: - case Reduce2Layer::ReduceType::SUM_SQUARE: { - float acc = 0.0f; for (int s = 0; s < stripes; s++) acc += partial_f[s]; - *out = acc; - break; - } - case Reduce2Layer::ReduceType::L2: { - float acc = 0.0f; for (int s = 0; s < stripes; s++) acc += partial_f[s]; - *out = std::sqrt(acc); - break; - } - case Reduce2Layer::ReduceType::LOG_SUM: { - float acc = 0.0f; for (int s = 0; s < stripes; s++) acc += partial_f[s]; - *out = total > 0 ? std::log(acc) : -std::numeric_limits::infinity(); - break; - } - case Reduce2Layer::ReduceType::PROD: { - float acc = 1.0f; for (int s = 0; s < stripes; s++) acc *= partial_f[s]; - *out = acc; - break; - } - default: CV_Error(Error::StsInternal, "reduceAllFloatParallel_: unhandled type"); - } -} - -void reduceLastAxesFloatParallel_(const Mat& src, Mat& dst, size_t innerLen, int reduce_type_int) { - const Reduce2Layer::ReduceType rt = (Reduce2Layer::ReduceType)reduce_type_int; - const float* p = src.ptr(); - float* q = dst.ptr(); - const size_t nOut = src.total() / innerLen; - - const float inv_inner = innerLen > 0 ? 1.0f / (float)innerLen : 0.0f; - - parallel_for_(Range(0, (int)nOut), [&](const Range& r) { - for (int row = r.start; row < r.end; row++) { - const float* s0 = p + (size_t)row * innerLen; - size_t i = 0, n = innerLen; -#if (CV_SIMD || CV_SIMD_SCALABLE) - const int L = VTraits::vlanes(); -#endif - switch (rt) { - case Reduce2Layer::ReduceType::MAX: { - float acc = -FLT_MAX; -#if (CV_SIMD || CV_SIMD_SCALABLE) - if (n >= (size_t)L) { - v_float32 va = vx_setall_f32(-FLT_MAX); - for (; i + L <= n; i += L) va = v_max(va, vx_load(s0 + i)); - acc = v_reduce_max(va); - } -#endif - for (; i < n; i++) acc = acc > s0[i] ? acc : s0[i]; - q[row] = acc; - break; - } - case Reduce2Layer::ReduceType::MIN: { - float acc = FLT_MAX; -#if (CV_SIMD || CV_SIMD_SCALABLE) - if (n >= (size_t)L) { - v_float32 va = vx_setall_f32(FLT_MAX); - for (; i + L <= n; i += L) va = v_min(va, vx_load(s0 + i)); - acc = v_reduce_min(va); - } -#endif - for (; i < n; i++) acc = acc < s0[i] ? acc : s0[i]; - q[row] = acc; - break; - } - case Reduce2Layer::ReduceType::SUM: - case Reduce2Layer::ReduceType::MEAN: - case Reduce2Layer::ReduceType::LOG_SUM: { - float acc = 0.0f; -#if (CV_SIMD || CV_SIMD_SCALABLE) - if (n >= (size_t)L) { - v_float32 va = vx_setzero_f32(); - for (; i + L <= n; i += L) va = v_add(va, vx_load(s0 + i)); - acc += v_reduce_sum(va); - } -#endif - for (; i < n; i++) acc += s0[i]; - if (rt == Reduce2Layer::ReduceType::MEAN) q[row] = acc * inv_inner; - else if (rt == Reduce2Layer::ReduceType::LOG_SUM) q[row] = std::log(acc); - else q[row] = acc; - break; - } - case Reduce2Layer::ReduceType::L1: { - float acc = 0.0f; -#if (CV_SIMD || CV_SIMD_SCALABLE) - if (n >= (size_t)L) { - v_float32 va = vx_setzero_f32(); - for (; i + L <= n; i += L) va = v_add(va, v_abs(vx_load(s0 + i))); - acc += v_reduce_sum(va); - } -#endif - for (; i < n; i++) acc += std::fabs(s0[i]); - q[row] = acc; - break; - } - case Reduce2Layer::ReduceType::L2: - case Reduce2Layer::ReduceType::SUM_SQUARE: { - float acc = 0.0f; -#if (CV_SIMD || CV_SIMD_SCALABLE) - if (n >= (size_t)L) { - v_float32 va = vx_setzero_f32(); - for (; i + L <= n; i += L) { - v_float32 x = vx_load(s0 + i); - va = v_add(va, v_mul(x, x)); - } - acc += v_reduce_sum(va); - } -#endif - for (; i < n; i++) { float x = s0[i]; acc += x * x; } - q[row] = (rt == Reduce2Layer::ReduceType::L2) ? std::sqrt(acc) : acc; - break; - } - case Reduce2Layer::ReduceType::PROD: { - float acc = 1.0f; -#if (CV_SIMD || CV_SIMD_SCALABLE) - if (n >= (size_t)L) { - v_float32 va = vx_setall_f32(1.0f); - for (; i + L <= n; i += L) va = v_mul(va, vx_load(s0 + i)); - float buf[VTraits::max_nlanes]; - v_store(buf, va); - for (int k = 0; k < L; k++) acc *= buf[k]; - } -#endif - for (; i < n; i++) acc *= s0[i]; - q[row] = acc; - break; - } - default: CV_Error(Error::StsInternal, "reduceLastAxesFloatParallel_: unhandled type"); - } - } - }, (double)nOut * (double)innerLen / 16384.0); -} - -CV_CPU_OPTIMIZATION_NAMESPACE_END -}} // cv::dnn - -#endif // CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY diff --git a/modules/dnn/src/layers/reduce2_layer.cpp b/modules/dnn/src/layers/reduce2_layer.cpp index 3eef667666..802038bc03 100644 --- a/modules/dnn/src/layers/reduce2_layer.cpp +++ b/modules/dnn/src/layers/reduce2_layer.cpp @@ -6,12 +6,6 @@ #include "../precomp.hpp" -#include "cpu_kernels/reduce2_kernels.simd.hpp" -#include "layers/cpu_kernels/reduce2_kernels.simd_declarations.hpp" -#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace cpu_baseline { -#define CV_CPU_OPTIMIZATION_NAMESPACE_END } -#undef CV_CPU_DISPATCH_MODES_ALL - #include #include "../net_impl.hpp" #include "../op_cann.hpp" @@ -21,12 +15,6 @@ namespace cv { namespace dnn { -template struct WorkType { using type = T; }; -template <> struct WorkType { using type = float; }; -template <> struct WorkType { using type = float; }; -template <> struct WorkType { using type = int; }; -template <> struct WorkType { using type = int; }; - class Reduce2LayerImpl CV_FINAL : public Reduce2Layer { public: @@ -168,312 +156,22 @@ public: outputs.assign(1, inputs[0]); } - template - class ReduceBase { - public: - using dtype_input = T; - using work_type = WT; - using acc_type = AccT; - typedef T dtype; - typedef WT WorkT; - ReduceBase(size_t n, const T& init) : n_(n), accumulator_(static_cast(static_cast(init))) {} - AccT finalize() const { return accumulator_; } - protected: - size_t n_; - AccT accumulator_; - }; - - template - class ReduceMin : public ReduceBase { - public: - using Base = ReduceBase; - ReduceMin(size_t n, const WT& init) : Base(n, static_cast(init)) { this->accumulator_ = static_cast(init); } - inline void update(const WT& a) { this->accumulator_ = a < static_cast(this->accumulator_) ? static_cast(a) : this->accumulator_; } - static WT identity() { return std::numeric_limits::has_infinity ? std::numeric_limits::infinity() : std::numeric_limits::max(); } - }; - - template - class ReduceMax : public ReduceBase { - public: - using Base = ReduceBase; - ReduceMax(size_t n, const WT& init) : Base(n, static_cast(init)) { this->accumulator_ = static_cast(init); } - inline void update(const WT& a) { this->accumulator_ = a > static_cast(this->accumulator_) ? static_cast(a) : this->accumulator_; } - static WT identity() { return std::numeric_limits::has_infinity ? -std::numeric_limits::infinity() : std::numeric_limits::lowest(); } - }; - - template - class ReduceSum : public ReduceBase { - public: - using Base = ReduceBase; - ReduceSum(size_t n, const WT&) : Base(n, static_cast(0)) { this->accumulator_ = AccT(0); } - inline void update(const WT& a) { this->accumulator_ += static_cast(a); } - static WT identity() { return WT(0); } - }; - - template - class ReduceMean : public ReduceSum { - public: - using Base = ReduceSum; - ReduceMean(size_t n, const WT& init) : Base(n, init) {} - inline AccT finalize() const { - return (this->n_ > 0) ? (this->accumulator_ / static_cast(this->n_)) : AccT(0); + static int toCoreReduceOp(ReduceType t) + { + switch (t) { + case ReduceType::MAX: return REDUCE_MAX; + case ReduceType::MIN: return REDUCE_MIN; + case ReduceType::MEAN: return REDUCE_AVG; + case ReduceType::SUM: return REDUCE_SUM; + case ReduceType::L1: return REDUCE_L1; + case ReduceType::L2: return REDUCE_L2; + case ReduceType::PROD: return REDUCE_PROD; + case ReduceType::SUM_SQUARE: return REDUCE_SUM2; + case ReduceType::LOG_SUM: return REDUCE_LOG_SUM; + case ReduceType::LOG_SUM_EXP: return REDUCE_LOG_SUM_EXP; + } + CV_Error(Error::StsBadArg, "DNN/Reduce: Unsupported operation."); } - static WT identity() { return WT(0); } - }; - - template - class ReduceSumSquare : public ReduceBase { - public: - using Base = ReduceBase; - ReduceSumSquare(size_t n, const WT&) : Base(n, static_cast(0)) { this->accumulator_ = AccT(0); } - inline void update(const WT& a) { this->accumulator_ += static_cast(a) * static_cast(a); } - static WT identity() { return WT(0); } - }; - - template - class ReduceL1 : public ReduceBase { - public: - using Base = ReduceBase; - ReduceL1(size_t n, const WT&) : Base(n, static_cast(0)) { this->accumulator_ = AccT(0); } - inline void update(const WT& a) { this->accumulator_ += static_cast(a >= WT(0) ? a : -a); } - static WT identity() { return WT(0); } - }; - - template - class ReduceL2 : public ReduceBase { - public: - using Base = ReduceBase; - ReduceL2(size_t n, const WT&) : Base(n, static_cast(0)) { this->accumulator_ = AccT(0); } - inline void update(const WT& a) { this->accumulator_ += static_cast(a) * static_cast(a); } - inline AccT finalize() const { return static_cast(std::sqrt(this->accumulator_)); } - static WT identity() { return WT(0); } - }; - - template - class ReduceProd : public ReduceBase { - public: - using Base = ReduceBase; - ReduceProd(size_t n, const WT&) : Base(n, static_cast(1)) { this->accumulator_ = static_cast(WT(1)); } - inline void update(const WT& a) { this->accumulator_ = static_cast(this->accumulator_) * static_cast(a); } - static WT identity() { return WT(1); } - }; - - template - class ReduceLogSum : public ReduceBase { - public: - using Base = ReduceBase; - ReduceLogSum(size_t n, const WT&) : Base(n, static_cast(0)) { this->accumulator_ = AccT(0); } - inline void update(const WT& a) { this->accumulator_ += static_cast(a); } - inline AccT finalize() const { - return (this->n_ > 0) ? static_cast(std::log(this->accumulator_)) : -std::numeric_limits::infinity(); - } - static WT identity() { return -std::numeric_limits::infinity(); } - }; - - template - class ReduceLogSumExp : public ReduceBase { - public: - using Base = ReduceBase; - ReduceLogSumExp(size_t n, const WT&) : Base(n, static_cast(0)) { this->accumulator_ = AccT(0); } - inline void update(const WT& a) { this->accumulator_ += static_cast(std::exp(static_cast(a))); } - inline AccT finalize() const { return static_cast(std::log(this->accumulator_)); } - static WT identity() { return -std::numeric_limits::infinity(); } - }; - - template - class ReduceAllInvoker : public ParallelLoopBody { - public: - using dtype = typename Op::dtype_input; - using WT = typename Op::work_type; - const Mat& src; - Mat& dst; - int n_reduce; - int loop_size; - int total; - int cost_per_thread; - - ReduceAllInvoker(const Mat& src_, Mat& dst_) : src(src_), dst(dst_) { - auto shape_src = shape(src); - n_reduce = std::accumulate(shape_src.begin(), shape_src.end(), 1, std::multiplies()); - loop_size = n_reduce; - total = 1; - cost_per_thread = 1; - } - - void operator()(const Range& r) const CV_OVERRIDE { - int start = r.start; - int end = r.end; - const dtype* p_src = src.ptr(); - dtype* p_dst = dst.ptr(); - for (int i = start; i < end; ++i) { - Op accumulator(n_reduce, static_cast(*p_src)); - for (int l = 0; l < loop_size; ++l) { - accumulator.update(static_cast(p_src[l])); - } - auto val = accumulator.finalize(); - p_dst[i] = saturate_cast(static_cast(val)); - } - } - }; - - template - class ReduceInvoker : public ParallelLoopBody { - public: - using dtype = typename Op::dtype_input; - using WT = typename Op::work_type; - const Mat& src; - Mat& dst; - std::vector reduced_axes; - int n_reduce; - int loop_size; - int last_reduced_dim; - int last_reduced_step; - std::vector projected_steps; - int last_unreduced_dim; - int last_unreduced_step; - std::vector unprojected_steps; - int total; - int cost_per_thread; - - ReduceInvoker(const Mat& src_, Mat& dst_, std::vector axes_) : src(src_), dst(dst_), reduced_axes(axes_) { - auto shape_src = shape(src); - - auto steps_src = shape_src; - steps_src[steps_src.size() - 1] = 1; - for (int i = (int)steps_src.size() - 2; i >= 0; --i) - steps_src[i] = steps_src[i + 1] * shape_src[i + 1]; - - size_t projection_size = 1; - for (auto axis : reduced_axes) projection_size *= shape_src[axis]; - n_reduce = (int)projection_size; - - last_reduced_dim = shape_src[reduced_axes.back()]; - last_reduced_step = steps_src[reduced_axes.back()]; - loop_size = last_reduced_dim * last_reduced_step; - projection_size /= last_reduced_dim; - - int last_reduced_axis = (int)reduced_axes.size() - 1; - if (last_reduced_axis == 0) { - projected_steps.resize(1, 0); - } else { - projected_steps.resize(projection_size); - std::vector projected_indices(last_reduced_axis, 0); - for (size_t i = 0, current_step = 0; i < projection_size; ++i) { - projected_steps[i] = current_step; - ++projected_indices[last_reduced_axis - 1]; - current_step += steps_src[reduced_axes[last_reduced_axis - 1]]; - for (int j = last_reduced_axis - 1; j > 0; --j) { - if (projected_indices[j] < shape_src[reduced_axes[j]]) - break; - // Carry into the next reduced axis, as for the - // unprojected axes below. - projected_indices[j] -= shape_src[reduced_axes[j]]; - current_step -= shape_src[reduced_axes[j]] * steps_src[reduced_axes[j]]; - ++projected_indices[j - 1]; - current_step += steps_src[reduced_axes[j - 1]]; - } - } - } - - std::vector unreduced_axes; - for (int i = 0; i < (int)shape_src.size(); ++i) { - if (std::find(reduced_axes.begin(), reduced_axes.end(), i) == reduced_axes.end()) - unreduced_axes.push_back(i); - } - size_t unprojection_size = 1; - for (auto axis : unreduced_axes) unprojection_size *= shape_src[axis]; - last_unreduced_dim = shape_src[unreduced_axes.back()]; - last_unreduced_step = steps_src[unreduced_axes.back()]; - unprojection_size /= last_unreduced_dim; - - std::vector unprojected_indices(unreduced_axes.size(), 0); - unprojected_steps.reserve(unprojection_size); - if (unprojected_indices.size() <= 1) { - unprojected_steps.push_back(0); - } else { - for (size_t i = 0, current_step = 0; i < unprojection_size; ++i) { - unprojected_steps.push_back(current_step); - ++unprojected_indices[unprojected_indices.size() - 2]; - current_step += steps_src[unreduced_axes[unreduced_axes.size() - 2]]; - for (int j = (int)unreduced_axes.size() - 2; j > 0; --j) { - if (unprojected_indices[j] < shape_src[unreduced_axes[j]]) - break; - unprojected_indices[j] -= shape_src[unreduced_axes[j]]; - current_step -= shape_src[unreduced_axes[j]] * steps_src[unreduced_axes[j]]; - ++unprojected_indices[j - 1]; - current_step += steps_src[unreduced_axes[j - 1]]; - } - } - } - - auto shape_dst = shape(dst); - total = std::accumulate(shape_dst.begin(), shape_dst.end(), 1, std::multiplies()); - cost_per_thread = (int)(projected_steps.size() * last_reduced_step); - } - - static void run(const Mat& src, Mat& dst, std::vector axes, bool noop_with_empty_axes) { - CV_Assert(src.isContinuous()); - CV_Assert(dst.isContinuous()); - if (src.total() == 0) { - dst.setTo(Scalar(static_cast(Op::identity()))); - return; - } - - if (shape(src).empty() || (shape(src).size() == 1)){ - ReduceAllInvoker p(src, dst); - p(Range(0, p.total)); - return; - } - - if (axes.empty()) { - if (noop_with_empty_axes) { - const auto p_src = src.ptr(); - auto p_dst = dst.ptr(); - std::memcpy(p_dst, p_src, sizeof(dtype) * dst.total()); - return; - } - ReduceAllInvoker p(src, dst); - double nstripes = (size_t)p.total * (size_t)p.cost_per_thread * (1 / 1024.0); - parallel_for_(Range(0, p.total), p, nstripes); - return; - } - - ReduceInvoker p(src, dst, axes); - double nstripes = (size_t)p.total * (size_t)p.cost_per_thread * (1 / 1024.0); - parallel_for_(Range(0, p.total), p, nstripes); - } - - void operator()(const Range& r) const CV_OVERRIDE { - int start = r.start; - int end = r.end; - const dtype* p_src = src.ptr(); - dtype* p_dst = dst.ptr(); - size_t main_index = start / last_unreduced_dim; - size_t loop = start % last_unreduced_dim; - size_t origin = unprojected_steps[main_index] + loop * last_unreduced_step; - for (int i = start; i < end; ++i) { - Op accumulator(n_reduce, static_cast(p_src[origin + projected_steps[0]])); - for (auto projected_step : projected_steps) { - const dtype* loop_p_src = p_src + origin + projected_step; - for (auto l = 0; l < loop_size; l += last_reduced_step) { - accumulator.update(static_cast(loop_p_src[l])); - } - } - auto val = accumulator.finalize(); - p_dst[i] = saturate_cast(static_cast(val)); - - ++loop; - if (loop >= last_unreduced_dim) { - loop = 0; - ++main_index; - if (main_index < unprojected_steps.size()) - origin = unprojected_steps[main_index]; - } else { - origin += last_unreduced_step; - } - } - } - }; void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE { @@ -531,42 +229,24 @@ public: outputs_arr.getMatVector(outputs); Mat& dst = outputs[0]; - if (src.depth() == CV_32F && src.isContinuous() && dst.isContinuous() && - reduce_type != ReduceType::LOG_SUM_EXP) { - if (dst.total() == 1) { - CV_CPU_DISPATCH(reduceAllFloatParallel_, (src, dst, (int)reduce_type), - NEON, AVX2, AVX, BASELINE); - return; - } - size_t innerLen = 1; - if (reduceTrailingAxesLen(src, axes, innerLen) && innerLen > 1) { - CV_CPU_DISPATCH(reduceLastAxesFloatParallel_, (src, dst, innerLen, (int)reduce_type), - NEON, AVX2, AVX, BASELINE); - return; - } + if (axes.empty() && noop_with_empty_axes) { + src.copyTo(dst); + return; } + if (src.depth() == CV_Bool) + CV_Assert(reduce_type == ReduceType::MAX || reduce_type == ReduceType::MIN); - typeDispatch(dst.type(), src, dst, axes, noop_with_empty_axes); + // reduce into a keepdims view of the output, which has the same layout + MatShape keepShape = inpShape; + if (axes.empty()) + std::fill(keepShape.begin(), keepShape.end(), 1); + for (int a : axes) + keepShape[a] = 1; + CV_Assert(dst.isContinuous() && dst.total() == keepShape.total()); + Mat dstKeep(keepShape, dst.type(), dst.data); + cv::reduce(src, dstKeep, ReduceParams(toCoreReduceOp(reduce_type), axes)); } - static bool reduceTrailingAxesLen(const Mat& src, const std::vector& axes, - size_t& innerLen) - { - MatShape s = shape(src); - int nd = s.dims; - if (axes.empty() || (int)axes.size() > nd) return false; - std::vector sorted_axes(axes.begin(), axes.end()); - std::sort(sorted_axes.begin(), sorted_axes.end()); - // Must be the trailing [nd - k .. nd - 1] block. - int k = (int)sorted_axes.size(); - for (int i = 0; i < k; i++) - if (sorted_axes[i] != nd - k + i) return false; - innerLen = 1; - for (int i = nd - k; i < nd; i++) innerLen *= (size_t)s[i]; - return true; - } - - virtual std::ostream& dumpAttrs(std::ostream& strm, int indent) const CV_OVERRIDE { prindent(strm, indent); @@ -587,42 +267,6 @@ public: strm << "]\n"; return strm; } - - template - inline void opDispatch(Args&&... args) { - switch (reduce_type) { - case ReduceType::MAX: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::MIN: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::MEAN: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::SUM: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::L1: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::L2: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::PROD: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::SUM_SQUARE: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::LOG_SUM: ReduceInvoker>::run(std::forward(args)...); break; - case ReduceType::LOG_SUM_EXP: ReduceInvoker>::run(std::forward(args)...); break; - default: CV_Error(Error::StsBadArg, "DNN/Reduce: Unsupported operation."); - } - } - - template - inline void typeDispatch(const int type, Args&&... args) { - switch (type) { - case CV_Bool: - CV_Assert(reduce_type == ReduceType::MAX || reduce_type == ReduceType::MIN); - opDispatch(std::forward(args)...); - break; - case CV_8U: opDispatch(std::forward(args)...); break; - case CV_8S: opDispatch(std::forward(args)...); break; - case CV_32S: opDispatch(std::forward(args)...); break; - case CV_64S: opDispatch(std::forward(args)...); break; - case CV_32F: opDispatch(std::forward(args)...); break; - case CV_64F: opDispatch(std::forward(args)...); break; - case CV_16F: opDispatch(std::forward(args)...); break; - case CV_16BF: opDispatch(std::forward(args)...); break; - default: CV_Error(cv::Error::BadDepth, "DNN/Reduce: Unsupported type."); - } - } }; Ptr Reduce2Layer::create(const LayerParams& params) diff --git a/modules/dnn/test/test_onnx_conformance.cpp b/modules/dnn/test/test_onnx_conformance.cpp index 8b74492f24..508683f61b 100644 --- a/modules/dnn/test/test_onnx_conformance.cpp +++ b/modules/dnn/test/test_onnx_conformance.cpp @@ -1995,6 +1995,12 @@ TEST_P(Test_ONNX_conformance, Layer_Test) applyTestTag(CV_TEST_TAG_DNN_SKIP_GLOBAL, CV_TEST_TAG_DNN_SKIP_ONNX_CONFORMANCE); } + // Reduce2 falls back to the CPU kernel on every backend; same 1 ULP product drift. + if (name == "test_reduce_prod_default_axes_keepdims_random") { + default_l1 = std::max(default_l1, 0.002); // Expected: (normL1) <= (l1), actual: 0.00195312 vs 1e-05 + default_lInf = std::max(default_lInf, 0.002); // Expected: (normInf) <= (lInf), actual: 0.00195312 vs 0.0001 + } + if (backend == DNN_BACKEND_OPENCV) { if ((target == DNN_TARGET_OPENCL_FP16) && (opencl_fp16_deny_list.find(name) != opencl_fp16_deny_list.end())) @@ -2023,10 +2029,6 @@ TEST_P(Test_ONNX_conformance, Layer_Test) default_lInf = (target == DNN_TARGET_OPENCL_FP16) ? 0.0016 : 0.0005; } } - if (name == "test_reduce_prod_default_axes_keepdims_random") { - default_l1 = 0.002; // Expected: (normL1) <= (l1), actual: 0.00195312 vs 1e-05 - default_lInf = 0.002; // Expected: (normInf) <= (lInf), actual: 0.00195312 vs 0.0001 - } if (name == "test_reduce_sum_square_default_axes_keepdims_random" || name == "test_reduce_sum_square_default_axes_keepdims_random_expanded") { default_l1 = 2e-5; // Expected: (normL1) <= (l1), actual: 1.52588e-05 vs 1e-05