mirror of
https://github.com/opencv/opencv.git
synced 2026-12-01 13:48:53 -06:00
Merge pull request #26056 from vpisarev:new_dnn_engine
New dnn engine #26056 This is the 1st PR with the new engine; CI is green and PR is ready to be merged, I think. Merge together with https://github.com/opencv/opencv_contrib/pull/3794 --- **Known limitations:** * [solved] OpenVINO is temporarily disabled, but is probably easy to restore (it's not a deal breaker to merge this PR, I guess) * The new engine does not support any backends nor any targets except for the default CPU implementation. But it's possible to choose the old engine when loading a model, then all the functionality is available. * [Caffe patch is here: #26208] The new engine only supports ONNX. When a model is constructed manually or is loaded from a file of different format (.tf, .tflite, .caffe, .darknet), the old engine is used. * Even in the case of ONNX some layers are not supported by the new engine, such as all quantized layers (including DequantizeLinear, QuantizeLinear, QLinearConv etc.), LSTM, GRU, .... It's planned, of course, to have full support for ONNX by OpenCV 5.0 gold release. When a loaded model contains unsupported layers, we switch to the old engine automatically (at ONNX parsing time, not at `forward()` time). * Some layers , e.g. Expat, are only partially supported by the new engine. In the case of unsupported flavours it switches to the old engine automatically (at ONNX parsing time, not at `forward()` time). * 'Concat' graph optimization is disabled. The optimization eliminates Concat layer and instead makes the layers that generate tensors to be concatenated to write the outputs to the final destination. Of course, it's only possible when `axis=0` or `axis=N=1`. The optimization is not compatible with dynamic shapes since we need to know in advance where to store the tensors. Because some of the layer implementations have been modified to become more compatible with the new engine, the feature appears to be broken even when the old engine is used. * Some `dnn::Net` API is not available with the new engine. Also, shape inference may return false if some of the output or intermediate tensors' shapes cannot be inferred without running the model. Probably this can be fixed by a dummy run of the model with zero inputs. * Some overloads of `dnn::Net::getFLOPs()` and `dnn::Net::getMemoryConsumption()` are not exposed any longer in wrapper generators; but the most useful overloads are exposed (and checked by Java tests). * [in progress] A few Einsum tests related to empty shapes have been disabled due to crashes in the tests and in Einsum implementations. The code and the tests need to be repaired. * OpenCL implementation of Deconvolution is disabled. It's very bad and very slow anyway; need to be completely revised. * Deconvolution3D test is now skipped, because it was only supported by CUDA and OpenVINO backends, both of which are not supported by the new engine. * Some tests, such as FastNeuralStyle, checked that the in the case of CUDA backend there is no fallback to CPU. Currently all layers in the new engine are processed on CPU, so there are many fallbacks. The checks, therefore, have been temporarily disabled. --- - [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 - [ ] 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
This commit is contained in:
@@ -80,21 +80,16 @@ class BaseConvolutionLayerImpl : public ConvolutionLayer
|
||||
public:
|
||||
bool fusedWeights, fusedBias;
|
||||
std::vector<double> weightsMultipliers;
|
||||
#ifdef HAVE_WEBNN
|
||||
int groups;
|
||||
#endif
|
||||
|
||||
BaseConvolutionLayerImpl(const LayerParams ¶ms)
|
||||
{
|
||||
setParamsFrom(params);
|
||||
getConvolutionKernelParams(params, kernel_size, pads_begin, pads_end, strides, dilations,
|
||||
padMode, adjust_pads, useWinograd);
|
||||
|
||||
numOutput = params.get<int>("num_output");
|
||||
int ngroups = params.get<int>("group", 1);
|
||||
#ifdef HAVE_WEBNN
|
||||
groups = ngroups;
|
||||
#endif
|
||||
CV_Assert(numOutput % ngroups == 0);
|
||||
numOutput = -1;
|
||||
groups = params.get<int>("group", 1);
|
||||
|
||||
if (kernel_size.size() == 2) {
|
||||
kernel = Size(kernel_size[1], kernel_size[0]);
|
||||
@@ -122,10 +117,11 @@ public:
|
||||
|
||||
CV_Assert((inputs.size() > outputs.size() && blobs.empty()) ||
|
||||
(!inputs.empty() && (blobs.size() == 1 || blobs.size() == 2)));
|
||||
MatSize weightShape = blobs.empty() ? inputs[1].size : blobs[0].size;
|
||||
MatShape weightShape = blobs.empty() ? inputs[1].shape() : blobs[0].shape();
|
||||
numOutput = weightShape[0];
|
||||
|
||||
CV_Assert(inputs[0].dims == outputs[0].dims);
|
||||
if (weightShape.dims() == 3)
|
||||
if (weightShape.dims == 3)
|
||||
{
|
||||
kernel_size.resize(1, kernel_size[0]);
|
||||
strides.resize(1, strides[0]);
|
||||
@@ -133,7 +129,7 @@ public:
|
||||
pads_begin.resize(1, pads_begin[0]);
|
||||
pads_end.resize(1, pads_end[0]);
|
||||
}
|
||||
CV_Assert(weightShape.dims() == kernel_size.size() + 2);
|
||||
CV_Assert(weightShape.dims == kernel_size.size() + 2);
|
||||
for (int i = 0; i < kernel_size.size(); i++) {
|
||||
CV_Assert(weightShape[i + 2] == kernel_size[i]);
|
||||
}
|
||||
@@ -338,7 +334,8 @@ public:
|
||||
if (padMode.empty())
|
||||
{
|
||||
for (int i = 0; i < inpShape.size(); i++)
|
||||
outShape.push_back((inpShape[i] + pads_begin[i] + pads_end[i] - dilations[i] * (kernel_size[i] - 1) - 1) / strides[i] + 1);
|
||||
outShape.push_back((inpShape[i] + pads_begin[i] + pads_end[i] -
|
||||
dilations[i] * (kernel_size[i] - 1) - 1) / strides[i] + 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -351,7 +348,7 @@ public:
|
||||
"be multiple of %d but got %d", weightShape[1], inpCn));
|
||||
CV_Assert(ngroups > 0 && inpCn % ngroups == 0 && outCn % ngroups == 0);
|
||||
|
||||
outputs.resize(1, outShape);
|
||||
outputs.resize(1, MatShape(outShape));
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -1329,13 +1326,11 @@ public:
|
||||
MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE
|
||||
{
|
||||
int dims = inpShape.size();
|
||||
int inpCn = inpShape[1];
|
||||
int inpD = dims == 5 ? inpShape[2] : 1;
|
||||
int inpH = inpShape[dims - 2];
|
||||
int inpW = inpShape.back();
|
||||
int outCn = outShape[1];
|
||||
int ngroups = inpCn / blobs[0].size[0];
|
||||
int outGroupCn = outCn / ngroups;
|
||||
int outGroupCn = outCn / groups;
|
||||
int ksize = outGroupCn * std::accumulate(kernel_size.begin(), kernel_size.end(),
|
||||
1, std::multiplies<size_t>());
|
||||
return shape(ksize, inpD * inpH * inpW);
|
||||
@@ -1372,10 +1367,14 @@ public:
|
||||
std::vector<MatShape> &outputs,
|
||||
std::vector<MatShape> &internals) const CV_OVERRIDE
|
||||
{
|
||||
CV_Assert(!hasBias() || blobs[1].total() == (size_t)numOutput);
|
||||
CV_Assert(inputs.size() != 0);
|
||||
|
||||
int outCn = numOutput;
|
||||
if (outCn < 0) {
|
||||
CV_Assert(inputs.size() > 1 || !blobs.empty());
|
||||
MatShape weightShape = blobs.empty() ? inputs[1] : blobs[0].shape();
|
||||
outCn = weightShape[1]*groups;
|
||||
}
|
||||
std::vector<int> outShape;
|
||||
outShape.push_back(inputs[0][0]); // batch
|
||||
outShape.push_back(outCn);
|
||||
@@ -1398,13 +1397,12 @@ public:
|
||||
CV_Error(Error::StsError, "Unsupported padding mode " + padMode);
|
||||
|
||||
CV_Assert(outCn % blobs[0].size[1] == 0);
|
||||
int ngroups = outCn / blobs[0].size[1];
|
||||
|
||||
int inpCn = inputs[0][1];
|
||||
CV_Assert(inpCn % ngroups == 0 && outCn % ngroups == 0);
|
||||
CV_Assert(inpCn % groups == 0 && outCn % groups == 0);
|
||||
CV_Assert(blobs[0].size[0] == inpCn);
|
||||
|
||||
outputs.resize(1, outShape);
|
||||
outputs.resize(1, MatShape(outShape));
|
||||
|
||||
if (!is1x1())
|
||||
internals.push_back(computeColRowShape(inputs[0], outputs[0]));
|
||||
@@ -1412,6 +1410,17 @@ public:
|
||||
return false;
|
||||
}
|
||||
|
||||
void getTypes(const std::vector<MatType> &inputs,
|
||||
const int requiredOutputs,
|
||||
const int requiredInternals,
|
||||
std::vector<MatType> &outputs,
|
||||
std::vector<MatType> &internals) const CV_OVERRIDE
|
||||
{
|
||||
CV_Assert(inputs.size() > 0);
|
||||
outputs.assign(requiredOutputs, inputs[0]);
|
||||
internals.assign(requiredInternals, CV_32F);
|
||||
}
|
||||
|
||||
void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
|
||||
{
|
||||
BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);
|
||||
@@ -1420,6 +1429,11 @@ public:
|
||||
inputs_arr.getMatVector(inputs);
|
||||
outputs_arr.getMatVector(outputs);
|
||||
|
||||
CV_Assert(inputs.size() > 1 || !blobs.empty());
|
||||
|
||||
MatShape weightShape = blobs.empty() ? inputs[1].shape() : blobs[0].shape();
|
||||
numOutput = weightShape[1]*groups;
|
||||
|
||||
std::vector<int> inpShape;
|
||||
std::vector<int> outShape;
|
||||
for (int i = 2; i < inputs[0].dims; i++) {
|
||||
@@ -1436,11 +1450,13 @@ public:
|
||||
}
|
||||
|
||||
weightsMultipliers.assign(numOutput, 1.0);
|
||||
if (weightsMat.empty())
|
||||
{
|
||||
|
||||
if (weightsMat.empty() && !blobs.empty()) {
|
||||
transpose(blobs[0].reshape(1, blobs[0].size[0]), weightsMat);
|
||||
biasesMat = hasBias() ? blobs[1].reshape(1, numOutput)
|
||||
: Mat::zeros(numOutput, 1, CV_32F);
|
||||
}
|
||||
|
||||
if (biasesMat.empty() && blobs.size() >= 2) {
|
||||
biasesMat = blobs[1].reshape(1, numOutput);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1754,33 +1770,40 @@ public:
|
||||
if (is1x1())
|
||||
return false;
|
||||
|
||||
if (umat_weights.empty())
|
||||
{
|
||||
if (umat_weights.empty() || inputs.size() >= 2) {
|
||||
Mat temp;
|
||||
if (fusedWeights)
|
||||
weightsMat.copyTo(umat_weights);
|
||||
else
|
||||
transpose(blobs[0].reshape(1, inpCn), umat_weights);
|
||||
else if (!blobs.empty()) {
|
||||
transpose(blobs[0].reshape(1, inpCn), temp);
|
||||
temp.copyTo(umat_weights);
|
||||
}
|
||||
else {
|
||||
transpose(inputs[1].reshape(1, inpCn), temp);
|
||||
temp.copyTo(umat_weights);
|
||||
}
|
||||
}
|
||||
|
||||
if (umat_biases.empty() || inputs.size() >= 3) {
|
||||
if (fusedBias)
|
||||
biasesMat.copyTo(umat_biases);
|
||||
else if (blobs.size() > 1)
|
||||
blobs[1].reshape(1, outCn).copyTo(umat_biases);
|
||||
else if (inputs.size() >= 3)
|
||||
inputs[2].reshape(1, outCn).copyTo(umat_biases);
|
||||
else
|
||||
{
|
||||
if (hasBias())
|
||||
blobs[1].reshape(1, outCn).copyTo(umat_biases);
|
||||
else
|
||||
umat_biases = UMat::zeros(outCn, 1, CV_32F);
|
||||
}
|
||||
umat_biases = UMat::zeros(outCn, 1, CV_32F);
|
||||
}
|
||||
|
||||
String buildopt = format("-DT=%s ", ocl::typeToStr(inputs[0].type()));
|
||||
buildopt += format("-DPAD_H=%d -DPAD_W=%d -DKERNEL_H=%d -DKERNEL_W=%d -DSTRIDE_H=%d -DSTRIDE_W=%d ",
|
||||
pad.height, pad.width, kernel.height, kernel.width, stride.height, stride.width);
|
||||
|
||||
for (size_t ii = 0; ii < outputs.size(); ii++)
|
||||
//for (size_t ii = 0; ii < outputs.size(); ii++)
|
||||
{
|
||||
int ngroups = outCn / blobs[0].size[1];
|
||||
int inpGroupCn = inpCn / ngroups;
|
||||
int outGroupCn = blobs[0].size[1];
|
||||
int ii = 0;
|
||||
int inpGroupCn = inpCn / groups;
|
||||
int outGroupCn = outCn / groups;
|
||||
const UMat& inp = inputs[ii];
|
||||
UMat& out = outputs[ii];
|
||||
int numImg = inp.size[0];
|
||||
@@ -1789,21 +1812,21 @@ public:
|
||||
|
||||
MatShape inpshape = shape(numImg*inpCn, inpH*inpW);
|
||||
MatShape outshape = shape(numImg*outCn, outH*outW);
|
||||
UMat convBlob = inputs[ii].reshape(1, inpshape.size(), &inpshape[0]);
|
||||
UMat decnBlob = out.reshape(1, outshape.size(), &outshape[0]);
|
||||
int rows = internals[0].rows / ngroups;
|
||||
UMat convBlob = inputs[ii].reshape(1, inpshape);
|
||||
UMat decnBlob = out.reshape(1, outshape);
|
||||
int rows = internals[0].rows / groups;
|
||||
|
||||
for (int n = 0; n < numImg; n++)
|
||||
{
|
||||
for (int g = 0; g < ngroups; g++)
|
||||
for (int g = 0; g < groups; g++)
|
||||
{
|
||||
UMat colMat = internals[0].rowRange(_Range(g * rows, rows));
|
||||
UMat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));
|
||||
UMat convMat = convBlob.rowRange(_Range((g + n * groups) * inpGroupCn, inpGroupCn));
|
||||
UMat wghtMat = umat_weights.colRange(_Range(g * inpGroupCn, inpGroupCn));
|
||||
gemm(wghtMat, convMat, 1, noArray(), 0, colMat, 0);
|
||||
}
|
||||
|
||||
for (int g = 0; g < ngroups; g++)
|
||||
for (int g = 0; g < groups; g++)
|
||||
{
|
||||
int total = outGroupCn * decnBlob.cols;
|
||||
int index = 0;
|
||||
@@ -1826,7 +1849,7 @@ public:
|
||||
k.set(index++, ocl::KernelArg::PtrReadOnly(umat_biases));
|
||||
k.set(index++, (int)(g * outGroupCn * umat_biases.cols));
|
||||
k.set(index++, ocl::KernelArg::PtrWriteOnly(decnBlob));
|
||||
k.set(index++, (int)((g + n * ngroups) * outGroupCn * decnBlob.cols));
|
||||
k.set(index++, (int)((g + n * groups) * outGroupCn * decnBlob.cols));
|
||||
|
||||
size_t global[] = { (size_t)total };
|
||||
bool ret = k.run(1, global, NULL, false);
|
||||
@@ -1845,38 +1868,67 @@ public:
|
||||
CV_TRACE_FUNCTION();
|
||||
CV_TRACE_ARG_VALUE(name, "name", name.c_str());
|
||||
|
||||
CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
|
||||
forward_ocl(inputs_arr, outputs_arr, internals_arr));
|
||||
// For some reason, tests for deconvolution fail;
|
||||
// Also, the current implementation is super-inefficient,
|
||||
// Just disabled it. Need to rewrite it and then uncomment back these lines
|
||||
//CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
|
||||
// forward_ocl(inputs_arr, outputs_arr, internals_arr));
|
||||
|
||||
if (inputs_arr.depth() == CV_16F)
|
||||
if (inputs_arr.depth(0) == CV_16F)
|
||||
{
|
||||
forward_fallback(inputs_arr, outputs_arr, internals_arr);
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<Mat> inputs, outputs, internals;
|
||||
auto kind = outputs_arr.kind();
|
||||
std::vector<Mat> inputs, internals;
|
||||
inputs_arr.getMatVector(inputs);
|
||||
outputs_arr.getMatVector(outputs);
|
||||
internals_arr.getMatVector(internals);
|
||||
|
||||
int outCn = numOutput;
|
||||
int inpCn = inputs[0].size[1];
|
||||
bool is1x1flag = is1x1();
|
||||
int nstripes = getNumThreads();
|
||||
/*CV_Assert(outputs.size() == 1);
|
||||
CV_Assert(inputs[0].size[0] == outputs[0].size[0]);
|
||||
CV_Assert(outCn == outputs[0].size[1]);*/
|
||||
|
||||
if( weightsMat.empty() )
|
||||
{
|
||||
transpose(blobs[0].reshape(1, inpCn), weightsMat);
|
||||
biasesMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat::zeros(outCn, 1, CV_32F);
|
||||
if (weightsMat.empty() || inputs.size() >= 2) {
|
||||
Mat inpWeights = !blobs.empty() ? blobs[0] : inputs[1];
|
||||
transpose(inpWeights.reshape(1, inpCn), weightsMat);
|
||||
}
|
||||
|
||||
for (size_t ii = 0; ii < outputs.size(); ii++)
|
||||
if (biasesMat.empty() || inputs.size() >= 3) {
|
||||
Mat inpBias = blobs.size() >= 2 ? blobs[1] : inputs.size() >= 3 ? inputs[2] : Mat();
|
||||
Mat biasesMat_ = !inpBias.empty() ? inpBias.reshape(1, outCn) : Mat::zeros(outCn, 1, CV_32F);
|
||||
biasesMat_.copyTo(biasesMat);
|
||||
}
|
||||
|
||||
/*printf("DeConvolution Input: ");
|
||||
pprint(std::cout, inputs[0], 0, 3, 100, '[');
|
||||
printf("\nDeConvolution Weights: ");
|
||||
pprint(std::cout, weightsMat, 0, 3, 100, '[');
|
||||
printf("\nDeConvolution Bias: ");
|
||||
pprint(std::cout, biasesMat, 0, 3, 100, '[');
|
||||
printf("\n");*/
|
||||
|
||||
//for (size_t ii = 0; ii < outputs.size(); ii++)
|
||||
{
|
||||
int ngroups = outCn / blobs[0].size[1];
|
||||
int inpGroupCn = inpCn / ngroups;
|
||||
int outGroupCn = blobs[0].size[1];
|
||||
int ii = 0;
|
||||
int inpGroupCn = inpCn / groups;
|
||||
int outGroupCn = outCn / groups;
|
||||
const Mat& inp = inputs[ii];
|
||||
Mat& out = outputs[ii];
|
||||
MatShape outshape = outputs_arr.shape(0);
|
||||
CV_Assert(outshape.dims == inp.dims);
|
||||
CV_Assert(outshape[0] == inp.size[0]);
|
||||
CV_Assert(outshape[1] == outCn);
|
||||
Mat out;
|
||||
if (kind == _InputArray::STD_VECTOR_MAT) {
|
||||
out = outputs_arr.getMat(0);
|
||||
}
|
||||
else {
|
||||
out.create(outshape, inp.type());
|
||||
}
|
||||
int numImg = inp.size[0];
|
||||
int inpH = inp.size[2], inpW = inp.size[3];
|
||||
int outH = out.size[2], outW = out.size[3];
|
||||
@@ -1886,12 +1938,12 @@ public:
|
||||
|
||||
for (int n = 0; n < numImg; n++)
|
||||
{
|
||||
for (int g = 0; g < ngroups; g++)
|
||||
for (int g = 0; g < groups; g++)
|
||||
{
|
||||
Mat dstMat = decnBlob.rowRange(_Range((g + n * ngroups) * outGroupCn, outGroupCn));
|
||||
Mat dstMat = decnBlob.rowRange(_Range((g + n * groups) * outGroupCn, outGroupCn));
|
||||
Mat &colMat = is1x1flag ? dstMat : internals[0];
|
||||
|
||||
Mat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));
|
||||
Mat convMat = convBlob.rowRange(_Range((g + n * groups) * inpGroupCn, inpGroupCn));
|
||||
Mat wghtMat = weightsMat.colRange(_Range(g * inpGroupCn, inpGroupCn));
|
||||
Mat curBiasMat = biasesMat.rowRange(_Range(g * outGroupCn, outGroupCn));
|
||||
|
||||
@@ -1905,6 +1957,10 @@ public:
|
||||
curBiasMat.ptr<float>(), is1x1flag);
|
||||
}
|
||||
}
|
||||
if (kind == _InputArray::STD_VECTOR_UMAT) {
|
||||
std::vector<UMat>& u_outputs = outputs_arr.getUMatVecRef();
|
||||
out.copyTo(u_outputs[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user