mirror of
https://github.com/opencv/opencv.git
synced 2026-12-02 21:22:43 -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
152 lines
5.0 KiB
C++
152 lines
5.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 scalar Mul / Div immediately preceding Softmax into the Softmax
|
|
// layer's `scale` parameter. The fused softmax bakes the scale into the
|
|
// per-element load before max/exp/sum/divide, removing one full pass over
|
|
// the (often large) [B, H, S, S] attention-logits tensor.
|
|
//
|
|
// Pattern:
|
|
// X -> Mul(X, c) -> Softmax => X -> Softmax(scale=c)
|
|
// X -> Div(X, c) -> Softmax => X -> Softmax(scale=1/c)
|
|
|
|
#include "precomp.hpp"
|
|
#include "net_impl.hpp"
|
|
|
|
namespace cv { namespace dnn {
|
|
CV__DNN_INLINE_NS_BEGIN
|
|
|
|
using std::vector;
|
|
using std::string;
|
|
|
|
struct ModelFusionScaleSoftmax
|
|
{
|
|
explicit ModelFusionScaleSoftmax(Net::Impl* netimpl_) : netimpl(netimpl_) {}
|
|
|
|
bool extractScalar(Arg a, float& out) const
|
|
{
|
|
if (!netimpl->isConstArg(a)) return false;
|
|
Mat t = netimpl->argTensor(a);
|
|
if (t.total() != 1) return false;
|
|
if (t.type() == CV_32F) { out = t.ptr<float>()[0]; return true; }
|
|
if (t.type() == CV_64F) { out = (float)t.ptr<double>()[0]; return true; }
|
|
return false;
|
|
}
|
|
|
|
void fuse() { fuseGraph(netimpl->mainGraph); }
|
|
|
|
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;
|
|
|
|
SoftmaxLayer* sm = dynamic_cast<SoftmaxLayer*>(layer.get());
|
|
if (!sm || sm->logSoftMax) continue;
|
|
if (layer->inputs.size() != 1) continue;
|
|
|
|
Arg sm_in = layer->inputs[0];
|
|
auto it = producer.find(sm_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];
|
|
NaryEltwiseLayer* elt = dynamic_cast<NaryEltwiseLayer*>(pl.get());
|
|
if (!elt) continue;
|
|
const auto op = elt->op;
|
|
const bool is_mul = (op == NaryEltwiseLayer::OPERATION::PROD);
|
|
const bool is_div = (op == NaryEltwiseLayer::OPERATION::DIV);
|
|
if (!is_mul && !is_div) continue;
|
|
if (pl->inputs.size() != 2 || pl->outputs.size() != 1) continue;
|
|
|
|
// Identify which operand is the scalar constant.
|
|
float scalar = 0.f;
|
|
int x_slot = -1;
|
|
if (extractScalar(pl->inputs[1], scalar)) {
|
|
x_slot = 0;
|
|
} else if (is_mul && extractScalar(pl->inputs[0], scalar)) {
|
|
// Mul is commutative; Div with the data on the right doesn't
|
|
// simplify (1 / scale*x ≠ softmax-fold) so only handle Mul here.
|
|
x_slot = 1;
|
|
} else {
|
|
continue;
|
|
}
|
|
|
|
if (is_div) {
|
|
if (scalar == 0.f) continue;
|
|
scalar = 1.f / scalar;
|
|
}
|
|
if (!std::isfinite(scalar)) continue;
|
|
|
|
sm->scale *= scalar;
|
|
// A shared Mul/Div stays until its last consumer has folded it.
|
|
Arg src = pl->inputs[x_slot];
|
|
layer->inputs[0] = src;
|
|
usecounts[src.idx]++;
|
|
if (--usecounts[sm_in.idx] == 0) {
|
|
dropped[prod_idx] = true;
|
|
for (Arg a : pl->inputs)
|
|
if (a.idx > 0)
|
|
usecounts[a.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::fuseScaleSoftmax()
|
|
{
|
|
if (preferableBackend != DNN_BACKEND_OPENCV ||
|
|
preferableTarget != DNN_TARGET_CPU)
|
|
return;
|
|
ModelFusionScaleSoftmax pass(this);
|
|
pass.fuse();
|
|
}
|
|
|
|
CV__DNN_INLINE_NS_END
|
|
}}
|