mirror of
https://github.com/opencv/opencv.git
synced 2026-12-03 05:33:03 -06:00
DNN: Optimize block layout handling and fold Mul/Add into BatchNorm - #30313 Requires: https://github.com/opencv/opencv_extra/pull/1439 ### PR Changes - AveragePool runs on plain NCHW input without conversion to block layout; with an avgpool HAL hook registered, block layout is kept as before. - NaryEltwise with a scalar constant operand runs in block layout. - BatchNorm absorbs following Mul/Add by scalar or per-channel constants into its scale and bias; ChainFuser marks a [C,1,1] / [1,C,1,1] constant per channel once it proves the input is 4D. - Global average/max pooling reduces block input directly. - An elementwise op feeding a conversion to plain now runs after it, on C channels instead of C0 lanes. - Slice2 on the channel axis keeps block layout for C0-aligned or runtime bounds. ### Performance Measured on i9-14900KS, default threads (32). | Model | 5.x | After PR | ORT (1.30) | OpenCV before vs after | After PR vs ORT | |-------------|-----------:|-----------:|-----------:|-----------------------:|----------------:| | RAFT | 965.67 ms | 691.03 ms | 604.26 ms | 1.40x | 0.87x | | DenseNet121 | 14.14 ms | 9.84 ms | 12.05 ms | 1.44x | 1.22x | | XFeat | 5.80 ms | 5.63 ms | 2.95 ms | 1.03x | 0.52x | | NAFNet | 1304.50 ms | 1195.67 ms | 1407.77 ms | 1.09x | 1.18x | | RealESRGAN | 422.57 ms | 403.93 ms | 534.29 ms | 1.05x | 1.32x | | PPOCRv3_det | 14.25 ms | 14.15 ms | 16.32 ms | 1.01x | 1.15x | ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [ ] There is a reference to the original bug report and related work - [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [x] The feature is well documented and sample code can be built with the project CMake
370 lines
15 KiB
C++
370 lines
15 KiB
C++
// 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.
|
|
|
|
#include "precomp.hpp"
|
|
#include "net_impl.hpp"
|
|
|
|
namespace cv { namespace dnn {
|
|
CV__DNN_INLINE_NS_BEGIN
|
|
|
|
using std::vector;
|
|
using std::string;
|
|
|
|
using PLayer = Ptr<LayerInfo>;
|
|
using PGraph = Ptr<Graph>;
|
|
|
|
/* Inserts layout conversion operations (if needed) into the model graph and subgraphs.
|
|
|
|
Some of the operations
|
|
(let's call them 'operations of category B' or B-operations, 'B' stands for 'Block'),
|
|
most notably Convolution (including depthwise convolution), ConvTranspose, MaxPool and AveragePool,
|
|
can be computed more efficiently if data is represented in so-called block layout,
|
|
i.e. when 4D tensor NxCxHxW is represented in memory as 5D tensor NxC1xHxWxC0,
|
|
where all C channels of the original tensor are split into C1 groups of C0 channels each.
|
|
For each spatial location (y=y0, x=x0) each group of C0 channels is stored sequentially.
|
|
C1 is thus computed as following: C1 = (C + C0-1)/C0, where division is performed with truncation.
|
|
|
|
Some other operations (let's call them A-operations, 'A' stands for 'Any'),
|
|
most notably unary element-wise operations or special cases of binary
|
|
element-wise operations can be efficiently computed in any layout, including block layout.
|
|
|
|
Finally, all other operations (denoted as C-operations, 'C' for 'Casual' or 'Channels')
|
|
do not support block layout at all. The inputs should come in the original model format
|
|
(e.g. NCHW in the case of Onnx).
|
|
|
|
We want to transform the graph so that:
|
|
1. B-operations always take the inputs in block layout. If not, the inputs must be converted to
|
|
block layout prior to B-operation. Note that only the first input should be converted
|
|
in the case of Convolution, convolution weights (if constant) are pre-processed separately.
|
|
2. C-operations always take the inputs in non-block layout, e.g. NCHW. If some of the inputs are
|
|
stored in block layout, they must be converted from block layout prior to C-operation.
|
|
3. the number of layout transformation operations is minimal,
|
|
i.e. we don't do transformations unless it's necessary.
|
|
|
|
Note that this graph transformation is applied after fusion, since inside a fused operation
|
|
(e.g. 'Convolution + Batch Norm + Activation + Adding Skip connection') we don't need to
|
|
transform layout. That is, we have to deal with less operations at this stage.
|
|
*/
|
|
|
|
struct BlockLayoutTransformer
|
|
{
|
|
BlockLayoutTransformer(Net::Impl* netimpl_) : netimpl(netimpl_) {}
|
|
|
|
Net::Impl* netimpl;
|
|
vector<DataLayout> layouts; // layouts for each argument
|
|
vector<Arg> blockCache; // if an Arg needs to be converted to block layout and
|
|
// if it's used by several operations,
|
|
// then we reuse once transformed arg,
|
|
// don't transform it several times
|
|
vector<Arg> nonblockCache; // another cache of non-block args
|
|
DataLayout defaultLayout;
|
|
int trlayoutIdx;
|
|
|
|
std::pair<Arg, PLayer> getProperArg(const Arg& arg, bool block, int defaultC0)
|
|
{
|
|
if (arg.empty() || (layouts[arg.idx] == DATA_LAYOUT_BLOCK) == block)
|
|
return {arg, PLayer()};
|
|
std::vector<Arg> *cache, *altCache;
|
|
if (block) {
|
|
cache = &blockCache;
|
|
altCache = &nonblockCache;
|
|
} else {
|
|
cache = &nonblockCache;
|
|
altCache = &blockCache;
|
|
}
|
|
Arg cached = cache->at(arg.idx);
|
|
if (!cached.empty())
|
|
return {cached, PLayer()};
|
|
size_t nargs = netimpl->args.size();
|
|
CV_Assert(layouts.size() == nargs &&
|
|
cache->size() == nargs &&
|
|
altCache->size() == nargs);
|
|
|
|
const ArgData& adata = netimpl->args.at(arg.idx);
|
|
const char* suffix = block ? "block" : "nonblock";
|
|
|
|
std::string newname = format("%s.%s", adata.name.c_str(), suffix);
|
|
int idx = 1;
|
|
for ( ; netimpl->haveArg(newname); idx++) {
|
|
newname = format("%s.%s%d", adata.name.c_str(), suffix, idx);
|
|
}
|
|
|
|
cached = netimpl->newArg(newname, DNN_ARG_TEMP);
|
|
CV_Assert(size_t(cached.idx) == nargs);
|
|
|
|
cache->at(arg.idx) = cached;
|
|
cache->push_back(cached);
|
|
altCache->push_back(arg);
|
|
|
|
LayerParams params;
|
|
params.name = format("trlayout.%d", trlayoutIdx++);
|
|
params.type = "TransformLayout";
|
|
params.set("layout", int(block ? DATA_LAYOUT_BLOCK : defaultLayout));
|
|
params.set("C0", int(defaultC0));
|
|
PLayer trlayer = TransformLayoutLayer::create(params);
|
|
|
|
trlayer->netimpl = netimpl;
|
|
trlayer->inputs = {arg};
|
|
trlayer->outputs = {cached};
|
|
layouts.push_back(block ? DATA_LAYOUT_BLOCK : defaultLayout);
|
|
|
|
return {cached, trlayer};
|
|
}
|
|
|
|
void transformGraph(PGraph& g)
|
|
{
|
|
const vector<PLayer>& currProg = g->prog();
|
|
int defaultC0 = netimpl->defaultC0;
|
|
vector<PLayer> newProg;
|
|
std::vector<Arg> newInputs;
|
|
std::vector<DataLayout> inputLayoutsOrig, inputLayoutsNew, outputLayouts;
|
|
size_t nchanges = 0;
|
|
|
|
for (size_t opidx = 0; opidx < currProg.size(); opidx++) {
|
|
const PLayer& layer = currProg[opidx];
|
|
const vector<Arg>& inputs = layer->inputs;
|
|
const vector<Arg>& outputs = layer->outputs;
|
|
size_t ninputs = inputs.size(), noutputs = outputs.size();
|
|
std::string op_name = layer->type;
|
|
std::string name = layer->name;
|
|
vector<PGraph>* subgraphs = layer->subgraphs();
|
|
bool deviceOp = g->opBackend((int)opidx) != DNN_BACKEND_OPENCV;
|
|
//std::cout << "name: " << name << ", op_name: " << op_name << ", inp0 layout: " << layoutToString(layouts[inputs[0].idx]) << "\n";
|
|
|
|
if (subgraphs) {
|
|
for (PGraph& subgraph: *subgraphs) {
|
|
size_t nargsBefore = netimpl->args.size();
|
|
CV_Assert_N(nargsBefore == blockCache.size(), nargsBefore == nonblockCache.size());
|
|
transformGraph(subgraph);
|
|
size_t nargsAfter = netimpl->args.size();
|
|
CV_Assert_N(nargsAfter == blockCache.size(), nargsAfter == nonblockCache.size());
|
|
// after transforming a subgraph we 'forget' all cached transformations,
|
|
// because they need to be redone in the outer graph and/or other subgraphs.
|
|
// however, we cannot remove the newly added arguments, because we need to properly
|
|
// assign memory buffers for them etc.
|
|
for (size_t i = nargsBefore; i < nargsAfter; i++) {
|
|
Arg b = blockCache[i];
|
|
Arg nb = nonblockCache[i];
|
|
if (size_t(b.idx) < nargsBefore) {
|
|
nonblockCache[b.idx] = Arg();
|
|
}
|
|
if (size_t(nb.idx) < nargsBefore) {
|
|
blockCache[nb.idx] = Arg();
|
|
}
|
|
}
|
|
nchanges += nargsAfter > nargsBefore;
|
|
}
|
|
}
|
|
|
|
inputLayoutsOrig.clear();
|
|
for (size_t i = 0; i < ninputs; i++) {
|
|
inputLayoutsOrig.push_back(layouts.at(inputs[i].idx));
|
|
}
|
|
|
|
layer->getLayouts(inputLayoutsOrig, inputLayoutsNew, int(noutputs), outputLayouts);
|
|
CV_Assert(inputLayoutsNew.size() == ninputs);
|
|
CV_Assert(outputLayouts.size() == noutputs);
|
|
|
|
if (deviceOp) {
|
|
for (size_t i = 0; i < ninputs; i++)
|
|
inputLayoutsNew[i] = defaultLayout;
|
|
for (size_t i = 0; i < noutputs; i++)
|
|
outputLayouts[i] = defaultLayout;
|
|
}
|
|
|
|
newInputs.clear();
|
|
bool changedInputs = false;
|
|
for (size_t i = 0; i < ninputs; i++) {
|
|
Arg inp = inputs[i];
|
|
DataLayout prevLayout = inputLayoutsOrig[i];
|
|
DataLayout newLayout = inputLayoutsNew[i];
|
|
if (!inp.empty()) {
|
|
if (prevLayout == DATA_LAYOUT_BLOCK) {
|
|
blockCache.at(inp.idx) = inp;
|
|
} else {
|
|
nonblockCache.at(inp.idx) = inp;
|
|
}
|
|
}
|
|
if (newLayout != prevLayout &&
|
|
(newLayout == DATA_LAYOUT_BLOCK ||
|
|
prevLayout == DATA_LAYOUT_BLOCK)) {
|
|
auto p = getProperArg(inp, newLayout == DATA_LAYOUT_BLOCK, defaultC0);
|
|
newInputs.push_back(p.first);
|
|
if (p.second) {
|
|
newProg.push_back(p.second);
|
|
}
|
|
changedInputs = true;
|
|
nchanges++;
|
|
} else {
|
|
newInputs.push_back(inp);
|
|
}
|
|
}
|
|
|
|
for (size_t i = 0; i < noutputs; i++) {
|
|
layouts.at(outputs[i].idx) = outputLayouts[i];
|
|
}
|
|
|
|
if (changedInputs) {
|
|
layer->inputs = newInputs;
|
|
}
|
|
newProg.push_back(layer);
|
|
}
|
|
|
|
if (nchanges > 0) {
|
|
g->setProg(newProg);
|
|
}
|
|
}
|
|
|
|
void transform()
|
|
{
|
|
size_t nargs = netimpl->args.size();
|
|
defaultLayout = netimpl->originalLayout;
|
|
trlayoutIdx = 0;
|
|
|
|
layouts.assign(nargs, DATA_LAYOUT_UNKNOWN);
|
|
blockCache.assign(nargs, Arg());
|
|
nonblockCache.assign(nargs, Arg());
|
|
|
|
transformGraph(netimpl->mainGraph);
|
|
netimpl->useCounts(usecounts);
|
|
hoistConversions(netimpl->mainGraph);
|
|
}
|
|
|
|
//! The only non-constant input of an elementwise op, or -1.
|
|
int flowInput(const PLayer& layer) const
|
|
{
|
|
bool elementwise = dynamic_cast<ActivationLayer*>(layer.get()) ||
|
|
dynamic_cast<NaryEltwiseLayer*>(layer.get());
|
|
if (!elementwise || layer->outputs.size() != 1 || layer->subgraphs())
|
|
return -1;
|
|
int flow = -1;
|
|
for (size_t i = 0; i < layer->inputs.size(); i++) {
|
|
if (netimpl->isConstArg(layer->inputs[i]))
|
|
continue;
|
|
if (flow >= 0)
|
|
return -1;
|
|
flow = (int)i;
|
|
}
|
|
return flow;
|
|
}
|
|
|
|
//! The conversion later absorbs an Add of a live tensor right after it, which an op moved
|
|
//! in between would prevent.
|
|
bool feedsResidualAdd(const vector<PLayer>& prog, const vector<int>& consumer, Arg z) const
|
|
{
|
|
int c = usecounts[z.idx] == 1 ? consumer[z.idx] : -1;
|
|
const NaryEltwiseLayer* add =
|
|
c >= 0 ? dynamic_cast<const NaryEltwiseLayer*>(prog[c].get()) : nullptr;
|
|
if (!add || add->inputs.size() != 2 ||
|
|
(add->op != NaryEltwiseLayer::OPERATION::ADD &&
|
|
add->op != NaryEltwiseLayer::OPERATION::SUM))
|
|
return false;
|
|
int k = add->inputs[0].idx == z.idx ? 1 : add->inputs[1].idx == z.idx ? 0 : -1;
|
|
return k >= 0 && !netimpl->isConstArg(add->inputs[k]);
|
|
}
|
|
|
|
//! A plain copy of block @p x produced before @p pos in this graph, or an empty Arg.
|
|
Arg plainCopyBefore(const vector<PLayer>& prog, const vector<int>& producer,
|
|
const vector<int>& consumer, const vector<Arg>& hoisted,
|
|
Arg x, int pos) const
|
|
{
|
|
for (Arg p : { hoisted[x.idx], nonblockCache[x.idx] }) {
|
|
int pp = p.empty() ? -1 : producer[p.idx];
|
|
const TransformLayoutLayer* tr = pp >= 0 && pp < pos ?
|
|
dynamic_cast<const TransformLayoutLayer*>(prog[pp].get()) : nullptr;
|
|
if (tr && tr->layout != DATA_LAYOUT_BLOCK && tr->inputs[0].idx == x.idx &&
|
|
tr->outputs[0].idx == p.idx && !feedsResidualAdd(prog, consumer, p))
|
|
return p;
|
|
}
|
|
return Arg();
|
|
}
|
|
|
|
// An elementwise op feeding only a conversion to plain runs after it instead: the same copy,
|
|
// but the op then works on C channels rather than on padded C0 lanes. When its input already
|
|
// has a plain copy, the op reads that one and the conversion is dropped.
|
|
void hoistConversions(PGraph& g)
|
|
{
|
|
vector<PLayer> prog = g->prog();
|
|
size_t nops = prog.size();
|
|
vector<int> producer(netimpl->args.size(), -1), consumer(netimpl->args.size(), -1);
|
|
vector<Arg> hoisted(netimpl->args.size());
|
|
for (size_t i = 0; i < nops; i++) {
|
|
vector<PGraph>* subgraphs = prog[i]->subgraphs();
|
|
if (subgraphs) {
|
|
for (PGraph& subgraph: *subgraphs)
|
|
hoistConversions(subgraph);
|
|
}
|
|
for (Arg out: prog[i]->outputs)
|
|
producer[out.idx] = (int)i;
|
|
for (Arg inp: prog[i]->inputs)
|
|
consumer[inp.idx] = (int)i;
|
|
}
|
|
|
|
bool changed = false;
|
|
for (size_t i = 0; i < nops; i++) {
|
|
TransformLayoutLayer* tr = dynamic_cast<TransformLayoutLayer*>(prog[i].get());
|
|
if (!tr || tr->layout == DATA_LAYOUT_BLOCK ||
|
|
feedsResidualAdd(prog, consumer, tr->outputs[0]))
|
|
continue;
|
|
int tidx = (int)i;
|
|
for (;;) {
|
|
Arg y = prog[tidx]->inputs[0];
|
|
int pidx = producer[y.idx];
|
|
if (pidx < 0 || !prog[pidx] || usecounts[y.idx] != 1)
|
|
break;
|
|
const PLayer& op = prog[pidx];
|
|
int flow = flowInput(op);
|
|
if (flow < 0 || layouts[op->inputs[flow].idx] != DATA_LAYOUT_BLOCK)
|
|
break;
|
|
Arg x = op->inputs[flow], z = prog[tidx]->outputs[0];
|
|
Arg p = plainCopyBefore(prog, producer, consumer, hoisted, x, tidx);
|
|
if (!p.empty()) {
|
|
// op: p -> z in the conversion's slot (it was op: x -> y, conversion: y -> z)
|
|
PLayer layer = op;
|
|
layer->inputs[flow] = p;
|
|
layer->outputs[0] = z;
|
|
prog[tidx] = layer;
|
|
prog[pidx] = PLayer();
|
|
usecounts[x.idx]--;
|
|
usecounts[p.idx]++;
|
|
usecounts[y.idx] = 0;
|
|
producer[y.idx] = -1;
|
|
producer[z.idx] = tidx;
|
|
changed = true;
|
|
break;
|
|
}
|
|
// conversion: x -> y, op: y -> z, where it was op: x -> y, conversion: y -> z
|
|
if (hoisted[x.idx].empty())
|
|
hoisted[x.idx] = y;
|
|
prog[tidx]->inputs[0] = x;
|
|
prog[tidx]->outputs[0] = y;
|
|
op->inputs[flow] = y;
|
|
op->outputs[0] = z;
|
|
layouts[y.idx] = defaultLayout;
|
|
std::swap(prog[tidx], prog[pidx]);
|
|
producer[y.idx] = pidx;
|
|
producer[z.idx] = tidx;
|
|
tidx = pidx;
|
|
changed = true;
|
|
}
|
|
}
|
|
if (changed) {
|
|
prog.erase(std::remove_if(prog.begin(), prog.end(),
|
|
[](const PLayer& l) { return !l; }), prog.end());
|
|
g->setProg(prog);
|
|
}
|
|
}
|
|
|
|
vector<int> usecounts;
|
|
};
|
|
|
|
void Net::Impl::useBlockLayout()
|
|
{
|
|
BlockLayoutTransformer use_block_layout(this);
|
|
use_block_layout.transform();
|
|
}
|
|
|
|
CV__DNN_INLINE_NS_END
|
|
}}
|