Files
opencv-MIRROR/modules/dnn/src/graph_fusion_reshape_transpose.cpp
Savya Sanchi Sharma 02dcf56058 Merge pull request #30276 from SavyaSanchi-Sharma:opti/consts
dnn: share equal constants and merge duplicate nodes in the ONNX importer - #30276

# Summary

The ONNX importer now gives initializers with the same type, shape and bytes a single constant,
and `parseNode()` skips a node that has the same op, attributes and inputs as an earlier one,
reusing that node's outputs instead. Many exported models repeat identical work: RAFT pads the
same correlation pyramid again in each of its 10 refinement iterations, and each iteration's
`pads` constant has a different name, so the Pads only look identical when constants are
compared by value. With this change RAFT runs 5 Pads instead of 41, as ONNX Runtime does.

Custom-domain ops, random ops, nodes with subgraphs and nodes producing graph outputs are never
merged. Neither are `QuantizeLinear`/`DequantizeLinear`: `fuseQDQ()` only folds a DQ into
MatMul/Gemm/Conv while it has a single consumer, so merging them would switch off int8 fusion.

Outputs match ONNX Runtime as closely as before.

| Model | This PR | OpenCV 5.0.0 | ORT 1.30 | vs 5.0.0 | vs ORT 1.30 |
|---|---:|---:|---:|---:|---:|
| RAFT | 392.4 ms | 544.5 ms | 291.3 ms | 1.39× faster | 0.74× |
| NAFNet | 1815.8 ms | 2157.6 ms | 1532.6 ms | 1.19× faster | 0.84× |
| YOLOX | 28.3 ms | 29.8 ms | 15.1 ms | 1.05× faster | 0.53× |

> Benchmarked on AMD Ryzen 9 9950X
### 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
- [ ] The PR is proposed to the proper branch
- [ ] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-10-28 21:28:47 +03:00

