diff --git a/modules/dnn/src/graph_fusion_chain.cpp b/modules/dnn/src/graph_fusion_chain.cpp index b78c5e2556..4bda69827b 100644 --- a/modules/dnn/src/graph_fusion_chain.cpp +++ b/modules/dnn/src/graph_fusion_chain.cpp @@ -43,8 +43,10 @@ void producerOf(const vector >& prog, int nargs, vector& pro class ChainFuser { public: - ChainFuser(Net::Impl& net, const Ptr& graph, const vector& usecounts) - : net_(net), graph_(graph), usecounts_(usecounts) + ChainFuser(Net::Impl& net, const Ptr& graph, const vector& usecounts, + bool transformLayoutOnly) + : net_(net), graph_(graph), usecounts_(usecounts), + transformLayoutOnly_(transformLayoutOnly) { CV_Assert((int)usecounts_.size() == (int)net_.args.size()); claimed_.assign(prog().size(), false); @@ -131,12 +133,13 @@ private: //! Producer must precede @p anchor and the arg must not be a graph output. No type check: //! an intermediate's ArgData is filled only at run time, so a gate here rejects them all. + //! The TransformLayout pass also takes a graph input (no producer), e.g. a skip connection. bool isFusableTensorArg(Arg a, size_t anchor) const { if (a.idx <= 0 || a.idx >= (int)producerOf_.size()) return false; const int prod = producerOf_[a.idx]; - if (prod < 0 || prod >= (int)anchor) + if ((prod < 0 && !transformLayoutOnly_) || prod >= (int)anchor) return false; return externalArgs_.find(a.idx) == externalArgs_.end(); } @@ -326,6 +329,10 @@ private: const FusionOps* anchorOps = fusionOpsFor(anchor); if (!anchorOps || !anchorOps->absorb) continue; + // Conv also takes tensor operands, but it was already offered its chains before + // the snapshot; after useBlockLayout() only the new TransformLayout nodes are. + if (transformLayoutOnly_ && !dynamic_cast(anchor)) + continue; ChainCandidate c; c.layerIdx.push_back((int)i); @@ -424,6 +431,7 @@ private: Net::Impl& net_; const Ptr& graph_; const vector& usecounts_; + const bool transformLayoutOnly_; AdjacencyGraphBuilder arena_; Ptr arenaPtr_; @@ -436,7 +444,7 @@ private: }; bool fuseChainsInGraph(Net::Impl& net, const Ptr& graph, - const vector& usecounts) + const vector& usecounts, bool transformLayoutOnly) { if (!graph) return false; @@ -446,7 +454,7 @@ bool fuseChainsInGraph(Net::Impl& net, const Ptr& graph, if (!layer) continue; if (vector >* subs = layer->subgraphs()) { for (Ptr& g : *subs) { - if (fuseChainsInGraph(net, g, usecounts)) + if (fuseChainsInGraph(net, g, usecounts, transformLayoutOnly)) subFused = true; } } @@ -456,7 +464,7 @@ bool fuseChainsInGraph(Net::Impl& net, const Ptr& graph, if (subFused) net.useCounts(recounted); - ChainFuser fuser(net, graph, subFused ? recounted : usecounts); + ChainFuser fuser(net, graph, subFused ? recounted : usecounts, transformLayoutOnly); const bool fusedHere = fuser.fuse(); return fusedHere || subFused; } @@ -488,7 +496,7 @@ void Net::Impl::fuseChains() vector usecounts; for (int iter = 0; iter < 10; iter++) { useCounts(usecounts); - if (!fuseChainsInGraph(*this, mainGraph, usecounts)) + if (!fuseChainsInGraph(*this, mainGraph, usecounts, false)) break; } } @@ -498,5 +506,16 @@ void Net::Impl::fuseChains() fuseInstanceNormAffine(); } +void Net::Impl::fuseTransformLayoutChains() +{ + // Chain pass only: the passes above already ran before the snapshot. TransformLayout + // absorbs a single Add, so there is no next step to expose and one round is enough. + if (!mainGraph || IS_DNN_OPENCL_TARGET(preferableTarget)) + return; + vector usecounts; + useCounts(usecounts); + fuseChainsInGraph(*this, mainGraph, usecounts, true); +} + CV__DNN_INLINE_NS_END }} // namespace cv::dnn diff --git a/modules/dnn/src/layers/conv2_common.hpp b/modules/dnn/src/layers/conv2_common.hpp index 289c4f9a17..b071c81cef 100644 --- a/modules/dnn/src/layers/conv2_common.hpp +++ b/modules/dnn/src/layers/conv2_common.hpp @@ -6,6 +6,7 @@ #define __OPENCV_DNN_LAYERS_CONV2_COMMON_HPP__ #include +#include #include namespace cv @@ -98,6 +99,23 @@ struct ConvState AutoPadding getAutoPadding(const LayerParams& params); +// Extra spatial split for when total_blocks alone is too few tasks to occupy +// every thread. Returns 1 (no-op) once total_blocks already saturates the pool. +static inline int computeSpatChunks(int total_blocks, int planeblocks, int min_per_chunk = 16) { + // Several tasks per thread let parallel_for_ even out uneven chunks. + // Value kept from the original forward-conv tuning (#28691). + constexpr int TASKS_PER_THREAD = 8; + int nSpatChunks = 1; + int nthreads = cv::getNumThreads(); + int target_tasks = nthreads * TASKS_PER_THREAD; + if (total_blocks < target_tasks && planeblocks > min_per_chunk) { + nSpatChunks = (target_tasks + total_blocks - 1) / total_blocks; + int max_chunks = planeblocks / min_per_chunk; + nSpatChunks = std::min(nSpatChunks, std::max(1, max_chunks)); + } + return nSpatChunks; +} + typedef void (*ConvFunc)(const void* inp, const void* residual, void* out, const ConvState& cs, const void* weights, const float* scale, const float* bias); diff --git a/modules/dnn/src/layers/cpu_kernels/conv2_deconv.cpp b/modules/dnn/src/layers/cpu_kernels/conv2_deconv.cpp index 25b0f55d56..b2f37bf763 100644 --- a/modules/dnn/src/layers/cpu_kernels/conv2_deconv.cpp +++ b/modules/dnn/src/layers/cpu_kernels/conv2_deconv.cpp @@ -71,8 +71,24 @@ static void deconvBlock32f(const void* inp__, const void* /*residual*/, #endif const int NK1 = N * K1; - parallel_for_(Range(0, NK1), [&](const Range& range) { - for (int nk1 = range.start; nk1 < range.end; nk1++) { + + // NK1 alone can be too few tasks; split the spatial range too. Safe without + // sync -- the loop gathers, not scatters, so each opos_flat owns one slot. + const int nSpatChunks = computeSpatChunks(NK1, ospatial); + const int spatChunkSize = (ospatial + nSpatChunks - 1) / nSpatChunks; + const int total_tasks = NK1 * nSpatChunks; + + parallel_for_(Range(0, total_tasks), [&](const Range& range) { + for (int task = range.start; task < range.end; task++) { + // nk1-major/chunk-minor keeps a thread's slice within one (n,k1) block, + // weights hot and out_k1 writes contiguous. + const int nk1 = task / nSpatChunks; + const int chunk = task % nSpatChunks; + + const int opos_begin = chunk * spatChunkSize; + const int opos_end = std::min(opos_begin + spatChunkSize, ospatial); + if (opos_begin >= opos_end) continue; + const int n = nk1 / K1; const int k1 = nk1 % K1; @@ -94,7 +110,7 @@ static void deconvBlock32f(const void* inp__, const void* /*residual*/, } #endif - for (int opos_flat = 0; opos_flat < ospatial; opos_flat++) { + for (int opos_flat = opos_begin; opos_flat < opos_end; opos_flat++) { float* out_ptr = out_k1 + opos_flat * C0; // Bias init: write currK0 valid lanes + zero-pad the rest. diff --git a/modules/dnn/src/layers/cpu_kernels/conv2_kernels.simd.hpp b/modules/dnn/src/layers/cpu_kernels/conv2_kernels.simd.hpp index 19ca02ef72..67a29e09bc 100644 --- a/modules/dnn/src/layers/cpu_kernels/conv2_kernels.simd.hpp +++ b/modules/dnn/src/layers/cpu_kernels/conv2_kernels.simd.hpp @@ -476,19 +476,6 @@ CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN #endif -// Compute number of spatial chunks for load balancing across threads. -static int computeSpatChunks(int total_blocks, int planeblocks, int min_per_chunk = 16) { - int nSpatChunks = 1; - int nthreads = cv::getNumThreads(); - int target_tasks = nthreads * 8; - if (total_blocks < target_tasks && planeblocks > min_per_chunk) { - nSpatChunks = (target_tasks + total_blocks - 1) / total_blocks; - int max_chunks = planeblocks / min_per_chunk; - nSpatChunks = std::min(nSpatChunks, std::max(1, max_chunks)); - } - return nSpatChunks; -} - static void setupActivation(const ConvState& cs, int K, FastActivation& fastActivation, const float*& activParams, ActivationFunc& activation, float& maxval, float& defaultAlpha) { diff --git a/modules/dnn/src/layers/transform_layout_layer.cpp b/modules/dnn/src/layers/transform_layout_layer.cpp index 608fb6dddc..83a3d4e834 100644 --- a/modules/dnn/src/layers/transform_layout_layer.cpp +++ b/modules/dnn/src/layers/transform_layout_layer.cpp @@ -5,6 +5,7 @@ #include "../precomp.hpp" #include "layers_common.hpp" #include "../net_impl.hpp" +#include "../adjacency_graph.hpp" #if defined(__AVX2__) #include @@ -253,7 +254,7 @@ TransformLayoutFunc getTransformLayoutFunc(DataLayout inplayout, DataLayout outl void transformLayout(const Mat& inp, Mat& out, DataLayout outlayout, DataLayout defaultLayout, - int C0) + int C0, const Mat& residual) { CV_Assert(defaultLayout == DATA_LAYOUT_NCHW || defaultLayout == DATA_LAYOUT_NHWC); CV_Assert(outlayout == DATA_LAYOUT_BLOCK || outlayout == DATA_LAYOUT_NCHW || outlayout == DATA_LAYOUT_NHWC); @@ -271,11 +272,22 @@ void transformLayout(const Mat& inp, Mat& out, MatShape outshape = inferTransformLayoutShape(inpshape, outlayout, defaultLayout, C0); out.fit(outshape, inp.type()); + // A residual is only fused into a float32 conversion to NCHW, with the exact output shape. + const bool addResidual = !residual.empty(); + if (addResidual) { + CV_Assert(outlayout == DATA_LAYOUT_NCHW); + CV_Assert(inp.type() == CV_32F && residual.type() == CV_32F); + CV_Assert(residual.size == out.size && residual.isContinuous()); + } + if (inp.empty()) return; if (inplayout == outlayout) { - inp.copyTo(out); + if (addResidual) + add(inp, residual, out); + else + inp.copyTo(out); return; } @@ -315,6 +327,7 @@ void transformLayout(const Mat& inp, Mat& out, bool interleave = inplayout == DATA_LAYOUT_NCHW; const uint8_t* inptr = (const uint8_t*)inp.data; uint8_t* outptr = (uint8_t*)out.data; + const uint8_t* resptr = residual.data; for (int chunk = range.start; chunk < range.end; chunk += dchunk) { @@ -334,6 +347,12 @@ void transformLayout(const Mat& inp, Mat& out, } kernel(inptr + inpofs, outptr + outofs, C, planesize, nc, nzc, dlen); + if (addResidual) { + // The chunk just written is nzc NCHW rows of dlen floats, planesize apart. + size_t step = planesize * sizeof(float); + Mat dst(nzc, (int)dlen, CV_32F, outptr + outofs, step); + add(dst, Mat(nzc, (int)dlen, CV_32F, (void*)(resptr + outofs), step), dst); + } } }, nstripes); } @@ -343,6 +362,7 @@ class TransformLayoutLayerImpl : public TransformLayoutLayer public: TransformLayoutLayerImpl(const LayerParams& params) { + registerFusionOpsOnce({ nullptr, &absorbOp, true }); setParamsFrom(params); layout = (DataLayout)params.get("layout"); C0 = params.get("C0", 1); @@ -365,10 +385,33 @@ public: return false; } + static bool absorbOp(Layer* self, const Ptr& expr) + { + return static_cast(self)->absorbMath(expr); + } + + // Accepts exactly ADD(INPUT, TENSOR); the residual is wired on as a real + // input by fuseLongestChains(), not here. + bool absorbMath(const Ptr& expr) + { + if (fusedAdd || !expr || expr->size() != 3 || layout != DATA_LAYOUT_NCHW) + return false; + const std::vector& nd = expr->nodes(); + const FusionNode& root = nd[expr->outputNode()]; + if (root.op != FusionEltwiseOp::ADD || root.inputs.size() != 2) + return false; + if (root.inputs[0] != 0 || nd[root.inputs[1]].op != FusionEltwiseOp::TENSOR) + return false; + if (expr->tensorArgs.size() != 1) + return false; + fusedAdd = true; + return true; + } + virtual int64_t getFLOPS(const std::vector &inputs, const std::vector &outputs) const CV_OVERRIDE { - CV_Assert(inputs.size() == 1); + CV_Assert(inputs.size() == (fusedAdd ? 2u : 1u)); CV_Assert(outputs.size() == 1); // probably, there should be a coefficient in the case of complex reduction functions return (int64_t)std::max(inputs[0].total(), outputs[0].total()); @@ -380,7 +423,7 @@ public: std::vector& temptypes) const CV_OVERRIDE { int ninputs = (int)inptypes.size(); - CV_Assert(ninputs == 1); + CV_Assert(ninputs == (fusedAdd ? 2 : 1)); outtypes.assign(1, inptypes[0]); temptypes.clear(); @@ -398,9 +441,14 @@ public: std::vector &tempshapes) const CV_OVERRIDE { size_t ninputs = inpshapes.size(); - CV_Assert(ninputs == 1); + CV_Assert(ninputs == (fusedAdd ? 2u : 1u)); - outshapes.assign(1, inferShape(inpshapes[0])); + MatShape outshape = inferShape(inpshapes[0]); + // Shapes aren't known when the Add is fused, so a broadcasting residual can + // show up here; the result then takes the Add's broadcast shape. + if (fusedAdd && inpshapes[1] != outshape) + outshape = outshape.expand(inpshapes[1]); + outshapes.assign(1, outshape); tempshapes.clear(); return true; } @@ -414,7 +462,7 @@ public: OutputArrayOfArrays) CV_OVERRIDE { size_t ninputs = inputs_arr.total(); - CV_Assert(ninputs == 1); + CV_Assert(ninputs == (fusedAdd ? 2u : 1u)); int inptype = inputs_arr.type(0); MatShape inpshape = inputs_arr.shape(0); @@ -427,10 +475,15 @@ public: Mat inp = inputs_arr.getMat(0); std::vector& outs = outputs_arr.getMatVecRef(); outs.resize(1); - outs[0].fit(outshape, inptype); - runOp(inp, outs[0]); + if (fusedAdd) { + runOpAdd(inp, inputs_arr.getMat(1), outs[0]); + } else { + outs[0].fit(outshape, inptype); + runOp(inp, outs[0]); + } } else { // [TODO] more efficient OpenCL implementation + // fusedAdd is never set here: fuseChains() refuses to run on an OpenCL target. Mat inp = inputs_arr.getMat(0); std::vector& outs = outputs_arr.getUMatVecRef(); outs.resize(1); @@ -458,6 +511,34 @@ public: CV_Assert(err == 0.); #endif } + + void runOpAdd(const Mat& inp, const Mat& residual, Mat& out) + { + CV_Assert(layout == DATA_LAYOUT_NCHW); + DataLayout origLayout = getNetImpl(this)->originalLayout; + MatShape outshape = inferShape(inp.shape()); + + if (residual.shape() == outshape && inp.type() == CV_32F && residual.type() == CV_32F) { + // Fused path. The conversion writes out before reading the residual, + // so the buffers must not alias. + CV_Assert(out.data != inp.data && out.data != residual.data); + transformLayout(inp, out, layout, origLayout, C0, residual); + return; + } + + // Broadcasting (or non-float) residual: do exactly what the fused-away Add did. + Mat converted; + transformLayout(inp, converted, layout, origLayout, C0); + MatShape addshape = outshape.expand(residual.shape()); + Mat a, b; + if (converted.shape() == addshape) a = converted; else broadcast(converted, addshape, a); + if (residual.shape() == addshape) b = residual; else broadcast(residual, addshape, b); + add(a, b, out); + } + +private: + // Set by absorbMath() when a following elementwise Add has been folded in. + bool fusedAdd = false; }; Ptr TransformLayoutLayer::create(const LayerParams& params) diff --git a/modules/dnn/src/net_impl.hpp b/modules/dnn/src/net_impl.hpp index 85c9298bc8..66dbc77f27 100644 --- a/modules/dnn/src/net_impl.hpp +++ b/modules/dnn/src/net_impl.hpp @@ -545,6 +545,9 @@ struct Net::Impl : public detail::NetImplBase // collapse Reshape+InstanceNorm+Reshape+Mul+Add into InstanceNorm or GroupNormalization void fuseInstanceNormAffine(); void fuseChains(); + // fuseChains()'s chain pass limited to TransformLayout sinks; run + // after useBlockLayout(), which is what creates those nodes + void fuseTransformLayoutChains(); // fuse ViT-style multi-head attention subgraphs void fuseAttention(); // rewrite MatMul(A, const_B [, const_bias]) into Gemm so projection-style @@ -589,8 +592,10 @@ Net readNetFromONNX2_ORT(const String& onnxFile); CV__DNN_INLINE_NS_END +// residual (optional): added to the result in the same pass; see transform_layout_layer.cpp void transformLayout(const Mat& inp, Mat& out, - DataLayout outlayout, DataLayout defaultLayout, int C0); + DataLayout outlayout, DataLayout defaultLayout, int C0, + const Mat& residual = Mat()); }} // namespace cv::dnn #endif // __OPENCV_DNN_SRC_NET_IMPL_HPP__ diff --git a/modules/dnn/src/net_impl2.cpp b/modules/dnn/src/net_impl2.cpp index 5a2373d85a..9b06e3850b 100644 --- a/modules/dnn/src/net_impl2.cpp +++ b/modules/dnn/src/net_impl2.cpp @@ -752,6 +752,9 @@ void Net::Impl::finalize() for (const Ptr& g : allgraphs) finalizeGraph(g, useCUDA); useBlockLayout(); + // TransformLayout nodes only exist from here on; fuse residual Adds into + // them, and leave every layer already fused before the snapshot alone. + fuseTransformLayoutChains(); assignBuffers(); totalLayers = updateGraphOfs(mainGraph, 0, true); diff --git a/modules/dnn/test/test_fusion.cpp b/modules/dnn/test/test_fusion.cpp index aec556c0a8..28d06d53a7 100644 --- a/modules/dnn/test/test_fusion.cpp +++ b/modules/dnn/test/test_fusion.cpp @@ -13,6 +13,11 @@ namespace opencv_test { namespace { using namespace cv::dnn; +static std::string _tf(const std::string& filename, bool required = true) +{ + return findDataFile(std::string("dnn/onnx/") + filename, required); +} + static const std::vector kNoBufs; // A standalone graph from one layer's math. Only tests build graphs this way; @@ -635,4 +640,97 @@ TEST(Fusion, BatchNormFoldsIntoPrepacked1x1Conv) checkBatchNormFoldsIntoConv("batchnorm_conv_1x1_mlas"); } +// ConvTranspose2d(8->16) -> Add(residual): the Add fuses into TransformLayout. +TEST(Fusion, TransformLayoutAddFusedMatchesUnfusedComputation) +{ + Net net = readNetFromONNX(_tf("models/deconv_transform_add.onnx")); + ASSERT_FALSE(net.empty()); + + std::vector preTypes; + net.getLayerTypes(preTypes); + ASSERT_NE(std::find(preTypes.begin(), preTypes.end(), std::string("NaryEltwise")), preTypes.end()) + << "test model must start with a separate NaryEltwise layer for this test to mean anything"; + + Mat input(std::vector{1, 8, 6, 6}, CV_32F); + theRNG().fill(input, RNG::UNIFORM, -1.0, 1.0); + Mat residual(std::vector{1, 16, 12, 12}, CV_32F); + theRNG().fill(residual, RNG::UNIFORM, -1.0, 1.0); + + net.setInput(input, "input"); + net.setInput(residual, "residual"); + + // Comes back already converted from block layout. + Mat deconvOut; + net.forward(deconvOut, "/deconv/ConvTranspose_output_0"); + + Mat fusedOut = net.forward(); + + // The fusion should have run: no NaryEltwise left in the graph. + std::vector postTypes; + net.getLayerTypes(postTypes); + EXPECT_EQ(std::find(postTypes.begin(), postTypes.end(), std::string("NaryEltwise")), postTypes.end()) + << "NaryEltwise should have been absorbed into TransformLayout by the fusion pass"; + + Mat unfusedOut; + cv::add(deconvOut, residual, unfusedOut); + + normAssert(unfusedOut, fusedOut, "fused vs unfused TransformLayout+Add", 1e-5, 1e-5); +} + +// ConvTranspose2d(8->12): C0=8 doesn't divide 12, so the last block is partial. +TEST(Fusion, TransformLayoutAddPartialChannelBlockMatchesUnfused) +{ + Net net = readNetFromONNX(_tf("models/deconv_transform_add_partial.onnx")); + ASSERT_FALSE(net.empty()); + + Mat input(std::vector{1, 8, 6, 6}, CV_32F); + theRNG().fill(input, RNG::UNIFORM, -1.0, 1.0); + Mat residual(std::vector{1, 12, 12, 12}, CV_32F); + theRNG().fill(residual, RNG::UNIFORM, -1.0, 1.0); + + net.setInput(input, "input"); + net.setInput(residual, "residual"); + + Mat deconvOut; + net.forward(deconvOut, "/deconv/ConvTranspose_output_0"); + Mat fusedOut = net.forward(); + + std::vector postTypes; + net.getLayerTypes(postTypes); + EXPECT_EQ(std::find(postTypes.begin(), postTypes.end(), std::string("NaryEltwise")), postTypes.end()) + << "NaryEltwise should have been absorbed into TransformLayout by the fusion pass"; + + Mat unfusedOut; + cv::add(deconvOut, residual, unfusedOut); + + normAssert(unfusedOut, fusedOut, "fused vs unfused, partial channel block", 1e-5, 1e-5); +} + +// Residual [1,16,1,1] broadcasts over the ConvTranspose output. Shapes aren't known +// at fusion time, so the fused layer must fall back to a broadcasting add. +TEST(Fusion, TransformLayoutAddBroadcastResidualMatchesUnfused) +{ + Net net = readNetFromONNX(_tf("models/deconv_transform_add_broadcast.onnx")); + ASSERT_FALSE(net.empty()); + + Mat input(std::vector{1, 8, 6, 6}, CV_32F); + theRNG().fill(input, RNG::UNIFORM, -1.0, 1.0); + Mat residual(std::vector{1, 16, 1, 1}, CV_32F); + theRNG().fill(residual, RNG::UNIFORM, -1.0, 1.0); + + net.setInput(input, "input"); + net.setInput(residual, "residual"); + + Mat deconvOut; + net.forward(deconvOut, "/deconv/ConvTranspose_output_0"); + Mat fusedOut = net.forward(); + + Mat residualFull; + broadcast(residual, deconvOut.shape(), residualFull); + Mat unfusedOut; + cv::add(deconvOut, residualFull, unfusedOut); + + normAssert(unfusedOut, fusedOut, "fused vs unfused, broadcast residual", 1e-5, 1e-5); +} + }} // namespace opencv_test diff --git a/modules/dnn/test/test_onnx_importer.cpp b/modules/dnn/test/test_onnx_importer.cpp index a2aae3ca20..1d73b6d06a 100644 --- a/modules/dnn/test/test_onnx_importer.cpp +++ b/modules/dnn/test/test_onnx_importer.cpp @@ -427,6 +427,9 @@ TEST_P(Test_ONNX_layers, Deconvolution) testONNXModels("deconvolution_output_shape", npy, 0, 0, false, false); if (target != DNN_TARGET_CUDA_FP16) // bug testONNXModels("deconv_adjpad_2d", npy, 0, 0, false, false); + // out_channels == C0, so NK1 == 1: exercises computeSpatChunks()'s spatial + // split in conv2_deconv.cpp regardless of thread count. + testONNXModels("deconv_spatial_narrow", npy, 0, 0, false, false); } TEST_P(Test_ONNX_layers, Deconvolution3D)