mirror of
https://github.com/opencv/opencv.git
synced 2026-12-05 14:35:09 -06:00
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
128 lines
4.0 KiB
C++
128 lines
4.0 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.
|
|
|
|
// Folds a Transpose-of-last-two-dims into the consuming MatMul's trans_a / trans_b.
|
|
//
|
|
// Pattern:
|
|
// X -> Transpose(perm=[0,..,n-3, n-1, n-2]) -> MatMul(., Y)
|
|
// => X -> MatMul(trans_a=true, ., Y)
|
|
//
|
|
// Symmetric on the second operand -> trans_b.
|
|
|
|
#include "precomp.hpp"
|
|
#include "net_impl.hpp"
|
|
|
|
namespace cv { namespace dnn {
|
|
CV__DNN_INLINE_NS_BEGIN
|
|
|
|
using std::vector;
|
|
using std::string;
|
|
|
|
struct ModelFusionTransposeMatMul
|
|
{
|
|
explicit ModelFusionTransposeMatMul(Net::Impl* netimpl_) : netimpl(netimpl_) {}
|
|
|
|
void fuse() { fuseGraph(netimpl->mainGraph); }
|
|
|
|
static bool isLastTwoSwap(const vector<int>& perm)
|
|
{
|
|
int n = (int)perm.size();
|
|
if (n < 2) return false;
|
|
for (int i = 0; i < n - 2; i++)
|
|
if (perm[i] != i) return false;
|
|
return perm[n - 2] == n - 1 && perm[n - 1] == n - 2;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
|
|
// Graph outputs count as uses, so a producer that is one never reaches zero.
|
|
vector<int> usecounts;
|
|
netimpl->useCounts(usecounts);
|
|
|
|
std::map<int, int> producer;
|
|
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;
|
|
|
|
MatMulLayer* mm = dynamic_cast<MatMulLayer*>(layer.get());
|
|
if (!mm) continue;
|
|
// MatMulInt8Layer does not read trans_a/trans_b
|
|
if (dynamic_cast<MatMulInt8Layer*>(layer.get())) continue;
|
|
|
|
if (layer->inputs.size() != 2) continue;
|
|
|
|
for (int slot = 0; slot < 2; slot++) {
|
|
Arg in = layer->inputs[slot];
|
|
auto it = producer.find(in.idx);
|
|
if (it == producer.end()) continue;
|
|
int prod_idx = it->second;
|
|
if (prod_idx < 0 || dropped[prod_idx]) continue;
|
|
|
|
const Ptr<LayerInfo>& pl = prog[prod_idx];
|
|
TransposeLayer* tr = dynamic_cast<TransposeLayer*>(pl.get());
|
|
if (!tr || pl->outputs.size() != 1) continue;
|
|
if (!isLastTwoSwap(tr->perm)) continue;
|
|
|
|
if (slot == 0) mm->trans_a = !mm->trans_a;
|
|
else mm->trans_b = !mm->trans_b;
|
|
|
|
// A shared Transpose stays until its last consumer has folded it.
|
|
Arg src = pl->inputs[0];
|
|
layer->inputs[slot] = src;
|
|
usecounts[src.idx]++;
|
|
if (--usecounts[in.idx] == 0) {
|
|
dropped[prod_idx] = true;
|
|
usecounts[src.idx]--;
|
|
}
|
|
modified = true;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
Net::Impl* netimpl;
|
|
};
|
|
|
|
void Net::Impl::fuseTransposeMatMul()
|
|
{
|
|
ModelFusionTransposeMatMul pass(this);
|
|
pass.fuse();
|
|
}
|
|
|
|
CV__DNN_INLINE_NS_END
|
|
}}
|