226 lines
8.4 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.
// Copyright (C) 2026, BigVision LLC, all rights reserved.
// Third party copyrights are property of their respective owners.
// Cleans up redundant Reshape/Transpose chains:
// - Reshape(A) -> Reshape(B): drop the inner reshape (A's shape is irrelevant
// once B reshapes to the final target).
// - Transpose(p1) -> Transpose(p2): compose into a single Transpose with
// perm[i] = p1[p2[i]].
// - Identity Transpose (perm == [0,1,...,n-1]): bypass.
// These run iteratively, so a Reshape+Transpose+Reshape that ends up with an
// identity transpose collapses to a single Reshape, and adjacent transposes
// in attention layouts merge.
#include "precomp.hpp"
#include "net_impl.hpp"
#include "layers/layers_common.hpp"
namespace cv { namespace dnn {
CV__DNN_INLINE_NS_BEGIN
using std::vector;
using std::string;
struct ModelFusionReshapeTranspose
{
explicit ModelFusionReshapeTranspose(Net::Impl* netimpl_) : netimpl(netimpl_) {}
void fuse()
{
for (int iter = 0; iter < 10; iter++) {
netimpl->useCounts(usecounts);
if (!fuseGraph(netimpl->mainGraph))
break;
}
}
static bool isIdentityPerm(const vector<int>& perm)
{
if (perm.empty()) return false;
for (size_t i = 0; i < perm.size(); i++)
if (perm[i] != (int)i) return false;
return true;
}
// A 0 in an ONNX reshape spec means "keep the input's dim here", so the Reshape depends
// on what feeds it and its producer cannot be dropped. An unreadable spec counts too.
bool shapeSpecCopiesInputDims(const Reshape2Layer* rs) const
{
MatShape spec = rs->newShapeDesc;
if (spec.dims < 0) {
if (rs->inputs.size() != 2 || !netimpl->isConstArg(rs->inputs[1]))
return true;
const Mat& t = netimpl->argTensor(rs->inputs[1]);
if (t.empty() || !t.isContinuous() || (t.type() != CV_32S && t.type() != CV_64S))
return true;
spec = tensorToShape(t);
}
for (int i = 0; i < spec.dims; i++)
if (spec[i] == 0)
return true;
return false;
}
bool fuseGraph(Ptr<Graph>& graph)
{
const vector<Ptr<LayerInfo>>& prog = graph->prog();
size_t nops = prog.size();
bool modified = false;
for (size_t i = 0; i < nops; i++) {
if (!prog[i]) continue;
vector<Ptr<Graph>>* subgraphs = prog[i]->subgraphs();
if (subgraphs) {
for (Ptr<Graph>& g : *subgraphs)
if (fuseGraph(g)) modified = true;
}
}
std::map<int, int> producer;
std::set<int> externalArgs;
for (Arg out : graph->outputs())
externalArgs.insert(out.idx);
for (size_t i = 0; i < nops; i++) {
if (!prog[i]) continue;
for (Arg out : prog[i]->outputs)
producer[out.idx] = (int)i;
}
vector<bool> dropped(nops, false);
for (size_t i = 0; i < nops; i++) {
const Ptr<LayerInfo>& layer = prog[i];
if (!layer || dropped[i]) continue;
if (layer->inputs.empty() || layer->outputs.empty()) continue;
// Identity Transpose: bypass.
TransposeLayer* tr = dynamic_cast<TransposeLayer*>(layer.get());
if (tr && layer->outputs.size() == 1 && isIdentityPerm(tr->perm)) {
Arg out = layer->outputs[0];
if (externalArgs.count(out.idx) == 0) {
redirectConsumers(prog, dropped, i + 1, out, layer->inputs[0]);
dropped[i] = true;
usecounts[out.idx] = 0;
// The bypassed Transpose no longer reads its input. Without this the
// producer's count never reaches 0 and it survives as a dead layer.
for (Arg a : layer->inputs)
if (a.idx > 0)
usecounts[a.idx]--;
modified = true;
continue;
}
}
// Transpose + Transpose -> Transpose (compose perms).
if (tr && layer->outputs.size() == 1) {
auto it = producer.find(layer->inputs[0].idx);
if (it != producer.end()) {
int prod_idx = it->second;
if (prod_idx >= 0 && !dropped[prod_idx]) {
const Ptr<LayerInfo>& pl = prog[prod_idx];
TransposeLayer* prevTr = dynamic_cast<TransposeLayer*>(pl.get());
if (prevTr && pl->outputs.size() == 1
&& !prevTr->perm.empty()
&& prevTr->perm.size() == tr->perm.size())
{
// composed[i] = prevTr->perm[tr->perm[i]]
vector<int> composed(tr->perm.size());
bool ok = true;
for (size_t k = 0; k < tr->perm.size(); k++) {
int idx = tr->perm[k];
if (idx < 0 || idx >= (int)prevTr->perm.size()) {
ok = false; break;
}
composed[k] = prevTr->perm[idx];
}
if (ok) {
tr->perm = composed;
bypassProducer(layer, pl, prod_idx, dropped);
producer[layer->outputs[0].idx] = (int)i;
modified = true;
continue;
}
}
}
}
}
//Reshape + Reshape -> Reshape (drop the inner reshape).
Reshape2Layer* rs = dynamic_cast<Reshape2Layer*>(layer.get());
if (rs && layer->outputs.size() == 1 && !shapeSpecCopiesInputDims(rs)) {
auto it = producer.find(layer->inputs[0].idx);
if (it != producer.end()) {
int prod_idx = it->second;
if (prod_idx >= 0 && !dropped[prod_idx]) {
const Ptr<LayerInfo>& pl = prog[prod_idx];
Reshape2Layer* prevRs = dynamic_cast<Reshape2Layer*>(pl.get());
if (prevRs && pl->outputs.size() == 1)
{
bypassProducer(layer, pl, prod_idx, dropped);
modified = true;
continue;
}
}
}
}
}
if (modified) {
vector<Ptr<LayerInfo>> newprog;
newprog.reserve(nops);
for (size_t i = 0; i < nops; i++) {
if (!dropped[i] && prog[i])
newprog.push_back(prog[i]);
}
graph->setProg(newprog);
}
return modified;
}
// Feed the consumer from the producer's input; the producer goes once nothing else reads it.
void bypassProducer(const Ptr<LayerInfo>& consumer, const Ptr<LayerInfo>& pl,
int prod_idx, vector<bool>& dropped)
{
Arg out = consumer->inputs[0], src = pl->inputs[0];
consumer->inputs[0] = src;
usecounts[src.idx]++;
if (--usecounts[out.idx] == 0) {
dropped[prod_idx] = true;
for (Arg a : pl->inputs)
if (a.idx > 0)
usecounts[a.idx]--;
}
}
void redirectConsumers(const vector<Ptr<LayerInfo>>& prog,
const vector<bool>& dropped,
size_t start_idx, Arg from, Arg to)
{
for (size_t j = start_idx; j < prog.size(); j++) {
if (!prog[j] || dropped[j]) continue;
for (Arg& in : prog[j]->inputs) {
if (in.idx == from.idx) {
in = to;
usecounts[to.idx]++;
}
}
}
}
Net::Impl* netimpl;
vector<int> usecounts;
};
void Net::Impl::fuseReshapeTranspose()
{
ModelFusionReshapeTranspose pass(this);
pass.fuse();
}
CV__DNN_INLINE_NS_END
}}