dnn.cpp 232.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
#include "op_halide.hpp"
44
#include "op_inf_engine.hpp"
45
#include "ie_ngraph.hpp"
46
#include "op_vkcom.hpp"
47
#include "op_cuda.hpp"
48
#include "op_webnn.hpp"
49

50
#ifdef HAVE_CUDA
51 52
#include "cuda4dnn/init.hpp"
#include "cuda4dnn/primitives/eltwise.hpp" // required by fuseLayers
53 54
#endif

55
#include "halide_scheduler.hpp"
56

57 58 59 60
#include <set>
#include <algorithm>
#include <iostream>
#include <sstream>
61
#include <fstream>
62
#include <iterator>
63
#include <numeric>
64
#include <memory>
65 66
#include <opencv2/dnn/shape_utils.hpp>
#include <opencv2/imgproc.hpp>
67
#include <opencv2/dnn/layer_reg.private.hpp>
68

69
#include <opencv2/core/utils/configuration.private.hpp>
70
#include <opencv2/core/utils/logger.hpp>
71

72 73
namespace cv {
namespace dnn {
74
CV__DNN_INLINE_NS_BEGIN
75

76 77
static size_t DNN_NETWORK_DUMP = utils::getConfigurationParameterSizeT("OPENCV_DNN_NETWORK_DUMP", 0);

L
luz.paz 已提交
78
// this option is useful to run valgrind memory errors detection
79 80
static bool DNN_DISABLE_MEMORY_OPTIMIZATIONS = utils::getConfigurationParameterBool("OPENCV_DNN_DISABLE_MEMORY_OPTIMIZATIONS", false);

A
Alexander Alekhin 已提交
81
#ifdef HAVE_OPENCL
82
static bool DNN_OPENCL_ALLOW_ALL_DEVICES = utils::getConfigurationParameterBool("OPENCV_DNN_OPENCL_ALLOW_ALL_DEVICES", false);
A
Alexander Alekhin 已提交
83
#endif
84

85 86 87 88 89 90 91 92
static int PARAM_DNN_BACKEND_DEFAULT = (int)utils::getConfigurationParameterSizeT("OPENCV_DNN_BACKEND_DEFAULT",
#ifdef HAVE_INF_ENGINE
    (size_t)DNN_BACKEND_INFERENCE_ENGINE
#else
    (size_t)DNN_BACKEND_OPENCV
#endif
);

93 94 95 96
// Additional checks (slowdowns execution!)
static bool DNN_CHECK_NAN_INF = utils::getConfigurationParameterBool("OPENCV_DNN_CHECK_NAN_INF", false);
static bool DNN_CHECK_NAN_INF_DUMP = utils::getConfigurationParameterBool("OPENCV_DNN_CHECK_NAN_INF_DUMP", false);
static bool DNN_CHECK_NAN_INF_RAISE_ERROR = utils::getConfigurationParameterBool("OPENCV_DNN_CHECK_NAN_INF_RAISE_ERROR", false);
97

98 99 100 101
using std::vector;
using std::map;
using std::make_pair;
using std::set;
102
using std::string;
103

104 105 106 107 108 109 110 111 112 113 114 115
//==================================================================================================

class BackendRegistry
{
public:
    typedef std::vector< std::pair<Backend, Target> > BackendsList;
    const BackendsList & getBackends() const { return backends; }
    static BackendRegistry & getRegistry()
    {
        static BackendRegistry impl;
        return impl;
    }
116

117 118
#ifdef HAVE_INF_ENGINE
    static inline bool checkIETarget(Target target)
119
    {
120
#if INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2019R3)
121
        // Lightweight detection
122
        const std::vector<std::string> devices = getCore("").GetAvailableDevices();
123 124 125 126
        for (std::vector<std::string>::const_iterator i = devices.begin(); i != devices.end(); ++i)
        {
            if (std::string::npos != i->find("MYRIAD") && target == DNN_TARGET_MYRIAD)
                return true;
127 128
            if (std::string::npos != i->find("HDDL") && target == DNN_TARGET_HDDL)
                return true;
129 130 131 132 133 134 135 136 137
            else if (std::string::npos != i->find("FPGA") && target == DNN_TARGET_FPGA)
                return true;
            else if (std::string::npos != i->find("CPU") && target == DNN_TARGET_CPU)
                return true;
            else if (std::string::npos != i->find("GPU") && (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16))
                return true;
        }
        return false;
#else
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
        cv::dnn::Net net;
        cv::dnn::LayerParams lp;
        lp.set("kernel_size", 1);
        lp.set("num_output", 1);
        lp.set("bias_term", false);
        lp.type = "Convolution";
        lp.name = "testLayer";
        lp.blobs.push_back(Mat({1, 2, 1, 1}, CV_32F, Scalar(1)));
        net.addLayerToPrev(lp.name, lp.type, lp);
        net.setPreferableBackend(cv::dnn::DNN_BACKEND_INFERENCE_ENGINE);
        net.setPreferableTarget(target);
        static int inpDims[] = {1, 2, 3, 4};
        net.setInput(cv::Mat(4, &inpDims[0], CV_32FC1, cv::Scalar(0)));
        try
        {
            net.forward();
        }
155
        catch(const std::exception& e)
156
        {
157
            CV_LOG_INFO(NULL, "checkIETarget(" << (int)target << ") has failed with message: " << e.what());
158 159 160
            return false;
        }
        return true;
161
#endif
162
    }
163
#endif
164

165 166 167 168 169 170 171 172 173 174 175 176
private:
    BackendRegistry()
    {
#ifdef HAVE_HALIDE
        backends.push_back(std::make_pair(DNN_BACKEND_HALIDE, DNN_TARGET_CPU));
#  ifdef HAVE_OPENCL
        if (cv::ocl::useOpenCL())
            backends.push_back(std::make_pair(DNN_BACKEND_HALIDE, DNN_TARGET_OPENCL));
#  endif
#endif // HAVE_HALIDE

#ifdef HAVE_INF_ENGINE
177
        if (checkIETarget(DNN_TARGET_CPU)) {
178
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
179
            backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, DNN_TARGET_CPU));
180
#endif
181 182 183 184 185
#ifdef HAVE_DNN_NGRAPH
            backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, DNN_TARGET_CPU));
#endif
        }
        if (checkIETarget(DNN_TARGET_MYRIAD)) {
186
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
187
            backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, DNN_TARGET_MYRIAD));
188
#endif
189 190
#ifdef HAVE_DNN_NGRAPH
            backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, DNN_TARGET_MYRIAD));
191 192 193 194 195 196 197 198
#endif
        }
        if (checkIETarget(DNN_TARGET_HDDL)) {
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
            backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, DNN_TARGET_HDDL));
#endif
#ifdef HAVE_DNN_NGRAPH
            backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, DNN_TARGET_HDDL));
199 200
#endif
        }
201
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
202
        if (checkIETarget(DNN_TARGET_FPGA))
203
            backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, DNN_TARGET_FPGA));
204
#endif
205
#ifdef HAVE_OPENCL
206 207
        if (cv::ocl::useOpenCL() && ocl::Device::getDefault().isIntel())
        {
208
            if (checkIETarget(DNN_TARGET_OPENCL)) {
209
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
210
                backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, DNN_TARGET_OPENCL));
211
#endif
212 213 214 215 216
#ifdef HAVE_DNN_NGRAPH
                backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, DNN_TARGET_OPENCL));
#endif
            }
            if (checkIETarget(DNN_TARGET_OPENCL_FP16)) {
217
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
218
                backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, DNN_TARGET_OPENCL_FP16));
219
#endif
220 221 222 223
#ifdef HAVE_DNN_NGRAPH
                backends.push_back(std::make_pair(DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, DNN_TARGET_OPENCL_FP16));
#endif
            }
224
        }
225
#endif
226 227
#endif // HAVE_INF_ENGINE

228 229 230 231 232 233 234
#ifdef HAVE_WEBNN
        if (haveWebnn())
        {
            backends.push_back(std::make_pair(DNN_BACKEND_WEBNN, DNN_TARGET_CPU));
        }
#endif // HAVE_WEBNN

235 236 237 238 239 240 241 242 243
#ifdef HAVE_OPENCL
        if (cv::ocl::useOpenCL())
        {
            backends.push_back(std::make_pair(DNN_BACKEND_OPENCV, DNN_TARGET_OPENCL));
            backends.push_back(std::make_pair(DNN_BACKEND_OPENCV, DNN_TARGET_OPENCL_FP16));
        }
#endif

        backends.push_back(std::make_pair(DNN_BACKEND_OPENCV, DNN_TARGET_CPU));
244 245

#ifdef HAVE_VULKAN
246 247
        if (haveVulkan())
            backends.push_back(std::make_pair(DNN_BACKEND_VKCOM, DNN_TARGET_VULKAN));
248
#endif
249 250

#ifdef HAVE_CUDA
Y
YashasSamaga 已提交
251
        if (haveCUDA())
252
        {
253
            backends.push_back(std::make_pair(DNN_BACKEND_CUDA, DNN_TARGET_CUDA));
Y
YashasSamaga 已提交
254
            backends.push_back(std::make_pair(DNN_BACKEND_CUDA, DNN_TARGET_CUDA_FP16));
255 256
        }
#endif
257 258 259 260 261 262 263 264 265 266 267 268 269
    }

    BackendsList backends;
};


std::vector< std::pair<Backend, Target> > getAvailableBackends()
{
    return BackendRegistry::getRegistry().getBackends();
}

std::vector<Target> getAvailableTargets(Backend be)
{
270 271
    if (be == DNN_BACKEND_DEFAULT)
        be = (Backend)PARAM_DNN_BACKEND_DEFAULT;
272 273 274 275
#ifdef HAVE_INF_ENGINE
    if (be == DNN_BACKEND_INFERENCE_ENGINE)
        be = getInferenceEngineBackendTypeParam();
#endif
276

277 278 279 280 281 282 283 284 285 286 287 288
    std::vector<Target> result;
    const BackendRegistry::BackendsList all_backends = getAvailableBackends();
    for(BackendRegistry::BackendsList::const_iterator i = all_backends.begin(); i != all_backends.end(); ++i )
    {
        if (i->first == be)
            result.push_back(i->second);
    }
    return result;
}

//==================================================================================================

289 290 291 292 293 294 295 296 297 298 299 300 301 302
namespace
{
    struct LayerShapes
    {
        ShapesVec in, out, internal;
        // No guarantees that layer which support in-place computations
        // will be computed in-place (input.data_ptr == output.data_ptr).
        // If layer said that it could work in-place and layers after it
        // no longer use input blob, we'll set output = input.
        bool supportInPlace;
        LayerShapes() {supportInPlace = false;}
    };
}

303
Mat blobFromImage(InputArray image, double scalefactor, const Size& size,
304
                  const Scalar& mean, bool swapRB, bool crop, int ddepth)
305
{
306 307
    CV_TRACE_FUNCTION();
    Mat blob;
308
    blobFromImage(image, blob, scalefactor, size, mean, swapRB, crop, ddepth);
309
    return blob;
310 311
}

312
void blobFromImage(InputArray image, OutputArray blob, double scalefactor,
313
                   const Size& size, const Scalar& mean, bool swapRB, bool crop, int ddepth)
314
{
A
Alexander Alekhin 已提交
315
    CV_TRACE_FUNCTION();
316
    std::vector<Mat> images(1, image.getMat());
317
    blobFromImages(images, blob, scalefactor, size, mean, swapRB, crop, ddepth);
318 319
}

320
Mat blobFromImages(InputArrayOfArrays images, double scalefactor, Size size,
321
                   const Scalar& mean, bool swapRB, bool crop, int ddepth)
322
{
A
Alexander Alekhin 已提交
323
    CV_TRACE_FUNCTION();
324
    Mat blob;
325
    blobFromImages(images, blob, scalefactor, size, mean, swapRB, crop, ddepth);
326 327 328 329
    return blob;
}

void blobFromImages(InputArrayOfArrays images_, OutputArray blob_, double scalefactor,
330
                    Size size, const Scalar& mean_, bool swapRB, bool crop, int ddepth)
331 332
{
    CV_TRACE_FUNCTION();
333 334 335 336
    CV_CheckType(ddepth, ddepth == CV_32F || ddepth == CV_8U, "Blob depth should be CV_32F or CV_8U");
    if (ddepth == CV_8U)
    {
        CV_CheckEQ(scalefactor, 1.0, "Scaling is not supported for CV_8U blob depth");
337
        CV_Assert(mean_ == Scalar() && "Mean subtraction is not supported for CV_8U blob depth");
338 339
    }

340 341 342
    std::vector<Mat> images;
    images_.getMatVector(images);
    CV_Assert(!images.empty());
343
    for (size_t i = 0; i < images.size(); i++)
344 345 346 347 348 349
    {
        Size imgSize = images[i].size();
        if (size == Size())
            size = imgSize;
        if (size != imgSize)
        {
350 351 352 353
            if(crop)
            {
              float resizeFactor = std::max(size.width / (float)imgSize.width,
                                            size.height / (float)imgSize.height);
354
              resize(images[i], images[i], Size(), resizeFactor, resizeFactor, INTER_LINEAR);
355 356 357 358 359 360
              Rect crop(Point(0.5 * (images[i].cols - size.width),
                              0.5 * (images[i].rows - size.height)),
                        size);
              images[i] = images[i](crop);
            }
            else
361
              resize(images[i], images[i], size, 0, 0, INTER_LINEAR);
362
        }
363
        if(images[i].depth() == CV_8U && ddepth == CV_32F)
364 365 366 367 368 369 370 371 372
            images[i].convertTo(images[i], CV_32F);
        Scalar mean = mean_;
        if (swapRB)
            std::swap(mean[0], mean[2]);

        images[i] -= mean;
        images[i] *= scalefactor;
    }

373
    size_t nimages = images.size();
374 375 376 377 378
    Mat image0 = images[0];
    int nch = image0.channels();
    CV_Assert(image0.dims == 2);
    if (nch == 3 || nch == 4)
    {
379
        int sz[] = { (int)nimages, nch, image0.rows, image0.cols };
380
        blob_.create(4, sz, ddepth);
381
        Mat blob = blob_.getMat();
382 383
        Mat ch[4];

384
        for(size_t i = 0; i < nimages; i++ )
385
        {
386
            const Mat& image = images[i];
387
            CV_Assert(image.depth() == blob_.depth());
388 389 390 391
            nch = image.channels();
            CV_Assert(image.dims == 2 && (nch == 3 || nch == 4));
            CV_Assert(image.size() == image0.size());

392
            for( int j = 0; j < nch; j++ )
393
                ch[j] = Mat(image.rows, image.cols, ddepth, blob.ptr((int)i, j));
394 395 396 397 398 399 400 401 402
            if(swapRB)
                std::swap(ch[0], ch[2]);
            split(image, ch);
        }
    }
    else
    {
       CV_Assert(nch == 1);
       int sz[] = { (int)nimages, 1, image0.rows, image0.cols };
403
       blob_.create(4, sz, ddepth);
404
       Mat blob = blob_.getMat();
405

406
       for(size_t i = 0; i < nimages; i++ )
407
       {
408
           const Mat& image = images[i];
409
           CV_Assert(image.depth() == blob_.depth());
410 411 412 413
           nch = image.channels();
           CV_Assert(image.dims == 2 && (nch == 1));
           CV_Assert(image.size() == image0.size());

414
           image.copyTo(Mat(image.rows, image.cols, ddepth, blob.ptr((int)i, 0)));
415 416 417 418
       }
    }
}

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_)
{
    CV_TRACE_FUNCTION();

    //A blob is a 4 dimensional matrix in floating point precision
    //blob_[0] = batchSize = nbOfImages
    //blob_[1] = nbOfChannels
    //blob_[2] = height
    //blob_[3] = width
    CV_Assert(blob_.depth() == CV_32F);
    CV_Assert(blob_.dims == 4);

    images_.create(cv::Size(1, blob_.size[0]), blob_.depth());

    std::vector<Mat> vectorOfChannels(blob_.size[1]);
    for (int n = 0; n <  blob_.size[0]; ++n)
    {
        for (int c = 0; c < blob_.size[1]; ++c)
        {
            vectorOfChannels[c] = getPlane(blob_, n, c);
        }
        cv::merge(vectorOfChannels, images_.getMatRef(n));
    }
}

444
#ifdef HAVE_OPENCL
445 446 447
class OpenCLBackendWrapper : public BackendWrapper
{
public:
448
    OpenCLBackendWrapper(Mat& m) : BackendWrapper(DNN_BACKEND_OPENCV, DNN_TARGET_OPENCL)
449 450 451 452 453 454 455
    {
        m.copyTo(umat);
        host = &m;
        hostDirty = false;
    }

    OpenCLBackendWrapper(const Ptr<BackendWrapper>& baseBuffer, Mat& m)
456
        : BackendWrapper(DNN_BACKEND_OPENCV, DNN_TARGET_OPENCL)
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    {
        Ptr<OpenCLBackendWrapper> base = baseBuffer.dynamicCast<OpenCLBackendWrapper>();
        CV_Assert(!base.empty());

        host = &m;

        int shape[] = {1, (int)base->umat.total()};
        umat = base->umat.reshape(1, 2, &shape[0])
                         .colRange(0, host->total())
                         .reshape(1, host->dims, &host->size[0]);
        hostDirty = false;
    }

    static Ptr<BackendWrapper> create(Mat& m)
    {
        return Ptr<BackendWrapper>(new OpenCLBackendWrapper(m));
    }

    static Ptr<BackendWrapper> create(const Ptr<BackendWrapper>& baseBuffer, Mat& m)
    {
        return Ptr<BackendWrapper>(new OpenCLBackendWrapper(baseBuffer, m));
    }

    static std::vector<UMat> getUMatVector(const std::vector<Ptr<BackendWrapper> >& wrappers)
    {
        const int numWrappers = wrappers.size();
        std::vector<UMat> mats(wrappers.size());
        for (int i = 0; i < numWrappers; ++i)
        {
            Ptr<OpenCLBackendWrapper> umatWrapper = wrappers[i].dynamicCast<OpenCLBackendWrapper>();
            CV_Assert(!umatWrapper.empty());
            umatWrapper->copyToDevice();
            mats[i] = umatWrapper->umat;
        }
        return mats;
    }

    // Replaces all umats in wrappers to specific ones.
    static void update(const std::vector<Ptr<BackendWrapper> >& wrappers,
                       const std::vector<UMat>& umats)
    {
        CV_Assert(wrappers.size() == umats.size());
        for (int i = 0, n = umats.size(); i < n; ++i)
        {
            Ptr<OpenCLBackendWrapper> umatWrapper = wrappers[i].dynamicCast<OpenCLBackendWrapper>();
            CV_Assert(!umatWrapper.empty());
            umatWrapper->umat = umats[i];
        }
    }

    ~OpenCLBackendWrapper() {}

    // Copies data from device to a host memory.
510
    virtual void copyToHost() CV_OVERRIDE
511 512 513 514
    {
        umat.copyTo(*host);
    }

515
    virtual void setHostDirty() CV_OVERRIDE
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    {
        hostDirty = true;
    };

    void copyToDevice()
    {
        if (hostDirty)
        {
            host->copyTo(umat);
            hostDirty = false;
        }
    }

private:
    UMat umat;
    Mat* host;
    bool hostDirty;
};
534
#endif
535

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
struct LayerPin
{
    int lid;
    int oid;

    LayerPin(int layerId = -1, int outputId = -1)
        : lid(layerId), oid(outputId) {}

    bool valid() const
    {
        return (lid >= 0 && oid >= 0);
    }

    bool equal(const LayerPin &r) const
    {
        return (lid == r.lid && oid == r.oid);
    }

    bool operator<(const LayerPin &r) const
    {
556
        return lid < r.lid || (lid == r.lid && oid < r.oid);
557 558 559 560 561 562 563 564 565 566
    }

    bool operator ==(const LayerPin &r) const
    {
        return lid == r.lid && oid == r.oid;
    }
};

struct LayerData
{
567 568 569
    LayerData() : id(-1), dtype(CV_32F), skip(false), flag(0) {}
    LayerData(int _id, const String &_name, const String &_type, const int &_dtype, LayerParams &_params)
        : id(_id), name(_name), type(_type), dtype(_dtype), params(_params), skip(false), flag(0)
570
    {
A
Alexander Alekhin 已提交
571 572
        CV_TRACE_FUNCTION();

573 574 575 576 577 578 579 580
        //add logging info
        params.name = name;
        params.type = type;
    }

    int id;
    String name;
    String type;
581
    int dtype; // Datatype of output blobs.
582 583 584 585 586 587
    LayerParams params;

    std::vector<LayerPin> inputBlobsId;
    std::set<int> inputLayersId;
    std::set<int> requiredOutputs;
    std::vector<LayerPin> consumers;
588 589
    std::vector<Ptr<BackendWrapper> > outputBlobsWrappers;
    std::vector<Ptr<BackendWrapper> > inputBlobsWrappers;
590
    std::vector<Ptr<BackendWrapper> > internalBlobsWrappers;
591

592 593 594 595 596 597 598
#ifdef HAVE_CUDA
    /* output ids which must be transferred to the host in the background
     * after the completion of the forward pass of the layer
     */
    std::vector<int> cudaD2HBackgroundTransfers;
#endif

599 600 601 602 603 604 605
    Ptr<Layer> layerInstance;
    std::vector<Mat> outputBlobs;
    std::vector<Mat*> inputBlobs;
    std::vector<Mat> internals;
    // Computation nodes of implemented backends (except DEFAULT).
    std::map<int, Ptr<BackendNode> > backendNodes;
    // Flag for skip layer computation for specific backend.
606
    bool skip;
607 608 609 610 611

    int flag;

    Ptr<Layer> getLayerInstance()
    {
A
Alexander Alekhin 已提交
612 613 614
        CV_TRACE_FUNCTION();
        CV_TRACE_ARG_VALUE(type, "type", type.c_str());

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
        if (layerInstance)
            return layerInstance;

        layerInstance = LayerFactory::createLayerInstance(type, params);
        if (!layerInstance)
        {
            CV_Error(Error::StsError, "Can't create layer \"" + name + "\" of type \"" + type + "\"");
        }

        return layerInstance;
    }
};

//fake layer containing network input blobs
struct DataLayer : public Layer
{
631 632 633 634 635 636 637 638
    DataLayer() : Layer()
    {
        skip = false;
    }

    virtual bool supportBackend(int backendId) CV_OVERRIDE
    {
        return backendId == DNN_BACKEND_OPENCV ||
639
               (backendId == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 && inputsData.size() == 1);
640
    }
641

642
    void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
643 644 645 646
    {
        CV_TRACE_FUNCTION();
        CV_TRACE_ARG_VALUE(name, "name", name.c_str());

647
        // FIXIT: add wrapper without exception suppression
648
        CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
649
                   forward_ocl(inputs_arr, outputs_arr, internals_arr))
650

651
        bool isFP16 = outputs_arr.depth() == CV_16S;
652 653 654 655

        std::vector<Mat> outputs, internals;
        outputs_arr.getMatVector(outputs);
        internals_arr.getMatVector(internals);
656 657 658

        for (int i = 0; i < inputsData.size(); ++i)
        {
659 660
            double scale = scaleFactors[i];
            Scalar& mean = means[i];
661

662
            CV_Assert(mean == Scalar() || inputsData[i].size[1] <= 4);
663 664 665 666
            if (isFP16)
                CV_CheckTypeEQ(outputs[i].type(), CV_16SC1, "");
            else
                CV_CheckTypeEQ(outputs[i].type(), CV_32FC1, "");
667 668 669 670 671 672 673 674 675

            bool singleMean = true;
            for (int j = 1; j < std::min(4, inputsData[i].size[1]) && singleMean; ++j)
            {
                singleMean = mean[j] == mean[j - 1];
            }

            if (singleMean)
            {
676 677 678 679 680 681 682 683 684 685
                if (isFP16)
                {
                    Mat input_f32;
                    inputsData[i].convertTo(input_f32, CV_32F, scale, -mean[0] * scale);
                    convertFp16(input_f32, outputs[i]);
                }
                else
                {
                    inputsData[i].convertTo(outputs[i], CV_32F, scale, -mean[0] * scale);
                }
686 687
            }
            else
688
            {
689
                for (int n = 0; n < inputsData[i].size[0]; ++n)
690
                {
691 692 693 694
                    for (int c = 0; c < inputsData[i].size[1]; ++c)
                    {
                        Mat inp = getPlane(inputsData[i], n, c);
                        Mat out = getPlane(outputs[i], n, c);
695 696 697 698 699 700 701 702 703 704
                        if (isFP16)
                        {
                            Mat input_f32;
                            inp.convertTo(input_f32, CV_32F, scale, -mean[c] * scale);
                            convertFp16(input_f32, out);
                        }
                        else
                        {
                            inp.convertTo(out, CV_32F, scale, -mean[c] * scale);
                        }
705
                    }
706
                }
707 708 709 710 711 712 713
            }
        }
    }

#ifdef HAVE_OPENCL
    bool forward_ocl(InputArrayOfArrays, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
    {
714 715
        bool isFP16 = outputs_.depth() == CV_16S;

716 717 718 719
        std::vector<UMat> outputs;
        outputs_.getUMatVector(outputs);

        for (int i = 0; i < inputsData.size(); ++i)
720
        {
721 722
            Mat inputData = inputsData[i];

723 724 725
            double scale = scaleFactors[i];
            Scalar& mean = means[i];

726 727 728 729 730 731
            CV_Assert(mean == Scalar() || inputData.size[1] <= 4);
            if (isFP16)
                CV_CheckTypeEQ(outputs[i].type(), CV_16SC1, "");
            else
                CV_CheckTypeEQ(outputs[i].type(), CV_32FC1, "");

732
            bool singleMean = true;
733
            for (int j = 1; j < std::min(4, inputData.size[1]) && singleMean; ++j)
734
            {
735 736 737
                singleMean = mean[j] == mean[j - 1];
            }

738
            if (singleMean)
739
            {
740
                if (isFP16)
741
                {
742 743 744
                    UMat input_i;
                    inputData.convertTo(input_i, CV_32F, scale, -mean[0] * scale);
                    convertFp16(input_i, outputs[i]);
745
                }
746 747
                else
                {
748
                    inputData.convertTo(outputs[i], CV_32F, scale, -mean[0] * scale);
749 750 751 752
                }
            }
            else
            {
753
                for (int n = 0; n < inputData.size[0]; ++n)
754
                {
755 756 757
                    for (int c = 0; c < inputData.size[1]; ++c)
                    {
                        Mat inp = getPlane(inputData, n, c);
758

759 760 761 762
                        std::vector<cv::Range> plane(4, Range::all());
                        plane[0] = Range(n, n + 1);
                        plane[1] = Range(c, c + 1);
                        UMat out = outputs[i](plane).reshape(1, inp.dims, inp.size);
763

764 765 766 767 768 769 770 771
                        if (isFP16)
                        {
                            UMat input_i;
                            inp.convertTo(input_i, CV_32F, scale, -mean[c] * scale);
                            convertFp16(input_i, out);
                        }
                        else
                        {
772 773
                            inp.convertTo(out, CV_32F, scale, -mean[c] * scale);
                        }
774
                    }
775
                }
776 777 778 779 780
            }
        }
        return true;
    }
#endif
781

782
    int outputNameToIndex(const String& tgtName) CV_OVERRIDE
783 784 785 786 787 788 789 790
    {
        int idx = (int)(std::find(outNames.begin(), outNames.end(), tgtName) - outNames.begin());
        return (idx < (int)outNames.size()) ? idx : -1;
    }

    void setNames(const std::vector<String> &names)
    {
        outNames.assign(names.begin(), names.end());
791 792 793 794 795 796 797 798 799 800 801 802
        shapes.clear(); shapes.resize(outNames.size());
    }

    void setInputShape(const String& tgtName, const MatShape& shape)
    {
        std::vector<String>::const_iterator it = std::find(outNames.begin(), outNames.end(), tgtName);
        CV_Check(tgtName, it != outNames.end(), "Unknown input");
        int idx = (int)(it - outNames.begin());

        CV_Assert(idx < (int)shapes.size());
        CV_Check(tgtName, shapes[idx].empty(), "Input shape redefinition is not allowed");
        shapes[idx] = shape;
803 804
    }

805 806 807
    bool getMemoryShapes(const std::vector<MatShape> &inputs,
                         const int requiredOutputs,
                         std::vector<MatShape> &outputs,
808
                         std::vector<MatShape> &internals) const CV_OVERRIDE
809 810 811 812 813 814
    {
        CV_Assert(inputs.size() == requiredOutputs);
        outputs.assign(inputs.begin(), inputs.end());
        return false;
    }

815
    virtual void finalize(InputArrayOfArrays, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
816
    {
817 818 819
        std::vector<Mat> outputs;
        outputs_arr.getMatVector(outputs);

820
        CV_Assert_N(outputs.size() == scaleFactors.size(), outputs.size() == means.size(),
821 822 823 824 825 826 827 828 829
                  inputsData.size() == outputs.size());
        skip = true;
        for (int i = 0; skip && i < inputsData.size(); ++i)
        {
            if (inputsData[i].data != outputs[i].data || scaleFactors[i] != 1.0 || means[i] != Scalar())
                skip = false;
        }
    }

830
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
831 832
    virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >&) CV_OVERRIDE
    {
833 834
        CV_CheckEQ(inputsData.size(), (size_t)1, "");
        CV_CheckEQ(inputsData[0].dims, 4, "");
835 836 837 838
        const size_t numChannels = inputsData[0].size[1];
        CV_Assert(numChannels <= 4);

        // Scale
839 840 841
        InferenceEngine::TensorDesc td(InferenceEngine::Precision::FP32, {numChannels},
                                       InferenceEngine::Layout::C);
        auto weights = InferenceEngine::make_shared_blob<float>(td);
842
        weights->allocate();
843 844 845

        float* weight_buf = weights->buffer().as<float*>();
        std::fill(weight_buf, weight_buf + numChannels, scaleFactors[0]);
846 847

        // Mean subtraction
848
        auto biases = InferenceEngine::make_shared_blob<float>(td);
849
        biases->allocate();
850 851
        float* bias_buf = biases->buffer().as<float*>();

852 853
        for (int i = 0; i < numChannels; ++i)
        {
854
            bias_buf[i] = -means[0][i] * scaleFactors[0];
855 856
        }

857 858 859
        InferenceEngine::Builder::Layer ieLayer = InferenceEngine::Builder::ScaleShiftLayer(name);
        addConstantData("weights", weights, ieLayer);
        addConstantData("biases", biases, ieLayer);
860 861
        return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
    }
862
#endif  // HAVE_DNN_IE_NN_BUILDER_2019
863

864
    std::vector<String> outNames;
865
    std::vector<MatShape> shapes;
866 867 868
    // Preprocessing parameters for each network's input.
    std::vector<double> scaleFactors;
    std::vector<Scalar> means;
869
    std::vector<Mat> inputsData;
870
    bool skip;
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
};

struct BlobManager
{
public:
    // Increase references counter to layer output.
    void addReference(const LayerPin& lp)
    {
        std::map<LayerPin, int>::iterator it = refCounter.find(lp);
        if (it == refCounter.end())
            refCounter[lp] = 1;
        else
            it->second += 1;
    }

    void addReferences(const std::vector<LayerPin>& pins)
    {
        for (int i = 0; i < pins.size(); i++)
        {
            addReference(pins[i]);
        }
    }

    // Returns number of references to allocated memory that used in specific
    // layer blob.
    int numReferences(const LayerPin& lp)
    {
        std::map<LayerPin, LayerPin>::iterator mapIt = reuseMap.find(lp);
        CV_Assert(mapIt != reuseMap.end());
        LayerPin memHost = mapIt->second;

        std::map<LayerPin, int>::iterator refIt = refCounter.find(memHost);
        CV_Assert(refIt != refCounter.end());
        return refIt->second;
    }

    // Reuse data allocated in <host> inside the <user> blob.
    void reuse(const LayerPin& host, const LayerPin& user)
    {
        CV_Assert(reuseMap.find(user) == reuseMap.end());
        CV_Assert(reuseMap.find(host) != reuseMap.end());
        LayerPin memHost = reuseMap[host];
        reuseMap[user] = memHost;
        if (refCounter.find(memHost) != refCounter.end())
        {
            std::map<LayerPin, int>::iterator userRefIt = refCounter.find(user);
            if (userRefIt != refCounter.end())
            {
                refCounter[memHost] += userRefIt->second;
                refCounter.erase(userRefIt);
            }
            else
                refCounter[memHost] += 1;
        }
    }

    // Decrease references counter to allocated memory inside specific blob.
    void releaseReference(const LayerPin& lp)
    {
        std::map<LayerPin, LayerPin>::iterator mapIt = reuseMap.find(lp);
        CV_Assert(mapIt != reuseMap.end());

        std::map<LayerPin, int>::iterator refIt = refCounter.find(mapIt->second);
        CV_Assert(refIt != refCounter.end());
        CV_Assert(refIt->second > 0);
        refIt->second -= 1;
    }

    void releaseReferences(const std::vector<LayerPin>& pins)
    {
        for (int i = 0; i < pins.size(); i++)
        {
            releaseReference(pins[i]);
        }
    }

947
    void reuseOrCreate(const MatShape& shape, const LayerPin& lp, Mat& dst, const int& dtype)
948
    {
949
        if (!DNN_DISABLE_MEMORY_OPTIMIZATIONS)
950 951 952
        {
            Mat bestBlob;
            LayerPin bestBlobPin;
953

954 955
            std::map<LayerPin, Mat>::iterator hostIt;
            std::map<LayerPin, int>::iterator refIt;
956

957 958
            const int targetTotal = total(shape);
            int bestBlobTotal = INT_MAX;
959

960
            for (hostIt = memHosts.begin(); hostIt != memHosts.end(); ++hostIt)
961
            {
962 963 964 965
                refIt = refCounter.find(hostIt->first);
                // Use only blobs that had references before because if not,
                // it might be used as output.
                if (refIt != refCounter.end() && refIt->second == 0)
966
                {
967 968
                    Mat& unusedBlob = hostIt->second;
                    if (unusedBlob.total() >= targetTotal &&
969 970
                        unusedBlob.total() < bestBlobTotal &&
                        unusedBlob.type() == dtype)
971 972 973 974 975
                    {
                        bestBlobPin = hostIt->first;
                        bestBlob = unusedBlob;
                        bestBlobTotal = unusedBlob.total();
                    }
976 977
                }
            }
978 979 980 981 982 983
            if (!bestBlob.empty())
            {
                reuse(bestBlobPin, lp);
                dst = bestBlob.reshape(1, 1).colRange(0, targetTotal).reshape(1, shape);
                return;
            }
984
        }
985

986 987
        {
            // if dst already has been allocated with total(shape) elements,
K
Kuang Fangjun 已提交
988
            // it won't be recreated and pointer of dst.data remains the same.
989
            dst.create(shape, dtype);
990 991 992 993 994
            addHost(lp, dst);
        }
    }

    void allocateBlobsForLayer(LayerData &ld, const LayerShapes& layerShapes,
995
                               std::vector<LayerPin>& pinsForInternalBlobs)
996
    {
A
Alexander Alekhin 已提交
997 998
        CV_TRACE_FUNCTION();

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
        pinsForInternalBlobs.clear();

        std::vector<Mat>& outputBlobs = ld.outputBlobs,
                &internalBlobs = ld.internals;

        const ShapesVec& outShapes = layerShapes.out,
                internalShapes = layerShapes.internal;

        outputBlobs.resize(std::max((size_t)1, outShapes.size())); //layer produce at least one output blob
        internalBlobs.resize(internalShapes.size());

        CV_Assert(ld.requiredOutputs.size() <= outShapes.size());

        // Check that layer could work in-place.
        bool inPlace = false;
        if (layerShapes.supportInPlace)
        {
            if (ld.inputBlobs.size() == 1)
            {
                // Get number of references to the input memory.
                int numRef = numReferences(ld.inputBlobsId[0]);
                // If current layer is one and only customer of this blob.
                inPlace = numRef == 1;
            }
        }

        ShapesVec shapes(outShapes);
        shapes.insert(shapes.end(), internalShapes.begin(), internalShapes.end());
        std::vector<Mat*> blobs;
        for(int i = 0; i < outputBlobs.size(); i++)
        {
            blobs.push_back(&outputBlobs[i]);
        }

        for(int i = 0; i < internalBlobs.size(); i++)
        {
            blobs.push_back(&internalBlobs[i]);
            if (total(internalShapes[i]))
            {
                pinsForInternalBlobs.push_back(LayerPin(ld.id, ld.outputBlobs.size() + i));
            }
        }

        addReferences(pinsForInternalBlobs);

        std::map<int, std::vector<int> > idxSizes;
        for(int i = 0; i < shapes.size(); i++)
        {
            idxSizes[total(shapes[i])].push_back(i);
        }

        std::map<int, std::vector<int> >::reverse_iterator it;
        for(it = idxSizes.rbegin(); it != idxSizes.rend(); it++)
        {
            for(int j = 0; j < it->second.size(); j++)
            {
                int index = it->second[j];
                if (total(shapes[index]))
                {
                    LayerPin blobPin(ld.id, index);
1059
                    if (index < outShapes.size() && inPlace)
1060
                    {
1061 1062
                        CV_Assert(ld.inputBlobs[0]->total() == total(shapes[index]));
                        ld.outputBlobs[index] = ld.inputBlobs[0]->reshape(1, shapes[index]);
1063 1064 1065
                        reuse(ld.inputBlobsId[0], blobPin);
                    }
                    else
1066
                        reuseOrCreate(shapes[index], blobPin, *blobs[index], ld.dtype);
1067 1068 1069 1070 1071 1072 1073 1074
                }
            }
        }
    }

    // Clear internal state. Calls before an every reallocation.
    void reset()
    {
A
Alexander Alekhin 已提交
1075 1076
        CV_TRACE_FUNCTION();

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
        refCounter.clear();
        reuseMap.clear();
        memHosts.clear();
    }

private:
    // Register allocated memory.
    void addHost(const LayerPin& lp, const Mat& mat)
    {
        CV_Assert(memHosts.find(lp) == memHosts.end());
        reuseMap[lp] = lp;
        memHosts[lp] = mat;
    }

    std::map<LayerPin, int> refCounter;
    // Maps pin to origin blob (for whom memory was allocated firstly).
    // For origin blobs key == value.
    std::map<LayerPin, LayerPin> reuseMap;
    std::map<LayerPin, Mat> memHosts;
};

1098
static Ptr<BackendWrapper> wrapMat(int backendId, int targetId, cv::Mat& m)
1099
{
1100
    if (backendId == DNN_BACKEND_OPENCV)
1101
    {
1102 1103
        if (targetId == DNN_TARGET_CPU)
            return Ptr<BackendWrapper>();
1104
#ifdef HAVE_OPENCL
L
Li Peng 已提交
1105
        else if (IS_DNN_OPENCL_TARGET(targetId))
1106
            return OpenCLBackendWrapper::create(m);
1107
#endif
1108
        else
1109
            CV_Error(Error::StsNotImplemented, "Unknown/unsupported target identifier");
1110 1111 1112 1113 1114 1115 1116
    }
    else if (backendId == DNN_BACKEND_HALIDE)
    {
        CV_Assert(haveHalide());
#ifdef HAVE_HALIDE
        return Ptr<BackendWrapper>(new HalideBackendWrapper(targetId, m));
#endif  // HAVE_HALIDE
1117
    }
1118
    else if (backendId == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019)
1119
    {
1120
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
1121
        return Ptr<BackendWrapper>(new InfEngineBackendWrapper(targetId, m));
1122
#else
1123
        CV_Error(Error::StsNotImplemented, "This OpenCV version is built without Inference Engine NN Builder API support");
1124 1125 1126 1127 1128 1129 1130 1131
#endif
    }
    else if (backendId == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
    {
#ifdef HAVE_DNN_NGRAPH
        return Ptr<BackendWrapper>(new NgraphBackendWrapper(targetId, m));
#else
        CV_Error(Error::StsNotImplemented, "This OpenCV version is built without support of Inference Engine + nGraph");
1132 1133 1134 1135 1136 1137 1138 1139
#endif
    }
    else if (backendId == DNN_BACKEND_WEBNN)
    {
#ifdef HAVE_WEBNN
        return Ptr<BackendWrapper>(new WebnnBackendWrapper(targetId, m));
#else
        CV_Error(Error::StsNotImplemented, "This OpenCV version is built without support of WebNN");
1140
#endif
1141 1142 1143 1144 1145 1146 1147
    }
    else if (backendId == DNN_BACKEND_VKCOM)
    {
        CV_Assert(haveVulkan());
#ifdef HAVE_VULKAN
        return Ptr<BackendWrapper>(new VkComBackendWrapper(m));
#endif  // HAVE_VULKAN
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    }
    else if (backendId == DNN_BACKEND_CUDA)
    {
        CV_Assert(haveCUDA());

#ifdef HAVE_CUDA
        switch (targetId)
        {
        case DNN_TARGET_CUDA:
            return CUDABackendWrapperFP32::create(m);
        case DNN_TARGET_CUDA_FP16:
            return CUDABackendWrapperFP16::create(m);
        default:
            CV_Assert(IS_DNN_CUDA_TARGET(targetId));
        }
#endif
1164 1165 1166
    }
    else
        CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
1167
    return Ptr<BackendWrapper>();  // TODO Error?
1168 1169
}

1170 1171
static int g_networkId = 0;

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
detail::NetImplBase::NetImplBase()
    : networkId(CV_XADD(&g_networkId, 1))
    , networkDumpCounter(0)
    , dumpLevel(DNN_NETWORK_DUMP)
{
    // nothing
}

std::string detail::NetImplBase::getDumpFileNameBase()
{
    std::string dumpFileNameBase = cv::format("ocv_dnn_net_%05d_%02d", networkId, networkDumpCounter++);
    return dumpFileNameBase;
}

struct Net::Impl : public detail::NetImplBase
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
{
    typedef std::map<int, LayerShapes> LayersShapesMap;
    typedef std::map<int, LayerData> MapIdToLayerData;

    Impl()
    {
        //allocate fake net input layer
        netInputLayer = Ptr<DataLayer>(new DataLayer());
        LayerData &inpl = layers.insert( make_pair(0, LayerData()) ).first->second;
        inpl.id = 0;
1197
        netInputLayer->name = inpl.name = "_input";
1198 1199 1200 1201
        inpl.type = "__NetInputLayer__";
        inpl.layerInstance = netInputLayer;
        layerNameToId.insert(std::make_pair(inpl.name, inpl.id));

1202
        lastLayerId = 0;
1203
        netWasAllocated = false;
1204
        netWasQuantized = false;
1205
        fusion = true;
1206
        isAsync = false;
1207 1208
        preferableBackend = DNN_BACKEND_DEFAULT;
        preferableTarget = DNN_TARGET_CPU;
1209
        skipInfEngineInit = false;
1210
        hasDynamicShapes = false;
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    }

    Ptr<DataLayer> netInputLayer;
    std::vector<LayerPin> blobsToKeep;
    MapIdToLayerData layers;
    std::map<String, int> layerNameToId;
    BlobManager blobManager;
    int preferableBackend;
    int preferableTarget;
    String halideConfigFile;
1221
    bool skipInfEngineInit;
1222
    bool hasDynamicShapes;
1223 1224
    // Map host data to backend specific wrapper.
    std::map<void*, Ptr<BackendWrapper> > backendWrappers;
1225 1226 1227 1228

    int lastLayerId;

    bool netWasAllocated;
1229
    bool netWasQuantized;
1230
    bool fusion;
1231
    bool isAsync;
1232
    std::vector<int64> layersTimings;
L
Li Peng 已提交
1233
    Mat output_blob;
1234

1235 1236 1237
#ifdef HAVE_CUDA
    struct CudaInfo_t
    {
1238 1239
        CudaInfo_t(cuda4dnn::csl::CSLContext ctxt, cuda4dnn::csl::Stream d2h_stream_)
         : context(std::move(ctxt)), d2h_stream(std::move(d2h_stream_)) { }
1240
        cuda4dnn::csl::CSLContext context;
1241
        cuda4dnn::csl::Stream d2h_stream;
1242 1243 1244 1245 1246 1247
        cuda4dnn::csl::Workspace workspace;
    };

    std::unique_ptr<CudaInfo_t> cudaInfo;
#endif

1248
    Ptr<BackendWrapper> wrap(Mat& host)
1249
    {
1250
        if (preferableBackend == DNN_BACKEND_OPENCV && preferableTarget == DNN_TARGET_CPU)
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
            return Ptr<BackendWrapper>();

        MatShape shape(host.dims);
        for (int i = 0; i < host.dims; ++i)
            shape[i] = host.size[i];

        void* data = host.data;
        if (backendWrappers.find(data) != backendWrappers.end())
        {
            Ptr<BackendWrapper> baseBuffer = backendWrappers[data];
1261
            if (preferableBackend == DNN_BACKEND_OPENCV)
1262
            {
1263
#ifdef HAVE_OPENCL
L
Li Peng 已提交
1264
                CV_Assert(IS_DNN_OPENCL_TARGET(preferableTarget));
1265
                return OpenCLBackendWrapper::create(baseBuffer, host);
1266 1267 1268
#else
                CV_Error(Error::StsInternal, "");
#endif
1269 1270
            }
            else if (preferableBackend == DNN_BACKEND_HALIDE)
1271 1272
            {
                CV_Assert(haveHalide());
1273
#ifdef HAVE_HALIDE
1274
                return Ptr<BackendWrapper>(new HalideBackendWrapper(baseBuffer, shape));
1275
#endif
1276
            }
1277 1278 1279 1280 1281
            else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019)
            {
                return wrapMat(preferableBackend, preferableTarget, host);
            }
            else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
1282 1283 1284
            {
                return wrapMat(preferableBackend, preferableTarget, host);
            }
1285 1286 1287 1288 1289 1290
            else if (preferableBackend == DNN_BACKEND_WEBNN)
            {
#ifdef HAVE_WEBNN
                return wrapMat(preferableBackend, preferableTarget, host);
#endif
            }
1291 1292 1293 1294 1295
            else if (preferableBackend == DNN_BACKEND_VKCOM)
            {
  #ifdef HAVE_VULKAN
                return Ptr<BackendWrapper>(new VkComBackendWrapper(baseBuffer, host));
  #endif
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
            }
            else if (preferableBackend == DNN_BACKEND_CUDA)
            {
                CV_Assert(haveCUDA());
#ifdef HAVE_CUDA
                switch (preferableTarget)
                {
                case DNN_TARGET_CUDA:
                    return CUDABackendWrapperFP32::create(baseBuffer, shape);
                case DNN_TARGET_CUDA_FP16:
                    return CUDABackendWrapperFP16::create(baseBuffer, shape);
                default:
                    CV_Assert(IS_DNN_CUDA_TARGET(preferableTarget));
                }
#endif
1311
            }
1312 1313 1314 1315 1316 1317 1318 1319 1320
            else
                CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
        }

        Ptr<BackendWrapper> wrapper = wrapMat(preferableBackend, preferableTarget, host);
        backendWrappers[data] = wrapper;
        return wrapper;
    }

1321
#ifdef HAVE_HALIDE
1322 1323
    void compileHalide()
    {
A
Alexander Alekhin 已提交
1324 1325
        CV_TRACE_FUNCTION();

1326 1327 1328
        CV_Assert(preferableBackend == DNN_BACKEND_HALIDE);

        HalideScheduler scheduler(halideConfigFile);
1329 1330
        std::vector< std::reference_wrapper<LayerData> > compileList; compileList.reserve(64);
        for (MapIdToLayerData::iterator it = layers.begin(); it != layers.end(); ++it)
1331 1332 1333
        {
            LayerData &ld = it->second;
            Ptr<Layer> layer = ld.layerInstance;
1334
            if (layer->supportBackend(DNN_BACKEND_HALIDE) && !ld.skip)
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
            {
                CV_Assert(!ld.backendNodes[DNN_BACKEND_HALIDE].empty());
                bool scheduled = scheduler.process(ld.backendNodes[DNN_BACKEND_HALIDE]);
                if (!scheduled)
                {
                    // Use automatic scheduling provided by layer.
                    layer->applyHalideScheduler(ld.backendNodes[DNN_BACKEND_HALIDE],
                                                ld.inputBlobs, ld.outputBlobs,
                                                preferableTarget);
                }
1345
                compileList.emplace_back(ld);
1346 1347
            }
        }
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
        std::atomic<int> progress(0);
        auto fn = ([&] () -> void
        {
            for (;;)
            {
                int id = progress.fetch_add(1);
                if ((size_t)id >= compileList.size())
                    return;
                const LayerData& ld = compileList[id].get();
                Ptr<BackendNode> node = ld.backendNodes.find(DNN_BACKEND_HALIDE)->second;
                dnn::compileHalide(ld.outputBlobs, node, preferableTarget);
            }
        });
        size_t num_threads = std::min(compileList.size(), (size_t)std::thread::hardware_concurrency());
        num_threads = std::max((size_t)1u, std::min((size_t)8u, num_threads));
        std::vector<std::thread> threads(num_threads - 1);
        for (auto& t: threads) t = std::thread(fn);
        fn(); // process own tasks
        for (auto& t: threads) t.join();
1367
    }
1368
#endif
1369 1370 1371

    void clear()
    {
A
Alexander Alekhin 已提交
1372 1373
        CV_TRACE_FUNCTION();

1374 1375 1376 1377
        MapIdToLayerData::iterator it;
        for (it = layers.begin(); it != layers.end(); it++)
        {
            if (it->second.id != 0) {
A
Aleksandr Rybnikov 已提交
1378
                it->second.inputBlobs.clear();
1379 1380 1381
                it->second.outputBlobs.clear();
                it->second.internals.clear();
            }
1382
            it->second.skip = false;
1383 1384
            //it->second.consumers.clear();
            Ptr<Layer> currLayer = it->second.layerInstance;
1385

1386 1387 1388
            if( currLayer.empty() )
                continue;

1389
            currLayer->unsetAttached();
1390
        }
1391
        netWasAllocated = false;
1392
        layersTimings.clear();
1393 1394 1395 1396
    }

    void setUpNet(const std::vector<LayerPin>& blobsToKeep_ = std::vector<LayerPin>())
    {
A
Alexander Alekhin 已提交
1397 1398
        CV_TRACE_FUNCTION();

1399
        if (dumpLevel && networkDumpCounter == 0)
1400 1401 1402 1403
        {
            dumpNetworkToFile();
        }

1404
        if (preferableBackend == DNN_BACKEND_DEFAULT)
1405
            preferableBackend = (Backend)PARAM_DNN_BACKEND_DEFAULT;
1406 1407 1408 1409
#ifdef HAVE_INF_ENGINE
        if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE)
            preferableBackend = getInferenceEngineBackendTypeParam();
#endif
1410

1411 1412 1413 1414 1415 1416 1417
        CV_Assert(preferableBackend != DNN_BACKEND_OPENCV ||
                  preferableTarget == DNN_TARGET_CPU ||
                  preferableTarget == DNN_TARGET_OPENCL ||
                  preferableTarget == DNN_TARGET_OPENCL_FP16);
        CV_Assert(preferableBackend != DNN_BACKEND_HALIDE ||
                  preferableTarget == DNN_TARGET_CPU ||
                  preferableTarget == DNN_TARGET_OPENCL);
1418
#ifdef HAVE_INF_ENGINE
1419 1420 1421 1422
        if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 ||
            preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
        {
            CV_Assert(
1423
                  (preferableTarget == DNN_TARGET_CPU && (!isArmComputePlugin() || preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)) ||
1424 1425
                  preferableTarget == DNN_TARGET_OPENCL ||
                  preferableTarget == DNN_TARGET_OPENCL_FP16 ||
1426
                  preferableTarget == DNN_TARGET_MYRIAD ||
1427
                  preferableTarget == DNN_TARGET_HDDL ||
1428 1429 1430
                  preferableTarget == DNN_TARGET_FPGA
            );
        }
1431 1432 1433 1434 1435 1436 1437
#endif
#ifdef HAVE_WEBNN
        if (preferableBackend == DNN_BACKEND_WEBNN)
        {
            CV_Assert(preferableTarget == DNN_TARGET_CPU ||
                      preferableTarget == DNN_TARGET_OPENCL);
        }
1438
#endif
1439 1440
        CV_Assert(preferableBackend != DNN_BACKEND_VKCOM ||
                  preferableTarget == DNN_TARGET_VULKAN);
1441 1442
        CV_Assert(preferableBackend != DNN_BACKEND_CUDA ||
                  IS_DNN_CUDA_TARGET(preferableTarget));
1443 1444
        if (!netWasAllocated || this->blobsToKeep != blobsToKeep_)
        {
1445
            if (preferableBackend == DNN_BACKEND_OPENCV && IS_DNN_OPENCL_TARGET(preferableTarget))
1446
#ifndef HAVE_OPENCL
1447
            {
1448
                CV_LOG_WARNING(NULL, "DNN: OpenCL target is not available in this OpenCV build, switching to CPU.");
1449 1450
                preferableTarget = DNN_TARGET_CPU;
            }
1451 1452
#else
            {
1453
                if (!DNN_OPENCL_ALLOW_ALL_DEVICES)
1454
                {
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
                    // Current implementation is only valid for GPU (#11494)
                    if (ocl::Device::getDefault().type() != ocl::Device::TYPE_GPU)
                    {
                        CV_LOG_WARNING(NULL, "DNN: OpenCL target is not supported with current OpenCL device (tested with GPUs only), switching to CPU.");
                        preferableTarget = DNN_TARGET_CPU;
                    }
                    else if (preferableTarget == DNN_TARGET_OPENCL_FP16 && !ocl::Device::getDefault().isIntel())
                    {
                        CV_LOG_WARNING(NULL,
                            "DNN: OpenCL target with fp16 precision is not supported "
                            "with current OpenCL device (tested with Intel GPUs only), "
                            "switching to OpenCL with fp32 precision.");
                        preferableTarget = DNN_TARGET_OPENCL;
                    }
1469 1470
                }
            }
1471
#endif
1472 1473 1474 1475 1476 1477
            if (preferableBackend == DNN_BACKEND_VKCOM && !haveVulkan())
            {
                preferableBackend = DNN_BACKEND_OPENCV;
                preferableTarget = DNN_TARGET_CPU;
            }

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
            if (preferableBackend == DNN_BACKEND_CUDA && !haveCUDA())
            {
#ifdef HAVE_CUDA
                CV_LOG_WARNING(NULL, "unable to use CUDA backend; switching to CPU");
#else
                CV_LOG_WARNING(NULL, "DNN module was not built with CUDA backend; switching to CPU");
#endif
                preferableBackend = DNN_BACKEND_OPENCV;
                preferableTarget = DNN_TARGET_CPU;
            }

1489 1490
            clear();

1491 1492 1493 1494 1495
            if (hasDynamicShapes)
            {
                updateLayersShapes();
            }

1496 1497
            this->blobsToKeep = blobsToKeep_;

1498
            allocateLayers(blobsToKeep_);
1499 1500 1501 1502 1503

            MapIdToLayerData::iterator it = layers.find(0);
            CV_Assert(it != layers.end());
            it->second.skip = netInputLayer->skip;

1504
            initBackend(blobsToKeep_);
1505

1506
            if (!netWasAllocated)
1507
            {
1508
#ifdef HAVE_HALIDE
1509 1510
                if (preferableBackend == DNN_BACKEND_HALIDE)
                    compileHalide();
1511 1512 1513
#else
                CV_Assert(preferableBackend != DNN_BACKEND_HALIDE);
#endif
1514 1515 1516
            }

            netWasAllocated = true;
1517

1518
            if (dumpLevel)
1519 1520 1521
            {
                dumpNetworkToFile();
            }
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
        }
    }

    int getLayerId(const String &layerName)
    {
        std::map<String, int>::iterator it = layerNameToId.find(layerName);
        return (it != layerNameToId.end()) ? it->second : -1;
    }

    int getLayerId(int id)
    {
        MapIdToLayerData::iterator it = layers.find(id);
        return (it != layers.end()) ? id : -1;
    }

    int getLayerId(DictValue &layerDesc)
    {
        if (layerDesc.isInt())
            return getLayerId(layerDesc.get<int>());
        else if (layerDesc.isString())
            return getLayerId(layerDesc.get<String>());

        CV_Assert(layerDesc.isInt() || layerDesc.isString());
        return -1;
    }

    String getLayerName(int id)
    {
        MapIdToLayerData::iterator it = layers.find(id);
        return (it != layers.end()) ? it->second.name : "(unknown layer)";
    }

    LayerData& getLayerData(int id)
    {
        MapIdToLayerData::iterator it = layers.find(id);

        if (it == layers.end())
            CV_Error(Error::StsObjectNotFound, format("Layer with requested id=%d not found", id));

        return it->second;
    }

    LayerData& getLayerData(const String &layerName)
    {
        int id = getLayerId(layerName);

        if (id < 0)
L
luz.paz 已提交
1569
            CV_Error(Error::StsError, "Requested layer \"" + layerName + "\" not found");
1570 1571 1572 1573 1574 1575

        return getLayerData(id);
    }

    LayerData& getLayerData(const DictValue &layerDesc)
    {
1576
        CV_Assert(layerDesc.isInt() || layerDesc.isString());
1577 1578
        if (layerDesc.isInt())
            return getLayerData(layerDesc.get<int>());
1579
        else /*if (layerDesc.isString())*/
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
            return getLayerData(layerDesc.get<String>());
    }

    static void addLayerInput(LayerData &ld, int inNum, LayerPin from)
    {
        if ((int)ld.inputBlobsId.size() <= inNum)
        {
            ld.inputBlobsId.resize(inNum + 1);
        }
        else
        {
            LayerPin storedFrom = ld.inputBlobsId[inNum];
            if (storedFrom.valid() && !storedFrom.equal(from))
1593 1594
                CV_Error(Error::StsError, format("Input #%d of layer \"%s\" already was connected",
                                                 inNum, ld.name.c_str()));
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
        }

        ld.inputBlobsId[inNum] = from;
    }

    int resolvePinOutputName(LayerData &ld, const String &outName)
    {
        if (outName.empty())
            return 0;
        return ld.getLayerInstance()->outputNameToIndex(outName);
    }

1607
    LayerPin getPinByAlias(const String &layerName)
1608 1609 1610 1611 1612
    {
        LayerPin pin;
        pin.lid = (layerName.empty()) ? 0 : getLayerId(layerName);

        if (pin.lid >= 0)
1613
            pin.oid = resolvePinOutputName(getLayerData(pin.lid), layerName);
1614 1615 1616 1617

        return pin;
    }

1618
    std::vector<LayerPin> getLayerOutPins(const String &layerName)
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
    {
        int lid = (layerName.empty()) ? 0 : getLayerId(layerName);

        std::vector<LayerPin> pins;

        for (int i = 0; i < layers[lid].outputBlobs.size(); i++)
        {
            pins.push_back(LayerPin(lid, i));
        }

        return pins;
    }

    void connect(int outLayerId, int outNum, int inLayerId, int inNum)
    {
        CV_Assert(outLayerId < inLayerId);
        LayerData &ldOut = getLayerData(outLayerId);
        LayerData &ldInp = getLayerData(inLayerId);

        addLayerInput(ldInp, inNum, LayerPin(outLayerId, outNum));
        ldOut.requiredOutputs.insert(outNum);
        ldOut.consumers.push_back(LayerPin(inLayerId, outNum));
    }

1643
    void initBackend(const std::vector<LayerPin>& blobsToKeep_)
1644
    {
A
Alexander Alekhin 已提交
1645
        CV_TRACE_FUNCTION();
1646
        if (preferableBackend == DNN_BACKEND_OPENCV)
1647
        {
L
Li Peng 已提交
1648
            CV_Assert(preferableTarget == DNN_TARGET_CPU || IS_DNN_OPENCL_TARGET(preferableTarget));
1649
        }
1650 1651
        else if (preferableBackend == DNN_BACKEND_HALIDE)
            initHalideBackend();
1652 1653
        else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019)
        {
1654
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
1655
            initInfEngineBackend(blobsToKeep_);
1656
#else
1657
            CV_Assert(false && "This OpenCV version is built without Inference Engine NN Builder API support");
1658 1659 1660 1661 1662
#endif
        }
        else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
        {
#ifdef HAVE_DNN_NGRAPH
1663
            initNgraphBackend(blobsToKeep_);
1664 1665
#else
            CV_Error(Error::StsNotImplemented, "This OpenCV version is built without support of Inference Engine + nGraph");
1666 1667 1668 1669 1670 1671 1672 1673
#endif
        }
        else if (preferableBackend == DNN_BACKEND_WEBNN)
        {
#ifdef HAVE_WEBNN
            initWebnnBackend(blobsToKeep_);
#else
            CV_Error(Error::StsNotImplemented, "This OpenCV version is built without support of WebNN");
1674 1675
#endif
        }
1676 1677
        else if (preferableBackend == DNN_BACKEND_VKCOM)
            initVkComBackend();
1678
        else if (preferableBackend == DNN_BACKEND_CUDA)
1679
            initCUDABackend(blobsToKeep_);
1680 1681 1682 1683 1684 1685 1686
        else
            CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
    }

    void initHalideBackend()
    {
        CV_TRACE_FUNCTION();
1687
        CV_Assert_N(preferableBackend == DNN_BACKEND_HALIDE, haveHalide());
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723

        // Iterator to current layer.
        MapIdToLayerData::iterator it = layers.begin();
        // Iterator to base layer for fusion. In example, in case of conv+bn+relu
        // it'll be a conv layer.
        MapIdToLayerData::iterator baseIt = layers.begin();
        for (; it != layers.end(); it++)
        {
            LayerData &ldTop = it->second;
            Ptr<Layer> layerTop = ldTop.layerInstance;
            if (!layerTop->supportBackend(preferableBackend))
            {
                // Move base iterator to layer that don't support preferable
                // backend to prevent fusion over layer of different backend.
                baseIt = it;
                continue;
            }
            // Try to do layers fusion.
            LayerData &ldBot = baseIt->second;
            Ptr<Layer> layerBot = ldBot.layerInstance;
            // 1. Check that bottom and top from the same backends.
            if (it != layers.begin() && layerBot->supportBackend(preferableBackend))
            {
                // 2. Check that current layer works in-place.
                bool inPlace = ldTop.inputBlobs.size() == 1 &&
                               ldBot.outputBlobs.size() == 1 &&
                               ldTop.inputBlobs[0]->data ==
                               ldBot.outputBlobs[0].data;
                if (inPlace)
                {
                    // 3. Try to attach node.
                    CV_Assert(!ldBot.backendNodes[preferableBackend].empty());
                    Ptr<BackendNode> fusedNode =
                        layerTop->tryAttach(ldBot.backendNodes[preferableBackend]);
                    if (!fusedNode.empty())
                    {
1724
                        ldTop.skip = true;
1725
                        ldBot.backendNodes[preferableBackend] = fusedNode;
1726
                        ldBot.outputBlobsWrappers = ldTop.outputBlobsWrappers;
1727 1728 1729 1730 1731
                        continue;
                    }
                }
            }
            // No layers fusion.
1732
            ldTop.skip = false;
1733 1734 1735 1736 1737 1738
            ldTop.backendNodes[DNN_BACKEND_HALIDE] =
                layerTop->initHalide(ldTop.inputBlobsWrappers);
            baseIt = it;
        }
    }

1739
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
1740 1741 1742 1743 1744
    // Before launching Inference Engine graph we need to specify output blobs.
    // This function requests output blobs based on inputs references of
    // layers from default backend or layers from different graphs.
    void addInfEngineNetOutputs(LayerData &ld)
    {
1745
        CV_TRACE_FUNCTION();
1746 1747 1748 1749 1750 1751 1752
        Ptr<InfEngineBackendNet> layerNet;
        if (ld.backendNodes.find(preferableBackend) != ld.backendNodes.end())
        {
            Ptr<BackendNode> node = ld.backendNodes[preferableBackend];
            if (!node.empty())
            {
                Ptr<InfEngineBackendNode> ieNode = node.dynamicCast<InfEngineBackendNode>();
1753
                CV_Assert(!ieNode.empty()); CV_Assert(!ieNode->net.empty());
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
                layerNet = ieNode->net;
            }
        }
        // For an every input reference we check that it belongs to one of
        // the Inference Engine backend graphs. Request an output blob if it is.
        // Do nothing if layer's input is from the same graph.
        for (int i = 0; i < ld.inputBlobsId.size(); ++i)
        {
            LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
            Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
            if (!inpNode.empty())
            {
                Ptr<InfEngineBackendNode> ieInpNode = inpNode.dynamicCast<InfEngineBackendNode>();
1767
                CV_Assert(!ieInpNode.empty()); CV_Assert(!ieInpNode->net.empty());
1768 1769 1770
                if (layerNet != ieInpNode->net)
                {
                    // layerNet is empty or nodes are from different graphs.
1771
                    ieInpNode->net->addOutput(ieInpNode->layer.getName());
1772 1773 1774 1775
                }
            }
        }
    }
1776

1777
    void initInfEngineBackend(const std::vector<LayerPin>& blobsToKeep_)
1778 1779
    {
        CV_TRACE_FUNCTION();
1780
        CV_Assert_N(preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, haveInfEngine());
1781 1782
        MapIdToLayerData::iterator it;
        Ptr<InfEngineBackendNet> net;
1783

1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
        for (it = layers.begin(); it != layers.end(); ++it)
        {
            LayerData &ld = it->second;
            if (ld.id == 0)
            {
                CV_Assert((netInputLayer->outNames.empty() && ld.outputBlobsWrappers.size() == 1) ||
                          (netInputLayer->outNames.size() == ld.outputBlobsWrappers.size()));
                for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                {
                    InferenceEngine::DataPtr dataPtr = infEngineDataNode(ld.outputBlobsWrappers[i]);
1794
#if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_LE(2019010000)
1795
                    dataPtr->name = netInputLayer->outNames.empty() ? ld.name : netInputLayer->outNames[i];
1796 1797 1798
#else
                    dataPtr->setName(netInputLayer->outNames.empty() ? ld.name : netInputLayer->outNames[i]);
#endif
1799 1800 1801 1802 1803 1804 1805
                }
            }
            else
            {
                for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                {
                    InferenceEngine::DataPtr dataPtr = infEngineDataNode(ld.outputBlobsWrappers[i]);
1806
#if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_LE(2019010000)
1807
                    dataPtr->name = ld.name;
1808 1809 1810
#else
                    dataPtr->setName(ld.name);
#endif
1811 1812 1813 1814
                }
            }
        }

1815 1816 1817 1818 1819 1820 1821
        if (skipInfEngineInit)
        {
            Ptr<BackendNode> node = layers[lastLayerId].backendNodes[preferableBackend];
            CV_Assert(!node.empty());

            Ptr<InfEngineBackendNode> ieNode = node.dynamicCast<InfEngineBackendNode>();
            CV_Assert(!ieNode.empty());
1822
            ieNode->net->reset();
1823 1824 1825 1826

            for (it = layers.begin(); it != layers.end(); ++it)
            {
                LayerData &ld = it->second;
1827
                if (ld.id == 0)
1828
                {
1829 1830 1831
                    for (int i = 0; i < ld.inputBlobsWrappers.size(); ++i)
                    {
                        InferenceEngine::DataPtr dataPtr = infEngineDataNode(ld.inputBlobsWrappers[i]);
1832
#if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_LE(2019010000)
1833
                        dataPtr->name = netInputLayer->outNames[i];
1834 1835 1836
#else
                        dataPtr->setName(netInputLayer->outNames[i]);
#endif
1837 1838 1839 1840 1841 1842 1843
                    }
                }
                else
                {
                    for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                    {
                        InferenceEngine::DataPtr dataPtr = infEngineDataNode(ld.outputBlobsWrappers[i]);
1844
#if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_LE(2019010000)
1845
                        dataPtr->name = ld.name;
1846 1847 1848
#else
                        dataPtr->setName(ld.name);
#endif
1849
                    }
1850 1851 1852 1853 1854 1855
                }
                ieNode->net->addBlobs(ld.inputBlobsWrappers);
                ieNode->net->addBlobs(ld.outputBlobsWrappers);
                ld.skip = true;
            }
            layers[lastLayerId].skip = false;
1856
            ieNode->net->init((Target)preferableTarget);
1857 1858 1859 1860 1861
            return;
        }

        // Build Inference Engine networks from sets of layers that support this
        // backend. Split a whole model on several Inference Engine networks if
1862
        // some of layers are not implemented.
1863

1864 1865 1866
        bool supportsCPUFallback = preferableTarget == DNN_TARGET_CPU ||
                                   BackendRegistry::checkIETarget(DNN_TARGET_CPU);

1867
        // Set of all input and output blobs wrappers for current network.
1868
        std::map<LayerPin, Ptr<BackendWrapper> > netBlobsWrappers;
1869 1870 1871
        for (it = layers.begin(); it != layers.end(); ++it)
        {
            LayerData &ld = it->second;
1872
            if (ld.id == 0 && ld.skip)
1873 1874
                continue;
            bool fused = ld.skip;
1875

1876
            Ptr<Layer> layer = ld.layerInstance;
1877
            if (!fused && !layer->supportBackend(preferableBackend))
1878
            {
1879
                bool customizable = ld.id != 0 &&
1880 1881
                                    INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2019R2) &&
                                    supportsCPUFallback;
1882
                // TODO: there is a bug in Myriad plugin with custom layers shape infer.
1883
                if (preferableTarget == DNN_TARGET_MYRIAD || preferableTarget == DNN_TARGET_HDDL)
1884 1885 1886 1887 1888 1889 1890 1891 1892
                {
                    for (int i = 0; customizable && i < ld.inputBlobs.size(); ++i)
                    {
                        customizable = ld.inputBlobs[i]->size[0] == 1;
                    }
                }

                // TODO: fix these workarounds
                if (preferableTarget == DNN_TARGET_MYRIAD ||
1893
                    preferableTarget == DNN_TARGET_HDDL ||
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
                    preferableTarget == DNN_TARGET_OPENCL ||
                    preferableTarget == DNN_TARGET_OPENCL_FP16)
                    customizable &= ld.type != "Concat";

                if (preferableTarget == DNN_TARGET_OPENCL ||
                    preferableTarget == DNN_TARGET_OPENCL_FP16)
                    customizable &= ld.type != "Power";

                if (preferableTarget == DNN_TARGET_OPENCL)
                    customizable &= ld.type != "Eltwise";

                if (!customizable)
                {
                    addInfEngineNetOutputs(ld);
                    net = Ptr<InfEngineBackendNet>();
                    netBlobsWrappers.clear();  // Is not used for R5 release but we don't wrap it to #ifdef.
                    layer->preferableTarget = DNN_TARGET_CPU;
                    continue;
                }
1913
            }
1914
            ld.skip = true;  // Initially skip all Inference Engine supported layers.
1915

1916
            // Create a new network if one of inputs from different Inference Engine graph.
1917 1918 1919 1920 1921 1922 1923
            for (int i = 0; i < ld.inputBlobsId.size(); ++i)
            {
                LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
                Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
                if (!inpNode.empty())
                {
                    Ptr<InfEngineBackendNode> ieInpNode = inpNode.dynamicCast<InfEngineBackendNode>();
1924
                    CV_Assert(!ieInpNode.empty()); CV_Assert(!ieInpNode->net.empty());
1925 1926 1927
                    if (ieInpNode->net != net)
                    {
                        net = Ptr<InfEngineBackendNet>();
1928
                        netBlobsWrappers.clear();  // Is not used for R5 release but we don't wrap it to #ifdef.
1929 1930 1931 1932 1933
                        break;
                    }
                }
            }

1934 1935 1936
            Ptr<BackendNode> node;
            if (!net.empty())
            {
1937
                if (fused)
1938
                {
1939 1940 1941 1942 1943
                    bool inPlace = ld.inputBlobsId.size() == 1 && ld.outputBlobs.size() == 1 &&
                                   ld.inputBlobs[0]->data == ld.outputBlobs[0].data;
                    CV_Assert(inPlace);
                    node = layers[ld.inputBlobsId[0].lid].backendNodes[preferableBackend];
                    ld.inputBlobsWrappers = layers[ld.inputBlobsId[0].lid].inputBlobsWrappers;
1944
                }
1945 1946
            }
            else
1947 1948 1949
                net = Ptr<InfEngineBackendNet>(new InfEngineBackendNet());

            if (!fused)
1950
            {
1951 1952 1953 1954 1955 1956 1957
                if (layer->supportBackend(preferableBackend))
                    node = layer->initInfEngine(ld.inputBlobsWrappers);
                else
                {
                    node = Ptr<BackendNode>(new InfEngineBackendNode(
                        ld.layerInstance, ld.inputBlobs, ld.outputBlobs, ld.internals));
                }
1958
            }
1959 1960
            else if (node.empty())
                continue;
1961 1962 1963 1964 1965 1966 1967 1968

            CV_Assert(!node.empty());
            ld.backendNodes[preferableBackend] = node;

            Ptr<InfEngineBackendNode> ieNode = node.dynamicCast<InfEngineBackendNode>();
            CV_Assert(!ieNode.empty());
            ieNode->net = net;

1969 1970 1971 1972 1973 1974 1975 1976 1977
            for (const auto& pin : blobsToKeep_)
            {
                if (pin.lid == ld.id)
                {
                    ieNode->net->addOutput(ieNode->layer.getName());
                    break;
                }
            }

1978 1979 1980
            // Convert weights in FP16 for specific targets.
            if ((preferableTarget == DNN_TARGET_OPENCL_FP16 ||
                 preferableTarget == DNN_TARGET_MYRIAD ||
1981
                 preferableTarget == DNN_TARGET_HDDL ||
1982 1983
                 preferableTarget == DNN_TARGET_FPGA) && !fused)
            {
1984
#if INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2019R1)
1985 1986 1987 1988 1989
                for (const std::string& name : {"weights", "biases"})
                {
                    auto it = ieNode->layer.getParameters().find(name);
                    if (it != ieNode->layer.getParameters().end())
                    {
1990 1991
                        InferenceEngine::Blob::Ptr bp = it->second.as<InferenceEngine::Blob::Ptr>();
                        it->second = convertFp16(std::const_pointer_cast<InferenceEngine::Blob>(bp));
1992 1993 1994
                    }
                }
#else
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
                auto& blobs = ieNode->layer.getConstantData();
                if (blobs.empty())
                {
                    // In case of non weightable layer we have to specify
                    // it's precision adding dummy blob.
                    auto blob = InferenceEngine::make_shared_blob<int16_t>(
                                    InferenceEngine::Precision::FP16,
                                    InferenceEngine::Layout::C, {1});
                    blob->allocate();
                    blobs[""] = blob;
                }
                else
                {
                    for (auto& it : blobs)
                        it.second = convertFp16(std::const_pointer_cast<InferenceEngine::Blob>(it.second));
                }
2011
#endif
2012 2013 2014 2015 2016 2017 2018 2019 2020
            }

            if (!fused)
                net->addLayer(ieNode->layer);

            net->connect(ld.inputBlobsWrappers, ld.outputBlobsWrappers, ieNode->layer.getName());
            net->addBlobs(ld.inputBlobsWrappers);
            net->addBlobs(ld.outputBlobsWrappers);
            addInfEngineNetOutputs(ld);
2021
        }
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041

        // Initialize all networks.
        for (MapIdToLayerData::reverse_iterator it = layers.rbegin(); it != layers.rend(); ++it)
        {
            LayerData &ld = it->second;
            if (ld.backendNodes.find(preferableBackend) == ld.backendNodes.end())
                continue;

            Ptr<BackendNode> node = ld.backendNodes[preferableBackend];
            if (node.empty())
                continue;

            Ptr<InfEngineBackendNode> ieNode = node.dynamicCast<InfEngineBackendNode>();
            if (ieNode.empty())
                continue;

            CV_Assert(!ieNode->net.empty());

            if (!ieNode->net->isInitialized())
            {
2042
                ieNode->net->init((Target)preferableTarget);
2043 2044 2045
                ld.skip = false;
            }
        }
2046
    }
2047
#endif  // HAVE_DNN_IE_NN_BUILDER_2019
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084


#ifdef HAVE_DNN_NGRAPH
    void addNgraphOutputs(LayerData &ld)
    {
        CV_TRACE_FUNCTION();

        Ptr<InfEngineNgraphNet> layerNet;
        auto it = ld.backendNodes.find(preferableBackend);
        if (it != ld.backendNodes.end())
        {
            Ptr<BackendNode> node = it->second;
            if (!node.empty())
            {
                Ptr<InfEngineNgraphNode> ieNode = node.dynamicCast<InfEngineNgraphNode>();
                CV_Assert(!ieNode.empty()); CV_Assert(!ieNode->net.empty());
                layerNet = ieNode->net;
            }
        }

        for (int i = 0; i < ld.inputBlobsId.size(); ++i)
        {
            LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
            Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
            if (!inpNode.empty())
            {
                Ptr<InfEngineNgraphNode> ieInpNode = inpNode.dynamicCast<InfEngineNgraphNode>();
                CV_Assert(!ieInpNode.empty()); CV_Assert(!ieInpNode->net.empty());
                if (layerNet != ieInpNode->net)
                {
                    ieInpNode->net->addOutput(ieInpNode->node->get_friendly_name());
                    ieInpNode->net->setUnconnectedNodes(ieInpNode);
                }
            }
        }
    }

2085
    void initNgraphBackend(const std::vector<LayerPin>& blobsToKeep_)
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
    {
        CV_TRACE_FUNCTION();
        CV_Assert_N(preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH, haveInfEngine());

        MapIdToLayerData::iterator it;
        Ptr<InfEngineNgraphNet> net;

        for (it = layers.begin(); it != layers.end(); ++it)
        {
            LayerData &ld = it->second;
            if (ld.id == 0)
            {
                CV_Assert((netInputLayer->outNames.empty() && ld.outputBlobsWrappers.size() == 1) ||
                          (netInputLayer->outNames.size() == ld.outputBlobsWrappers.size()));
                for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                {
                    InferenceEngine::DataPtr dataPtr = ngraphDataNode(ld.outputBlobsWrappers[i]);
2103 2104 2105
                    std::string outputName = netInputLayer->outNames.empty() ? ld.name : netInputLayer->outNames[i];
                    outputName = ld.outputBlobsWrappers.size() > 1 ? (outputName + "." + std::to_string(i)) : outputName;
                    dataPtr->setName(outputName);
2106 2107 2108 2109 2110 2111 2112
                }
            }
            else
            {
                for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                {
                    InferenceEngine::DataPtr dataPtr = ngraphDataNode(ld.outputBlobsWrappers[i]);
2113 2114
                    std::string outputName = ld.outputBlobsWrappers.size() > 1 ? (ld.name + "." + std::to_string(i)) : ld.name;
                    dataPtr->setName(outputName);
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
                }
            }
        }

        if (skipInfEngineInit)
        {
            Ptr<BackendNode> node = layers[lastLayerId].backendNodes[preferableBackend];
            CV_Assert(!node.empty());

            Ptr<InfEngineNgraphNode> ieNode = node.dynamicCast<InfEngineNgraphNode>();
            CV_Assert(!ieNode.empty());
2126 2127 2128 2129

            CV_Assert(ieNode->net);
            InfEngineNgraphNet& ienet = *ieNode->net;
            ienet.reset();
2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145

            for (it = layers.begin(); it != layers.end(); ++it)
            {
                LayerData &ld = it->second;
                if (ld.id == 0)
                {
                    for (int i = 0; i < ld.inputBlobsWrappers.size(); ++i)
                    {
                        InferenceEngine::DataPtr dataPtr = ngraphDataNode(ld.inputBlobsWrappers[i]);
                        dataPtr->setName(netInputLayer->outNames[i]);
                    }
                }
                else
                {
                    for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                    {
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
                        auto it = ienet.outputsDesc.find(ld.name);
                        if (it != ienet.outputsDesc.end())
                        {
                            const InferenceEngine::TensorDesc& descriptor = it->second;
                            InferenceEngine::DataPtr dataPtr = ngraphDataOutputNode(ld.outputBlobsWrappers[i], descriptor, ld.name);
                            dataPtr->setName(ld.name);
                        }
                        else
                        {
                            InferenceEngine::DataPtr dataPtr = ngraphDataNode(ld.outputBlobsWrappers[i]);
                            dataPtr->setName(ld.name);
                        }
2158 2159
                    }
                }
2160 2161
                ienet.addBlobs(ld.inputBlobsWrappers);
                ienet.addBlobs(ld.outputBlobsWrappers);
2162 2163 2164
                ld.skip = true;
            }
            layers[lastLayerId].skip = false;
2165
            ienet.init((Target)preferableTarget);
2166 2167 2168
            return;
        }

2169 2170
        bool supportsCPUFallback = !isArmComputePlugin() && (preferableTarget == DNN_TARGET_CPU ||
                                   BackendRegistry::checkIETarget(DNN_TARGET_CPU));
2171

2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
        // Build Inference Engine networks from sets of layers that support this
        // backend. Split a whole model on several Inference Engine networks if
        // some of layers are not implemented.
        for (it = layers.begin(); it != layers.end(); ++it)
        {
            LayerData &ld = it->second;

            if (ld.id == 0 && ld.skip)
                continue;

            bool fused = ld.skip;
            Ptr<Layer> layer = ld.layerInstance;
            if (!fused && !layer->supportBackend(preferableBackend))
            {
2186
                bool customizable = ld.id != 0 && supportsCPUFallback;
2187

2188
                // TODO: there is a bug in Myriad plugin with custom layers shape infer.
2189
                if (preferableTarget == DNN_TARGET_MYRIAD || preferableTarget == DNN_TARGET_HDDL)
2190
                {
2191 2192 2193
                    for (int i = 0; customizable && i < ld.inputBlobs.size(); ++i)
                    {
                        customizable = ld.inputBlobs[i]->size[0] == 1;
2194 2195
                    }
                }
2196 2197 2198

                // TODO: fix these workarounds
                if (preferableTarget == DNN_TARGET_MYRIAD ||
2199
                    preferableTarget == DNN_TARGET_HDDL ||
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
                    preferableTarget == DNN_TARGET_OPENCL ||
                    preferableTarget == DNN_TARGET_OPENCL_FP16)
                    customizable &= ld.type != "Concat";

                if (preferableTarget == DNN_TARGET_OPENCL ||
                    preferableTarget == DNN_TARGET_OPENCL_FP16)
                    customizable &= ld.type != "Power";

                if (preferableTarget == DNN_TARGET_OPENCL)
                    customizable &= ld.type != "Eltwise";

                if (!customizable)
                {
                    addNgraphOutputs(ld);
                    net = Ptr<InfEngineNgraphNet>();
                    layer->preferableTarget = DNN_TARGET_CPU;

                    for (int i = 0; i < ld.inputBlobsId.size(); ++i)
                    {
                        LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
                        Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
                        if (!inpNode.empty()) {
                            Ptr<InfEngineNgraphNode> ieNode = inpNode.dynamicCast<InfEngineNgraphNode>();
2223
                            CV_Assert(!ieNode.empty());
2224 2225 2226 2227 2228
                            ieNode->net->setUnconnectedNodes(ieNode);
                        }
                    }
                    continue;
                }
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
            }
            ld.skip = true;  // Initially skip all Inference Engine supported layers.

            // Create a new network if one of inputs from different Inference Engine graph.
            std::vector<Ptr<BackendNode>> inputNodes;
            for (int i = 0; i < ld.inputBlobsId.size(); ++i)
            {
                // Layer_Test_ROIPooling.Accuracy has 2 inputs inpLD = 0, 0 -> has 4 inputNodes (input, rois, input, rois)
                if (inputNodes.size() == ld.inputBlobsId.size()) {
                    break;
                }
                LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
                Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
                if (!inpNode.empty())
                {
                     Ptr<InfEngineNgraphNode> ieInpNode = inpNode.dynamicCast<InfEngineNgraphNode>();
                     CV_Assert(!ieInpNode.empty()); CV_Assert(!ieInpNode->net.empty());
                     if (ieInpNode->net == net && !fused) {
                        inputNodes.push_back(inpNode);
                        continue;
                     }
                }

                if (net.empty()) {
2253
                    net = Ptr<InfEngineNgraphNet>(new InfEngineNgraphNet(*this));
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
                }

                if (!fused) {
                    std::vector<std::string> inputNames;
                    std::vector<cv::Mat> inputs;

                    auto curr_pos = inpLd.consumers.begin();
                    auto compare = [&ld] (const LayerPin& lp) { return lp.lid == ld.id; };
                    auto cons = curr_pos;
                    while ((cons = std::find_if(curr_pos, inpLd.consumers.end(), compare)) !=
                            inpLd.consumers.end()) {
                        int cons_inp = cons->oid;
                        Ptr<NgraphBackendWrapper> inpWrapper = inpLd.outputBlobsWrappers[cons_inp].
                                                                     dynamicCast<NgraphBackendWrapper>();
2268
                        CV_Assert(!inpWrapper.empty());
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
                        auto iter = std::find(inputNames.begin(), inputNames.end(),
                                              inpWrapper->dataPtr->getName());
                        if (iter == inputNames.end()) {
                            inputNames.push_back(inpWrapper->dataPtr->getName());
                            inputs.push_back(inpLd.outputBlobs[cons_inp]);
                        }
                        curr_pos = cons + 1;
                    }

                    auto inps = net->setInputs(inputs, inputNames);
                    for (auto& inp : inps) {
                        inputNodes.emplace_back(Ptr<BackendNode>(new InfEngineNgraphNode(inp)));
                    }
                }
            }

            Ptr<BackendNode> node;
            if (!net.empty())
            {
                if (fused)
                {
                    bool inPlace = ld.inputBlobsId.size() == 1 && ld.outputBlobs.size() == 1 &&
                                   ld.inputBlobs[0]->data == ld.outputBlobs[0].data;
                    CV_Assert(inPlace);
                    node = layers[ld.inputBlobsId[0].lid].backendNodes[preferableBackend];
                    ld.inputBlobsWrappers = layers[ld.inputBlobsId[0].lid].inputBlobsWrappers;
                }
            }
            else {
2298
                net = Ptr<InfEngineNgraphNet>(new InfEngineNgraphNet(*this));
2299 2300 2301 2302
            }

            if (!fused)
            {
2303 2304
                CV_Assert(ld.inputBlobsId.size() == inputNodes.size());
                for (int i = 0; i < ld.inputBlobsId.size(); ++i)
2305
                {
2306 2307 2308 2309 2310 2311 2312
                    int lid = ld.inputBlobsId[i].lid;
                    int oid = ld.inputBlobsId[i].oid;
                    if (oid == 0 || lid == 0)
                        continue;

                    auto ieInpNode = inputNodes[i].dynamicCast<InfEngineNgraphNode>();
                    CV_Assert(oid < ieInpNode->node->get_output_size());
2313 2314 2315
#if INF_ENGINE_VER_MAJOR_GT(INF_ENGINE_RELEASE_2020_4)
                    inputNodes[i] = Ptr<BackendNode>(new InfEngineNgraphNode(ieInpNode->node));
#elif INF_ENGINE_VER_MAJOR_GT(INF_ENGINE_RELEASE_2020_3)
2316 2317
                    inputNodes[i] = Ptr<BackendNode>(new InfEngineNgraphNode(ieInpNode->node->get_output_as_single_output_node(oid)));
#else
2318
                    inputNodes[i] = Ptr<BackendNode>(new InfEngineNgraphNode(ieInpNode->node->get_output_as_single_output_node(oid, false)));
2319
#endif
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
                }

                if (layer->supportBackend(preferableBackend))
                {
                    node = layer->initNgraph(ld.inputBlobsWrappers, inputNodes);
                    for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                    {
                        InferenceEngine::DataPtr dataPtr = ngraphDataNode(ld.outputBlobsWrappers[i]);
                        node.dynamicCast<InfEngineNgraphNode>()->setName(dataPtr->getName());
                    }
                }
                else
                {
                    node = Ptr<BackendNode>(new InfEngineNgraphNode(inputNodes,
                        ld.layerInstance, ld.inputBlobs, ld.outputBlobs, ld.internals));
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
                }
            }
            else if (node.empty())
                continue;

            ld.backendNodes[preferableBackend] = node;

            Ptr<InfEngineNgraphNode> ieNode = node.dynamicCast<InfEngineNgraphNode>();
            CV_Assert(!ieNode.empty());
            ieNode->net = net;

            if (ld.consumers.empty()) {
                // TF EAST_text_detection
                ieNode->net->setUnconnectedNodes(ieNode);
            }
2350 2351 2352 2353 2354 2355 2356 2357
            for (const auto& pin : blobsToKeep_)
            {
                if (pin.lid == ld.id)
                {
                    ieNode->net->addOutput(ieNode->node->get_friendly_name());
                    break;
                }
            }
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
            ieNode->net->setNodePtr(&ieNode->node);

            net->addBlobs(ld.inputBlobsWrappers);
            net->addBlobs(ld.outputBlobsWrappers);
            addNgraphOutputs(ld);
        }

        // Initialize all networks.
        for (MapIdToLayerData::reverse_iterator it = layers.rbegin(); it != layers.rend(); ++it)
        {
            LayerData &ld = it->second;
            auto iter = ld.backendNodes.find(preferableBackend);
            if (iter == ld.backendNodes.end())
                continue;

            Ptr<BackendNode>& node = iter->second;
            if (node.empty())
                continue;

            Ptr<InfEngineNgraphNode> ieNode = node.dynamicCast<InfEngineNgraphNode>();
            if (ieNode.empty())
                continue;

            CV_Assert(!ieNode->net.empty());

            if (!ieNode->net->isInitialized())
            {
                ieNode->net->setUnconnectedNodes(ieNode);
                ieNode->net->createNet((Target)preferableTarget);
                ld.skip = false;
            }
        }
2390
    }
2391
#endif  // HAVE_DNN_NGRAPH
2392

2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656
#ifdef HAVE_WEBNN
    void addWebnnOutputs(LayerData &ld)
    {
        CV_TRACE_FUNCTION();

        Ptr<WebnnNet> layerNet;
        auto it = ld.backendNodes.find(preferableBackend);
        if (it != ld.backendNodes.end())
        {
            Ptr<BackendNode> node = it->second;
            if (!node.empty())
            {
                Ptr<WebnnBackendNode> webnnNode = node.dynamicCast<WebnnBackendNode>();
                CV_Assert(!webnnNode.empty()); CV_Assert(!webnnNode->net.empty());
                layerNet = webnnNode->net;
            }
        }

        for (int i = 0; i < ld.inputBlobsId.size(); ++i)
        {
            LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
            Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
            if (!inpNode.empty())
            {
                Ptr<WebnnBackendNode> webnnInpNode = inpNode.dynamicCast<WebnnBackendNode>();
                CV_Assert(!webnnInpNode.empty()); CV_Assert(!webnnInpNode->net.empty());
                if (layerNet != webnnInpNode->net)
                {
                    webnnInpNode->net->addOutput(webnnInpNode->name);
                    webnnInpNode->net->setUnconnectedNodes(webnnInpNode);
                }
            }
        }
    }

    void initWebnnBackend(const std::vector<LayerPin>& blobsToKeep_)
    {
        CV_TRACE_FUNCTION();
        CV_Assert_N(preferableBackend == DNN_BACKEND_WEBNN, haveWebnn());

        MapIdToLayerData::iterator it;
        Ptr<WebnnNet> net;

        for (it = layers.begin(); it != layers.end(); ++it)
        {
            LayerData &ld = it->second;
            if (ld.id == 0)
            {
                CV_Assert((netInputLayer->outNames.empty() && ld.outputBlobsWrappers.size() == 1) ||
                          (netInputLayer->outNames.size() == ld.outputBlobsWrappers.size()));
                for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                {
                    Ptr<WebnnBackendWrapper> wrapper = ld.outputBlobsWrappers[i].dynamicCast<WebnnBackendWrapper>();
                    std::string outputName = netInputLayer->outNames.empty() ? ld.name : netInputLayer->outNames[i];
                    outputName = ld.outputBlobsWrappers.size() > 1 ? (outputName + "." + std::to_string(i)) : outputName;
                    wrapper->name = outputName;
                }
            }
            else
            {
                for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                {
                    Ptr<WebnnBackendWrapper> wrapper = ld.outputBlobsWrappers[i].dynamicCast<WebnnBackendWrapper>();
                    std::string outputName = ld.outputBlobsWrappers.size() > 1 ? (ld.name + "." + std::to_string(i)) : ld.name;
                    wrapper->name = outputName;
                }
            }
        }

        // Build WebNN networks from sets of layers that support this
        // backend. Split a whole model on several WebNN networks if
        // some of layers are not implemented.
        for (it = layers.begin(); it != layers.end(); ++it)
        {
            LayerData &ld = it->second;

            if (ld.id == 0 && ld.skip)
                continue;

            bool fused = ld.skip;
            Ptr<Layer> layer = ld.layerInstance;
            if (!fused && !layer->supportBackend(preferableBackend))
            {
                // For test use. when not using WebNN, the test case will fail
                // with the following code.
                CV_LOG_WARNING(NULL, "Layer " + ld.type + " name " + ld.name + " is unsupported by WebNN backend.");

                addWebnnOutputs(ld);
                net = Ptr<WebnnNet>();
                layer->preferableTarget = DNN_TARGET_CPU;

                for (int i = 0; i < ld.inputBlobsId.size(); ++i)
                {
                    LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
                    Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
                    if (!inpNode.empty()) {
                        Ptr<WebnnBackendNode> webnnNode = inpNode.dynamicCast<WebnnBackendNode>();
                        CV_Assert(!webnnNode.empty());
                        webnnNode->net->setUnconnectedNodes(webnnNode);
                    }
                }
                continue;
            }
            ld.skip = true; // Initially skip all WebNN supported layers.

            // Create a new network if one of inputs from different WebNN graph.
            std::vector<Ptr<BackendNode>> inputNodes;
            for (int i = 0; i < ld.inputBlobsId.size(); ++i)
            {
                // Layer_Test_ROIPooling.Accuracy has 2 inputs inpLD = 0, 0 -> has 4 inputNodes (input, rois, input, rois)
                if (inputNodes.size() == ld.inputBlobsId.size()) {
                    break;
                }
                LayerData &inpLd = layers[ld.inputBlobsId[i].lid];
                Ptr<BackendNode> inpNode = inpLd.backendNodes[preferableBackend];
                if (!inpNode.empty())
                {
                     Ptr<WebnnBackendNode> webnnInpNode = inpNode.dynamicCast<WebnnBackendNode>();
                     CV_Assert(!webnnInpNode.empty()); CV_Assert(!webnnInpNode->net.empty());
                     if (webnnInpNode->net == net && !fused) {
                        inputNodes.push_back(inpNode);
                        continue;
                     }
                }

                if (net.empty()) {
                    net = Ptr<WebnnNet>(new WebnnNet());
                }

                if (!fused) {
                    std::vector<std::string> inputNames;
                    std::vector<cv::Mat> inputs;

                    auto curr_pos = inpLd.consumers.begin();
                    auto compare = [&ld] (const LayerPin& lp) { return lp.lid == ld.id; };
                    auto cons = curr_pos;
                    while ((cons = std::find_if(curr_pos, inpLd.consumers.end(), compare)) !=
                            inpLd.consumers.end()) {
                        int cons_inp = cons->oid;
                        Ptr<WebnnBackendWrapper> inpWrapper = inpLd.outputBlobsWrappers[cons_inp].
                                                                     dynamicCast<WebnnBackendWrapper>();
                        CV_Assert(!inpWrapper.empty());
                        auto iter = std::find(inputNames.begin(), inputNames.end(),
                                              inpWrapper->name);
                        if (iter == inputNames.end()) {
                            inputNames.push_back(inpWrapper->name);
                            inputs.push_back(inpLd.outputBlobs[cons_inp]);
                        }
                        curr_pos = cons + 1;
                    }

                    auto inps = net->setInputs(inputs, inputNames);
                    for (auto& inp : inps) {
                        WebnnBackendNode* node = new WebnnBackendNode(inp);
                        node->net = net;
                        inputNodes.emplace_back(Ptr<BackendNode>(node));
                    }
                }
            }

            Ptr<BackendNode> node;
            if (!net.empty())
            {
                if (fused)
                {
                    bool inPlace = ld.inputBlobsId.size() == 1 && ld.outputBlobs.size() == 1 &&
                                   ld.inputBlobs[0]->data == ld.outputBlobs[0].data;
                    CV_Assert(inPlace);
                    node = layers[ld.inputBlobsId[0].lid].backendNodes[preferableBackend];
                    ld.inputBlobsWrappers = layers[ld.inputBlobsId[0].lid].inputBlobsWrappers;
                }
            }
            else {
                net = Ptr<WebnnNet>(new WebnnNet());
            }

            if (!fused)
            {
                CV_Assert(ld.inputBlobsId.size() == inputNodes.size());
                for (int i = 0; i < ld.inputBlobsId.size(); ++i)
                {
                    int lid = ld.inputBlobsId[i].lid;
                    int oid = ld.inputBlobsId[i].oid;
                    if (oid == 0 || lid == 0)
                        continue;

                    auto webnnInpNode = inputNodes[i].dynamicCast<WebnnBackendNode>();
                    inputNodes[i] = Ptr<BackendNode>(new WebnnBackendNode(webnnInpNode->operand));
                }

                if (layer->supportBackend(preferableBackend))
                {
                    if (ld.type == "Const") {
                        ml::Operand fake_operand;
                        Ptr<WebnnBackendNode> fake_input_node = Ptr<WebnnBackendNode>(new WebnnBackendNode(fake_operand));
                        fake_input_node->net = net;
                        inputNodes.push_back(fake_input_node);
                    }
                    node = layer->initWebnn(ld.inputBlobsWrappers, inputNodes);
                    for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                    {
                        Ptr<WebnnBackendWrapper> wrapper = ld.outputBlobsWrappers[i].dynamicCast<WebnnBackendWrapper>();
                        node.dynamicCast<WebnnBackendNode>()->name = wrapper->name;
                    }
                }
                else
                {
                    continue;
                }
            }
            else if (node.empty())
                continue;

            ld.backendNodes[preferableBackend] = node;

            Ptr<WebnnBackendNode> webnnNode = node.dynamicCast<WebnnBackendNode>();
            CV_Assert(!webnnNode.empty());
            webnnNode->net = net;

            if (ld.consumers.empty()) {
                // TF EAST_text_detection
                webnnNode->net->setUnconnectedNodes(webnnNode);
            }
            for (const auto& pin : blobsToKeep_)
            {
                if (pin.lid == ld.id)
                {
                    webnnNode->net->addOutput(webnnNode->name);
                    break;
                }
            }
            net->addBlobs(ld.inputBlobsWrappers);
            net->addBlobs(ld.outputBlobsWrappers);
            addWebnnOutputs(ld);
        }

        // Initialize all networks.
        for (MapIdToLayerData::reverse_iterator it = layers.rbegin(); it != layers.rend(); ++it)
        {
            LayerData &ld = it->second;
            auto iter = ld.backendNodes.find(preferableBackend);
            if (iter == ld.backendNodes.end())
                continue;

            Ptr<BackendNode>& node = iter->second;
            if (node.empty())
                continue;

            Ptr<WebnnBackendNode> webnnNode = node.dynamicCast<WebnnBackendNode>();
            if (webnnNode.empty())
                continue;

            CV_Assert(!webnnNode->net.empty());

            if (!webnnNode->net->isInitialized())
            {
                webnnNode->net->setUnconnectedNodes(webnnNode);
                webnnNode->net->createNet((Target)preferableTarget);
                ld.skip = false;
            }
        }
    }
#endif

2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
    void initVkComBackend()
    {
        CV_TRACE_FUNCTION();
        CV_Assert(preferableBackend == DNN_BACKEND_VKCOM);
#ifdef HAVE_VULKAN
        if (!haveVulkan())
            return;

        MapIdToLayerData::iterator it = layers.begin();
        for (; it != layers.end(); it++)
        {
            LayerData &ld = it->second;
            Ptr<Layer> layer = ld.layerInstance;
            if (!layer->supportBackend(preferableBackend))
            {
                continue;
            }

            ld.skip = false;

            try
            {
                ld.backendNodes[DNN_BACKEND_VKCOM] =
                    layer->initVkCom(ld.inputBlobsWrappers);
            }
            catch (const cv::Exception& e)
            {
                CV_LOG_ERROR(NULL, "initVkCom failed, fallback to CPU implementation. " << e.what());
                ld.backendNodes[DNN_BACKEND_VKCOM] = Ptr<BackendNode>();
            }
        }
#endif
2689 2690
    }

2691 2692
    void initCUDABackend(const std::vector<LayerPin>& blobsToKeep_)
    {
2693
        CV_Assert(haveCUDA());
2694
        CV_Assert(preferableBackend == DNN_BACKEND_CUDA);
2695 2696

#ifdef HAVE_CUDA
Y
YashasSamaga 已提交
2697 2698 2699
        if (!cudaInfo) /* we need to check only once */
            cuda4dnn::checkVersions();

2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
        if (cuda4dnn::getDeviceCount() <= 0)
            CV_Error(Error::StsError, "No CUDA capable device found.");

        if (cuda4dnn::getDevice() < 0)
            CV_Error(Error::StsError, "No CUDA capable device selected.");

        if (!cuda4dnn::isDeviceCompatible())
            CV_Error(Error::GpuNotSupported, "OpenCV was not built to work with the selected device. Please check CUDA_ARCH_PTX or CUDA_ARCH_BIN in your build configuration.");

        if (preferableTarget == DNN_TARGET_CUDA_FP16 && !cuda4dnn::doesDeviceSupportFP16())
Y
YashasSamaga 已提交
2710 2711 2712 2713
        {
            CV_LOG_WARNING(NULL, "The selected CUDA device does not support FP16 target; switching to FP32 target.");
            preferableTarget = DNN_TARGET_CUDA;
        }
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746

        if (!cudaInfo)
        {
            cuda4dnn::csl::CSLContext context;
            context.stream = cuda4dnn::csl::Stream(true);
            context.cublas_handle = cuda4dnn::csl::cublas::Handle(context.stream);
            context.cudnn_handle = cuda4dnn::csl::cudnn::Handle(context.stream);

            auto d2h_stream = cuda4dnn::csl::Stream(true); // stream for background D2H data transfers
            cudaInfo = std::unique_ptr<CudaInfo_t>(new CudaInfo_t(std::move(context), std::move(d2h_stream)));
        }

        cudaInfo->workspace = cuda4dnn::csl::Workspace(); // release workspace memory if any

        for (auto& layer : layers)
        {
            auto& ld = layer.second;
            if (ld.id == 0)
            {
                for (auto& wrapper : ld.inputBlobsWrappers)
                {
                    auto cudaWrapper = wrapper.dynamicCast<CUDABackendWrapper>();
                    cudaWrapper->setStream(cudaInfo->context.stream, cudaInfo->d2h_stream);
                }
            }

            for (auto& wrapper : ld.outputBlobsWrappers)
            {
                auto cudaWrapper = wrapper.dynamicCast<CUDABackendWrapper>();
                cudaWrapper->setStream(cudaInfo->context.stream, cudaInfo->d2h_stream);
            }
        }

2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
        for (auto& layer : layers)
        {
            auto& ld = layer.second;
            auto& layerInstance = ld.layerInstance;

            if (!layerInstance->supportBackend(DNN_BACKEND_CUDA))
            {
                std::ostringstream os;
                os << "CUDA backend will fallback to the CPU implementation for the layer \"" << ld.name
                   << "\" of type " << ld.type << '\n';
                CV_LOG_INFO(NULL, os.str().c_str());
                continue;
            }

            /* we make a copy so that `initCUDA` doesn't modify `cudaInfo->context` */
            auto context = cudaInfo->context;
            auto node = layerInstance->initCUDA(&context, ld.inputBlobsWrappers, ld.outputBlobsWrappers);
            ld.backendNodes[DNN_BACKEND_CUDA] = node;

            auto cudaNode = node.dynamicCast<CUDABackendNode>();
            cudaInfo->workspace.require(cudaNode->get_workspace_memory_in_bytes());
        }
2769 2770 2771 2772 2773 2774 2775 2776 2777

        if (blobsToKeep_.size() > 1)
        {
            for (const auto& pin : blobsToKeep_)
            {
                LayerData& ld = layers[pin.lid];
                ld.cudaD2HBackgroundTransfers.push_back(pin.oid);
            }
        }
2778 2779 2780
#endif
    }

2781 2782
    void allocateLayer(int lid, const LayersShapesMap& layersShapes)
    {
A
Alexander Alekhin 已提交
2783 2784
        CV_TRACE_FUNCTION();

2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818
        LayerData &ld = layers[lid];

        //already allocated
        if (ld.flag)
            return;

        size_t ninputs = ld.inputBlobsId.size();
#if 0
        printf("layer %s:", ld.name.c_str());
        for (size_t i = 0; i < ninputs; i++)
        {
            int inp_lid = ld.inputBlobsId[i].lid;
            LayerData &inp_ld = layers[inp_lid];
            int inp_outputs = (int)inp_ld.outputBlobs.size();
            std::cout << " " << inp_ld.name << "(" << inp_outputs;

            for( int j = 0; j < inp_outputs; j++ )
            {
                std::cout << (j == 0 ? ": " : ", ") << inp_ld.outputBlobs[j].size;
            }
            std::cout << ")";
        }
        printf("\n");
#endif

        //determine parent layers
        for (size_t i = 0; i < ninputs; i++)
            ld.inputLayersId.insert(ld.inputBlobsId[i].lid);

        //allocate parents
        for (set<int>::iterator i = ld.inputLayersId.begin(); i != ld.inputLayersId.end(); i++)
            allocateLayer(*i, layersShapes);

        //bind inputs
2819 2820 2821 2822 2823 2824 2825 2826
        if (ld.id == 0)  // DataLayer
        {
            ninputs = netInputLayer->inputsData.size();
            ld.inputBlobsWrappers.resize(ninputs);
            for (size_t i = 0; i < ninputs; i++)
                ld.inputBlobsWrappers[i] = wrap(netInputLayer->inputsData[i]);
        }
        else
2827
        {
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837
            ld.inputBlobs.resize(ninputs);
            ld.inputBlobsWrappers.resize(ninputs);
            for (size_t i = 0; i < ninputs; i++)
            {
                LayerPin from = ld.inputBlobsId[i];
                CV_Assert(from.valid());
                CV_DbgAssert(layers.count(from.lid) && (int)layers[from.lid].outputBlobs.size() > from.oid);
                ld.inputBlobs[i] = &layers[from.lid].outputBlobs[from.oid];
                ld.inputBlobsWrappers[i] = layers[from.lid].outputBlobsWrappers[from.oid];
            }
2838 2839 2840 2841 2842 2843
        }

        LayersShapesMap::const_iterator layerShapesIt = layersShapes.find(lid);

        CV_Assert(layerShapesIt != layersShapes.end());

2844 2845 2846
        if (preferableBackend == DNN_BACKEND_OPENCV && preferableTarget == DNN_TARGET_OPENCL_FP16 && ld.dtype == CV_32F)
            ld.dtype = CV_16S;

2847
        std::vector<LayerPin> pinsForInternalBlobs;
2848
        blobManager.allocateBlobsForLayer(ld, layerShapesIt->second, pinsForInternalBlobs);
2849 2850 2851
        ld.outputBlobsWrappers.resize(ld.outputBlobs.size());
        for (int i = 0; i < ld.outputBlobs.size(); ++i)
            ld.outputBlobsWrappers[i] = wrap(ld.outputBlobs[i]);
2852 2853 2854 2855

        /* CUDA backend has its own system for internal blobs; we don't need these */
        ld.internalBlobsWrappers.resize((preferableBackend == DNN_BACKEND_CUDA) ? 0 : ld.internals.size());
        for (int i = 0; i < ld.internalBlobsWrappers.size(); ++i)
2856
            ld.internalBlobsWrappers[i] = wrap(ld.internals[i]);
2857 2858 2859

        Ptr<Layer> layerPtr = ld.getLayerInstance();
        {
2860 2861 2862 2863 2864 2865
            std::vector<Mat> inps(ld.inputBlobs.size());
            for (int i = 0; i < ld.inputBlobs.size(); ++i)
            {
                inps[i] = *ld.inputBlobs[i];
            }
            layerPtr->finalize(inps, ld.outputBlobs);
2866
            layerPtr->preferableTarget = preferableTarget;
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884
#if 0
            std::cout << "\toutputs:";
            size_t noutputs = ld.outputBlobs.size();
            for (size_t j = 0; j < noutputs; j++)
            {
                std::cout << (j == 0 ? " " : ", ") << ld.outputBlobs[j].size;
            }
            std::cout << "\n";
#endif
        }

        // After allocation of layer, we decrease counters to it's input blobs.
        blobManager.releaseReferences(ld.inputBlobsId);
        blobManager.releaseReferences(pinsForInternalBlobs);

        ld.flag = 1;
    }

2885 2886 2887 2888 2889 2890
#if 0
#define printf_(args) printf args
#else
#define printf_(args)
#endif

2891 2892
    void fuseLayers(const std::vector<LayerPin>& blobsToKeep_)
    {
A
Alexander Alekhin 已提交
2893 2894
        CV_TRACE_FUNCTION();

2895
        if(!fusion || (preferableBackend != DNN_BACKEND_OPENCV &&
2896
                        preferableBackend != DNN_BACKEND_CUDA &&
2897 2898 2899 2900
                        preferableBackend != DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 &&
                        preferableBackend != DNN_BACKEND_INFERENCE_ENGINE_NGRAPH))
           return;

2901 2902 2903 2904 2905 2906 2907 2908 2909
        // scan through all the layers. If there is convolution layer followed by the activation layer,
        // we try to embed this activation into the convolution and disable separate execution of the activation
        std::set<LayerPin> pinsToKeep(blobsToKeep_.begin(),
                                      blobsToKeep_.end());
        MapIdToLayerData::iterator it;
        for (it = layers.begin(); it != layers.end(); it++)
        {
            int lid = it->first;
            LayerData& ld = layers[lid];
2910
            if( ld.skip )
2911
            {
2912
                printf_(("skipped %s: %s\n", ld.layerInstance->name.c_str(), ld.layerInstance->type.c_str()));
2913 2914
                continue;
            }
2915
            printf_(("analyzing %s: %s\n", ld.layerInstance->name.c_str(), ld.layerInstance->type.c_str()));
2916

2917 2918 2919 2920
            // the optimization #1. try to fuse batch norm, scaling and/or activation layers
            // with the current layer if they follow it. Normally, the are fused with the convolution layer,
            // but some of them (like activation) may be fused with fully-connected, elemwise (+) and
            // some other layers.
2921 2922
            Ptr<Layer>& currLayer = ld.layerInstance;
            if( ld.consumers.size() == 1 && pinsToKeep.count(LayerPin(lid, 0)) == 0 )
2923 2924 2925
            {
                LayerData* nextData = &layers[ld.consumers[0].lid];
                LayerPin lpNext(ld.consumers[0].lid, 0);
2926
                while (nextData)
2927
                {
2928 2929 2930 2931 2932
                    /* we use `tryFuse` member of convolution layer to fuse eltwise later
                     * it's not intended to be fused here; hence, we stop when we encounter eltwise
                     */
                    if (preferableBackend == DNN_BACKEND_CUDA && ld.type == "Convolution" && nextData->type == "Eltwise")
                        break;
2933 2934
                    Ptr<Layer> nextLayer = nextData->layerInstance;
                    if (currLayer->tryFuse(nextLayer))
2935
                    {
2936 2937
                        printf_(("\tfused with %s\n", nextLayer->name.c_str()));
                        nextData->skip = true;
2938 2939
                        ld.outputBlobs = layers[lpNext.lid].outputBlobs;
                        ld.outputBlobsWrappers = layers[lpNext.lid].outputBlobsWrappers;
2940
                        if (nextData->consumers.size() == 1)
A
Aleksandr Rybnikov 已提交
2941
                        {
2942 2943 2944
                            int nextLayerId = nextData->consumers[0].lid;
                            nextData = &layers[nextLayerId];
                            lpNext = LayerPin(nextLayerId, 0);
A
Aleksandr Rybnikov 已提交
2945
                        }
2946
                        else
A
Aleksandr Rybnikov 已提交
2947
                        {
2948 2949
                            nextData = 0;
                            break;
A
Aleksandr Rybnikov 已提交
2950
                        }
2951
                    }
2952 2953
                    else
                        break;
2954 2955
                }

2956
                if (preferableBackend != DNN_BACKEND_OPENCV && preferableBackend != DNN_BACKEND_CUDA)
2957 2958
                    continue;  // Go to the next layer.

2959 2960 2961 2962 2963 2964 2965
                // TODO: OpenCL target support more fusion styles.
                if ( preferableBackend == DNN_BACKEND_OPENCV && IS_DNN_OPENCL_TARGET(preferableTarget) &&
                     (!cv::ocl::useOpenCL() || (ld.layerInstance->type != "Convolution" &&
                     ld.layerInstance->type != "MVN" && ld.layerInstance->type != "Pooling" &&
                     ld.layerInstance->type != "Concat")) )
                    continue;

2966 2967 2968
                if (preferableBackend == DNN_BACKEND_CUDA && IS_DNN_CUDA_TARGET(preferableTarget)
                    && ld.layerInstance->type != "Convolution"
                    && ld.layerInstance->type != "Concat")
2969 2970
                    continue;

2971
                while (nextData)
2972
                {
2973 2974 2975 2976 2977 2978 2979 2980
                    // For now, OpenCL target support fusion with activation of ReLU/ChannelsPReLU/Power/Tanh
                    if (IS_DNN_OPENCL_TARGET(preferableTarget) &&
                        nextData->type != "ReLU" &&
                        nextData->type != "ChannelsPReLU" &&
                        nextData->type != "ReLU6" &&
                        nextData->type != "TanH" &&
                        nextData->type != "Power")
                        break;
W
Wu Zhiwen 已提交
2981

2982 2983 2984
                    Ptr<ActivationLayer> nextActivLayer = nextData->layerInstance.dynamicCast<ActivationLayer>();
                    if (nextActivLayer.empty())
                        break;
W
Wu Zhiwen 已提交
2985

2986
                    if (currLayer->setActivation(nextActivLayer))
W
Wu Zhiwen 已提交
2987 2988
                    {
                        printf_(("\tfused with %s\n", nextActivLayer->name.c_str()));
2989
                        nextData->skip = true;
2990 2991
                        ld.outputBlobs = layers[lpNext.lid].outputBlobs;
                        ld.outputBlobsWrappers = layers[lpNext.lid].outputBlobsWrappers;
2992
                        if (nextData->consumers.size() == 1)
2993
                        {
2994 2995 2996 2997 2998
                            int nextLayerId = nextData->consumers[0].lid;
                            nextData = &layers[nextLayerId];
                            lpNext = LayerPin(nextLayerId, 0);
                        }
                        else
2999
                        {
3000 3001
                            nextData = 0;
                            break;
3002 3003
                        }
                    }
3004 3005
                    else
                        break;
3006 3007
                }

3008 3009
                // OpenCL: fuse convolution layer followed by eltwise + relu
                // CUDA: fuse convolution layer followed by eltwise (and optional activation)
3010 3011 3012 3013
                while (nextData &&
                    (IS_DNN_OPENCL_TARGET(preferableTarget) || IS_DNN_CUDA_TARGET(preferableTarget)) &&
                    ld.layerInstance->type == "Convolution"
                )  // semantic of 'if'
3014
                {
3015 3016 3017 3018
                    Ptr<EltwiseLayer> nextEltwiseLayer = nextData->layerInstance.dynamicCast<EltwiseLayer>();
                    if (nextEltwiseLayer.empty())
                        break;

3019 3020 3021 3022 3023
#ifdef HAVE_CUDA
                    // CUDA backend supports fusion with eltwise sum (without variable channels)
                    if (IS_DNN_CUDA_TARGET(preferableTarget) && !nextEltwiseLayer.empty())
                    {
                        // we create a temporary backend node for eltwise layer to obtain the eltwise configuration
3024
                        cuda4dnn::csl::CSLContext context; // assume that initCUDA and EltwiseOp do not use the context during init
3025
                        const auto node = nextData->layerInstance->initCUDA(&context, nextData->inputBlobsWrappers, nextData->outputBlobsWrappers);
Y
YashasSamaga 已提交
3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038
                        auto eltwiseNode = node.dynamicCast<cuda4dnn::EltwiseOpBase>();

                        // broadcasting not supported in fused ops
                        auto required_shape = shape(nextData->outputBlobs[0]);
                        for (int i = 0; i < nextData->inputBlobs.size(); i++)
                        {
                            if (shape(*nextData->inputBlobs[i]) != required_shape)
                            {
                                eltwiseNode.reset();
                                break;
                            }
                        }

3039 3040 3041
                        // CUDA backend uses EltwiseOp when all operands have the same number of channels; otherwise, ShortcutOp is used.
                        // Hence, a successful cast to EltwiseOp implies that the number of channels is same in all operand tensors.
                        if (eltwiseNode.empty() || eltwiseNode->op != cuda4dnn::EltwiseOpType::SUM || !eltwiseNode->coeffs.empty())
3042
                            break;
3043 3044
                    }
#endif
3045

3046
                    if (IS_DNN_OPENCL_TARGET(preferableTarget) && pinsToKeep.count(lpNext) != 0)
3047 3048 3049 3050
                        break;
                    if (nextData->inputBlobsId.size() != 2)
                        break;

3051
                    if (IS_DNN_OPENCL_TARGET(preferableTarget))
3052
                    {
3053
                        if (!nextData->params.has("operation") || toLowerCase(nextData->params.get<String>("operation")) == "sum")
3054
                        {
3055
                            if (nextData->params.has("coeff"))
3056
                            {
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
                                DictValue paramCoeff = nextData->params.get("coeff");
                                int n = paramCoeff.size();
                                bool isCoeffOneOne = (n == 2);
                                for (int i = 0; isCoeffOneOne && i < n; i++)
                                {
                                    float c = paramCoeff.get<float>(i);
                                    isCoeffOneOne &= (c == 1.0f);
                                }
                                if (!isCoeffOneOne)
                                {
                                    CV_LOG_DEBUG(NULL, "DNN/OpenCL: fusion of 'Sum' without coeffs (or {1.0, 1.0}) is supported only");
                                    break;
                                }
3070 3071
                            }
                        }
3072 3073 3074 3075 3076
                        else
                        {
                            CV_LOG_DEBUG(NULL, "DNN/OpenCL: fusion with eltwise operation is not supported: " << nextData->params.get<String>("operation"));
                            break;
                        }
3077
                    }
3078 3079 3080 3081

                    {
                        LayerData *eltwiseData = nextData;

3082 3083 3084 3085
                        // Eltwise layer has two inputs. We need to determine which
                        // is a base convolution layer and which could be used as it's bias.
                        LayerData* biasLayerData = 0;
                        for (int i = 0; i < 2; ++i)
3086
                        {
3087 3088
                            LayerData *downLayerData = &layers[eltwiseData->inputBlobsId[i].lid];
                            CV_Assert(downLayerData);
3089
                            while (downLayerData->skip)
3090
                            {
3091
                                if (downLayerData->inputBlobsId.size() == 1)
3092
                                    downLayerData = &layers[downLayerData->inputBlobsId[0].lid];
3093 3094 3095 3096 3097
                                else
                                {
                                    downLayerData = 0;
                                    break;
                                }
3098
                            }
3099 3100 3101 3102 3103 3104 3105 3106
                            if (downLayerData && ld.id == downLayerData->id)
                            {
                                biasLayerData = &layers[eltwiseData->inputBlobsId[1 - i].lid];
                                break;
                            }
                        }
                        CV_Assert(biasLayerData);
                        {
3107 3108 3109
                            // fuse eltwise + activation layer
                            // bias must already be computed to fuse => bias layer must appear before convolution
                            if (biasLayerData->id < ld.id)
3110
                            {
3111 3112 3113 3114 3115 3116 3117
                                /* we can fuse activation if:
                                 * => activation layer that follows is the only consumer of eltwise output
                                 * => activation layer does not process multiple inputs
                                 * => we do not require to keep the output of eltwise
                                 */
                                Ptr<ActivationLayer> nextFusabeleActivLayer;
                                if (eltwiseData->consumers.size() == 1 && pinsToKeep.count(lpNext) == 0)
3118 3119 3120
                                {
                                    nextData = &layers[eltwiseData->consumers[0].lid];
                                    lpNext = LayerPin(eltwiseData->consumers[0].lid, 0);
3121 3122
                                    CV_Assert(nextData);
                                    if (nextData->outputBlobs.size() == 1)
3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
                                        nextFusabeleActivLayer = nextData->layerInstance.dynamicCast<ActivationLayer>();
                                }
                                else
                                {
                                    // OCL backend cannot fuse in this case but the CUDA backend can continue with just eltwise
                                    nextData = 0;
                                }

                                // the requirements of OCV OpenCL backend and CUDA backend are different
                                // we need to check them separately; hence, the fuse variables
                                bool fuse_eltwise = false, fuse_activation = false;

3135
                                Ptr<PowerLayer> activ_power;
3136
                                if (IS_DNN_OPENCL_TARGET(preferableTarget) && !nextFusabeleActivLayer.empty() &&
3137
                                    nextData &&
3138 3139
                                    (!nextData->type.compare("ReLU") ||
                                     !nextData->type.compare("ChannelsPReLU") ||
3140 3141
                                     (!nextData->type.compare("Power") && (activ_power = nextFusabeleActivLayer.dynamicCast<PowerLayer>()) && activ_power->scale == 1.0f)
                                    ) &&
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
                                    currLayer->setActivation(nextFusabeleActivLayer))
                                {
                                    fuse_eltwise = true;
                                    fuse_activation = true;
                                }

                                if (IS_DNN_CUDA_TARGET(preferableTarget))
                                {
                                    /* supported fusion options:
                                     * => convolution + eltwise
                                     * => activation(convolution) + eltwise
                                     *    > convolution + activation would have been fused already; we have to fuse eltwise
                                     * => activation(convolution + eltwise)
                                     *    > fuse eltwise and then activation
                                     */
                                    auto layer = nextEltwiseLayer.staticCast<Layer>();
                                    if (currLayer->tryFuse(layer))
                                    {
                                        fuse_eltwise = true; /* eltwise was successfully fused */
3161
                                        if (!nextFusabeleActivLayer.empty() && nextData)
3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181
                                        {
                                            if ((!nextData->type.compare("ReLU") ||
                                                 !nextData->type.compare("ReLU6") ||
                                                 !nextData->type.compare("Power") ||
                                                 !nextData->type.compare("TanH") ||
                                                 !nextData->type.compare("Sigmoid") ||
                                                 !nextData->type.compare("Swish") ||
                                                 !nextData->type.compare("Mish")) &&
                                                currLayer->setActivation(nextFusabeleActivLayer))
                                            {
                                                // activation was fused
                                                fuse_activation = true;
                                            }
                                        }
                                    }
                                }

                                CV_Assert(!fuse_activation || fuse_eltwise); /* cannot fuse activation without eltwise */
                                if(fuse_eltwise && fuse_activation)
                                {
3182
                                    CV_Assert(nextData);
3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
                                    CV_Assert_N(biasLayerData->outputBlobsWrappers.size() == 1, ld.inputBlobsWrappers.size() == 1);
                                    ld.inputBlobsWrappers.push_back(biasLayerData->outputBlobsWrappers[0]);
                                    printf_(("\tfused with %s\n", nextEltwiseLayer->name.c_str()));
                                    printf_(("\tfused with %s\n", nextFusabeleActivLayer->name.c_str()));
                                    eltwiseData->skip = true;
                                    nextData->skip = true;
                                    // This optimization for cases like
                                    // some_layer   conv
                                    //   |             |
                                    //   +-- eltwise --+
                                    //          |
                                    //        activ
                                    // This way all the element-wise computations
                                    // (i.e. some_layer+conv or some_layer*conv)
                                    // would be done at [conv] layer. So we need to
                                    // replace [conv]'s output blob to [eltwise]'s one
                                    // considering that [activ] is an in-place layer.
                                    // Also we need to move all the consumers' references.
                                    // To prevent memory collisions (i.e. when input of
                                    // [conv] and output of [eltwise] is the same blob)
                                    // we allocate a new blob.
                                    CV_Assert_N(ld.outputBlobs.size() == 1, ld.outputBlobsWrappers.size() == 1);
                                    ld.outputBlobs[0] = ld.outputBlobs[0].clone();
                                    ld.outputBlobsWrappers[0] = wrap(ld.outputBlobs[0]);

                                    eltwiseData->outputBlobs = ld.outputBlobs;
                                    nextData->outputBlobs = ld.outputBlobs;
                                    eltwiseData->outputBlobsWrappers = ld.outputBlobsWrappers;
                                    nextData->outputBlobsWrappers = ld.outputBlobsWrappers;

                                    // Move references of [activ] layer consumers to the newly allocated blob.
                                    for (int i = 0; i < nextData->consumers.size(); ++i)
                                    {
                                        LayerData& consumer = layers[nextData->consumers[i].lid];
                                        for (int j = 0; j < consumer.inputBlobsId.size(); ++j)
                                        {
                                            if (consumer.inputBlobsId[j].lid == lpNext.lid)
                                            {
                                                consumer.inputBlobs[j] = &ld.outputBlobs[0];
                                                consumer.inputBlobsWrappers[j] = ld.outputBlobsWrappers[0];
                                                break;
                                            }
                                        }
                                    }
                                }
                                else if (fuse_eltwise) // conv + eltwise (note: conv could have fused activations before eltwise)
                                {
                                    CV_Assert(IS_DNN_CUDA_TARGET(preferableTarget));
                                    CV_Assert_N(biasLayerData->outputBlobsWrappers.size() == 1, ld.inputBlobsWrappers.size() == 1);
                                    ld.inputBlobsWrappers.push_back(biasLayerData->outputBlobsWrappers[0]);
                                    printf_(("\tfused with %s\n", nextEltwiseLayer->name.c_str()));
                                    eltwiseData->skip = true;
                                    // This optimization is for cases like
                                    // some_layer   conv (maybe fused with activ)
                                    //   |             |
                                    //   +-- eltwise --+
                                    //
                                    // This way all the element-wise computations
                                    // (i.e. some_layer+conv or some_layer*conv)
                                    // would be done at [conv] layer. So we need to
                                    // replace [conv]'s output blob to [eltwise]'s one.
                                    // Also we need to move all the consumers' references.
                                    // To prevent memory collisions (i.e. when input of
                                    // [conv] and output of [eltwise] is the same blob)
                                    // we allocate a new blob.
                                    CV_Assert_N(ld.outputBlobs.size() == 1, ld.outputBlobsWrappers.size() == 1);
                                    ld.outputBlobs[0] = ld.outputBlobs[0].clone();
                                    ld.outputBlobsWrappers[0] = wrap(ld.outputBlobs[0]);

                                    eltwiseData->outputBlobs = ld.outputBlobs;
                                    eltwiseData->outputBlobsWrappers = ld.outputBlobsWrappers;

                                    // Move references of [eltwise] layer consumers to the newly allocated blob.
                                    for (int i = 0; i < eltwiseData->consumers.size(); ++i)
3257
                                    {
3258 3259
                                        LayerData& consumer = layers[eltwiseData->consumers[i].lid];
                                        for (int j = 0; j < consumer.inputBlobsId.size(); ++j)
3260
                                        {
3261
                                            if (consumer.inputBlobsId[j].lid == eltwiseData->id)
3262
                                            {
3263 3264 3265
                                                consumer.inputBlobs[j] = &ld.outputBlobs[0];
                                                consumer.inputBlobsWrappers[j] = ld.outputBlobsWrappers[0];
                                                break;
3266 3267
                                            }
                                        }
3268 3269 3270 3271
                                    }
                                }
                            }
                        }
W
Wu Zhiwen 已提交
3272
                    }
3273 3274

                    break;
3275 3276
                }
            }
3277

3278
            if (preferableBackend != DNN_BACKEND_OPENCV && preferableBackend != DNN_BACKEND_CUDA)
3279 3280
                continue;  // Go to the next layer.

3281
            // the optimization #2. if there is concat layer that concatenates channels
3282
            // from the inputs together (i.e. axis == 1) then we make the inputs of
K
Kuang Fangjun 已提交
3283
            // the concat layer to write to the concatenation output buffer
3284 3285 3286
            // (and so we eliminate the concatenation layer, because the channels
            // are concatenated implicitly).
            Ptr<ConcatLayer> concatLayer = ld.layerInstance.dynamicCast<ConcatLayer>();
Y
YashasSamaga 已提交
3287
            if( !concatLayer.empty() && !concatLayer->padding && ld.outputBlobs.size() == 1 )
3288 3289
            {
                Mat& output = ld.outputBlobs[0];
3290
                UMat umat_output;
3291
#ifdef HAVE_OPENCL
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
                if (!ld.outputBlobsWrappers.empty() &&
                    (preferableBackend == DNN_BACKEND_OPENCV && IS_DNN_OPENCL_TARGET(preferableTarget)))
                {
                    size_t i, ninputs = ld.inputBlobsId.size();
                    bool conv_layer = true;
                    for( i = 0; i < ninputs; i++ )
                    {
                        LayerPin pin = ld.inputBlobsId[i];
                        LayerData* inp_i_data = &layers[pin.lid];
                        while(inp_i_data->skip &&
                              inp_i_data->inputBlobsId.size() == 1 &&
                              inp_i_data->consumers.size() == 1)
                        {
                            pin = inp_i_data->inputBlobsId[0];
                            inp_i_data = &layers[pin.lid];
                        }
                        conv_layer = conv_layer && (inp_i_data->getLayerInstance()->type == "Convolution");
                    }
                    if (!conv_layer)
                        continue;
                    std::vector<UMat> umat_outputBlobs;
                    umat_outputBlobs = OpenCLBackendWrapper::getUMatVector(ld.outputBlobsWrappers);
                    umat_output = umat_outputBlobs[0];
                }
3316
#endif
3317 3318 3319 3320 3321 3322 3323

                // TODO: in general, this optimization can always be done, but
                // many layers currently check that the input/output blobs are
                // continuous arrays. Unfortunately, this is not true when
                // the concatenation optimization is applied with batch_size > 1.
                // so, for now, we only apply this optimization in the most popular
                // case batch_size == 1.
3324
                int axis = normalize_axis(concatLayer->axis, output.dims);
Y
YashasSamaga 已提交
3325
                if( output.total(0, axis) == 1 )
3326 3327 3328 3329 3330 3331 3332
                {
                    size_t i, ninputs = ld.inputBlobsId.size();
                    std::vector<LayerPin> realinputs(ninputs);
                    for( i = 0; i < ninputs; i++ )
                    {
                        LayerPin pin = ld.inputBlobsId[i];
                        LayerData* inp_i_data = &layers[pin.lid];
3333
                        while(inp_i_data->skip &&
D
Dmitry Kurtaev 已提交
3334 3335
                              inp_i_data->inputBlobsId.size() == 1 &&
                              inp_i_data->consumers.size() == 1)
3336 3337 3338 3339 3340 3341 3342 3343
                        {
                            pin = inp_i_data->inputBlobsId[0];
                            inp_i_data = &layers[pin.lid];
                        }
                        printf_(("\treal input for %s is %s\n",
                               layers[ld.inputBlobsId[i].lid].getLayerInstance()->name.c_str(),
                               inp_i_data->getLayerInstance()->name.c_str()));

3344
                        if(inp_i_data->skip || inp_i_data->consumers.size() != 1)
3345
                            break;
3346 3347 3348 3349
#ifdef HAVE_CUDA
                        if (preferableBackend == DNN_BACKEND_CUDA &&
                            (inp_i_data->layerInstance->supportBackend(DNN_BACKEND_CUDA) == false ||
                             (inp_i_data->layerInstance->type != "Convolution" &&
3350 3351 3352 3353 3354 3355 3356
                              inp_i_data->layerInstance->type != "Pooling" &&
                              inp_i_data->layerInstance->type != "Resize"  &&
                              inp_i_data->layerInstance->type != "Flatten" &&
                              inp_i_data->layerInstance->type != "Permute" &&
                              inp_i_data->layerInstance->type != "Reorg" &&
                              inp_i_data->layerInstance->type != "Eltwise" &&
                              inp_i_data->layerInstance.dynamicCast<ActivationLayer>().empty())))
3357 3358 3359 3360
                        {
                            break;
                        }
#endif
3361 3362 3363 3364 3365
                        realinputs[i] = pin;
                    }

                    if( i >= ninputs )
                    {
3366 3367 3368
                        // Allocate new memory to prevent collisions during memory
                        // reusing (see https://github.com/opencv/opencv/pull/10456).
                        output = output.clone();
3369
#ifdef HAVE_OPENCL
3370 3371 3372 3373 3374 3375 3376 3377
                        if (preferableBackend == DNN_BACKEND_OPENCV &&
                            IS_DNN_OPENCL_TARGET(preferableTarget))
                        {
                            std::vector<UMat> umats(1);
                            umat_output = umat_output.clone();
                            umats[0] = umat_output;
                            OpenCLBackendWrapper::update(ld.outputBlobsWrappers, umats);
                        }
3378
#endif
3379

3380 3381 3382
#ifdef HAVE_CUDA
                        if (preferableBackend == DNN_BACKEND_CUDA)
                            ld.outputBlobsWrappers[0] = wrap(output);
3383
#endif
Y
YashasSamaga 已提交
3384
                        std::vector<Range> chrange(output.dims, Range::all());
3385 3386 3387 3388 3389
                        int ofs = 0;
                        for( i = 0; i < ninputs; i++ )
                        {
                            LayerPin pin = realinputs[i];
                            LayerData* inp_i_data = &layers[pin.lid];
Y
YashasSamaga 已提交
3390 3391
                            int channels_i = ld.inputBlobs[i]->size[axis];
                            chrange[axis] = Range(ofs, ofs + channels_i);
3392 3393 3394 3395 3396 3397
                            printf_(("\toutput %s(%d) to channels (%d, %d)\n", inp_i_data->layerInstance->name.c_str(),
                                   pin.oid, ofs, ofs + channels_i));
                            ofs += channels_i;
                            Mat output_slice = output(chrange);
                            Mat& curr_output = inp_i_data->outputBlobs[pin.oid];
                            CV_Assert(output_slice.isContinuous() && output_slice.size == curr_output.size);
D
Dmitry Kurtaev 已提交
3398
                            Mat* oldPtr = &curr_output;
3399
                            curr_output = output_slice;
3400
#ifdef HAVE_OPENCL
3401 3402 3403 3404 3405 3406
                            if (preferableBackend == DNN_BACKEND_OPENCV && IS_DNN_OPENCL_TARGET(preferableTarget))
                            {
                                std::vector<UMat> umats(inp_i_data->outputBlobsWrappers.size());
                                umats[pin.oid] = umat_output(chrange);
                                OpenCLBackendWrapper::update(inp_i_data->outputBlobsWrappers, umats);
                            }
3407 3408 3409 3410 3411
#endif
#ifdef HAVE_CUDA
                            if (preferableBackend == DNN_BACKEND_CUDA)
                            {
                                auto cuda_wrapper = wrap(output).dynamicCast<CUDABackendWrapper>();
Y
YashasSamaga 已提交
3412 3413 3414
                                auto offset = chrange[axis].start * output_slice.total(axis + 1, output.dims);
                                auto new_shape = shape(output_slice);
                                cuda_wrapper->update(new_shape, offset);
3415 3416
                                inp_i_data->outputBlobsWrappers[pin.oid] = cuda_wrapper.staticCast<BackendWrapper>();
                            }
3417
#endif
D
Dmitry Kurtaev 已提交
3418 3419
                            // Layers that refer old input Mat will refer to the
                            // new data but the same Mat object.
3420
                            CV_Assert_N(curr_output.data == output_slice.data, oldPtr == &curr_output);
3421
                        }
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440

#ifdef HAVE_CUDA
                        if (preferableBackend == DNN_BACKEND_CUDA)
                        {
                            for (int i = 0; i < ld.consumers.size(); i++)
                            {
                                LayerData& consumer = layers[ld.consumers[i].lid];
                                for (int j = 0; j < consumer.inputBlobsId.size(); j++)
                                {
                                    if (consumer.inputBlobsId[j].lid == ld.id)
                                    {
                                        CV_Assert(consumer.inputBlobs[j]->data == ld.outputBlobs[0].data);
                                        consumer.inputBlobsWrappers[j] = ld.outputBlobsWrappers[0];
                                        break;
                                    }
                                }
                            }
                        }
#endif
3441
                        ld.skip = true;
3442 3443
                        printf_(("\toptimized out Concat layer %s\n", concatLayer->name.c_str()));
                    }
3444
                }
3445 3446 3447 3448 3449 3450
            }
        }
    }

    void allocateLayers(const std::vector<LayerPin>& blobsToKeep_)
    {
A
Alexander Alekhin 已提交
3451 3452
        CV_TRACE_FUNCTION();

3453 3454 3455 3456 3457 3458 3459 3460
        MapIdToLayerData::iterator it;
        for (it = layers.begin(); it != layers.end(); it++)
            it->second.flag = 0;

        CV_Assert(!layers[0].outputBlobs.empty());
        ShapesVec inputShapes;
        for(int i = 0; i < layers[0].outputBlobs.size(); i++)
        {
3461 3462 3463
            Mat& inp = layers[0].outputBlobs[i];
            CV_Assert(inp.total());
            if (preferableBackend == DNN_BACKEND_OPENCV &&
3464 3465
                preferableTarget == DNN_TARGET_OPENCL_FP16 &&
                layers[0].dtype == CV_32F)
L
Li Peng 已提交
3466
            {
3467
                layers[0].outputBlobs[i].create(inp.dims, inp.size, CV_16S);
L
Li Peng 已提交
3468
            }
3469
            inputShapes.push_back(shape(inp));
3470 3471 3472 3473 3474
        }
        LayersShapesMap layersShapes;
        getLayersShapes(inputShapes, layersShapes);

        blobManager.reset();
3475
        backendWrappers.clear();
3476 3477 3478 3479 3480 3481 3482 3483 3484

        for(auto& layer : layers)
        {
            auto& ld = layer.second;
            ld.inputBlobsWrappers.clear();
            ld.outputBlobsWrappers.clear();
            ld.internalBlobsWrappers.clear();
        }

3485 3486 3487
        // Fake references to input blobs.
        for (int i = 0; i < layers[0].outputBlobs.size(); ++i)
            blobManager.addReference(LayerPin(0, i));
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
        for (it = layers.begin(); it != layers.end(); ++it)
        {
            const LayerData& ld = it->second;
            blobManager.addReferences(ld.inputBlobsId);
        }

        for (int i = 0; i < blobsToKeep_.size(); i++)
        {
            blobManager.addReference(blobsToKeep_[i]);
        }

        for (it = layers.begin(); it != layers.end(); it++)
        {
            int lid = it->first;
            allocateLayer(lid, layersShapes);
        }

3505
        layersTimings.resize(lastLayerId + 1, 0);
3506 3507 3508 3509 3510
        fuseLayers(blobsToKeep_);
    }

    void forwardLayer(LayerData &ld)
    {
A
Alexander Alekhin 已提交
3511 3512
        CV_TRACE_FUNCTION();

3513 3514
        Ptr<Layer> layer = ld.layerInstance;

3515
        if( !ld.skip )
3516
        {
3517 3518 3519
            TickMeter tm;
            tm.start();

3520 3521
            std::map<int, Ptr<BackendNode> >::iterator it = ld.backendNodes.find(preferableBackend);
            if (preferableBackend == DNN_BACKEND_OPENCV || it == ld.backendNodes.end() || it->second.empty())
3522
            {
3523 3524 3525
                if (isAsync)
                    CV_Error(Error::StsNotImplemented, "Default implementation fallbacks in asynchronous mode");

3526 3527 3528 3529
                if (!layer->supportBackend(DNN_BACKEND_OPENCV))
                    CV_Error(Error::StsNotImplemented, format("Layer \"%s\" of type \"%s\" unsupported on OpenCV backend",
                                                       ld.name.c_str(), ld.type.c_str()));

3530
#ifdef HAVE_OPENCL
3531
                if (preferableBackend == DNN_BACKEND_OPENCV && IS_DNN_OPENCL_TARGET(preferableTarget))
3532
                {
3533
                    std::vector<UMat> umat_inputBlobs = OpenCLBackendWrapper::getUMatVector(ld.inputBlobsWrappers);
3534
                    std::vector<UMat> umat_outputBlobs = OpenCLBackendWrapper::getUMatVector(ld.outputBlobsWrappers);
3535 3536
                    std::vector<UMat> umat_internalBlobs = OpenCLBackendWrapper::getUMatVector(ld.internalBlobsWrappers);
                    layer->forward(umat_inputBlobs,
3537
                                   umat_outputBlobs,
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601
                                   umat_internalBlobs);
                    if (DNN_CHECK_NAN_INF)
                    {
                        bool fail = false;
                        for (size_t i = 0; i < umat_outputBlobs.size(); ++i)
                        {
                            UMat& u = umat_outputBlobs[i];
                            Mat m;
                            if (u.depth() == CV_16S) // FP16
                                convertFp16(u, m);
                            else
                                m = u.getMat(ACCESS_READ);
                            if (!checkRange(m))
                            {
                                std::cerr << "WARNING: NaN detected in layer output: id=" << ld.id << " name=" << layer->name << std::endl;
                                std::cerr << "output id=" << i << " output shape=" << shape(m) << std::endl;
                                fail = true;
                            }
                            else if (!checkRange(m, true, NULL, -1e6, 1e6))
                            {
                                std::cerr << "WARNING: Inf detected in layer output: id=" << ld.id << " name=" << layer->name << std::endl;
                                std::cerr << "output id=" << i << " output shape=" << shape(m) << std::endl;
                                fail = true;
                            }
                        }
                        if (fail)
                        {
                            for (size_t i = 0; i < umat_inputBlobs.size(); ++i)
                            {
                                UMat& u = umat_inputBlobs[i];
                                Mat m;
                                if (u.depth() == CV_16S) // FP16
                                    convertFp16(u, m);
                                else
                                    m = u.getMat(ACCESS_READ);
                                std::cout << "INPUT " << i << " " << cv::typeToString(u.type()) << " " << shape(m) << std::endl;
                                if (DNN_CHECK_NAN_INF_DUMP) std::cout << m.reshape(1, 1) << std::endl;
                            }
                            for (size_t i = 0; i < umat_outputBlobs.size(); ++i)
                            {
                                UMat& u = umat_outputBlobs[i];
                                Mat m;
                                if (u.depth() == CV_16S) // FP16
                                    convertFp16(u, m);
                                else
                                    m = u.getMat(ACCESS_READ);
                                std::cout << "OUTPUT " << i << " " << cv::typeToString(u.type()) << " " << shape(m) << std::endl;
                                if (DNN_CHECK_NAN_INF_DUMP) std::cout << m.reshape(1, 1) << std::endl;
                            }
                            for (size_t i = 0; i < umat_internalBlobs.size(); ++i)
                            {
                                UMat& u = umat_internalBlobs[i];
                                Mat m;
                                if (u.depth() == CV_16S) // FP16
                                    convertFp16(u, m);
                                else
                                    m = u.getMat(ACCESS_READ);
                                std::cout << "INTERNAL " << i << " " << shape(m) << std::endl;
                                if (DNN_CHECK_NAN_INF_DUMP) std::cout << cv::typeToString(u.type()) << " " << m.reshape(1, 1) << std::endl;
                            }
                            if (DNN_CHECK_NAN_INF_RAISE_ERROR)
                                CV_Assert(!fail);
                        }
                    }
3602
                    OpenCLBackendWrapper::update(ld.outputBlobsWrappers, umat_outputBlobs);
3603
                }
L
Li Peng 已提交
3604
                else
3605
#endif
3606
                {
3607 3608 3609 3610 3611 3612
                    for (int i = 0, n = ld.inputBlobsWrappers.size(); i < n; ++i)
                    {
                        if (!ld.inputBlobsWrappers[i].empty())
                            ld.inputBlobsWrappers[i]->copyToHost();
                    }

3613 3614 3615 3616 3617 3618
                    std::vector<Mat> inps(ld.inputBlobs.size());
                    for (int i = 0; i < ld.inputBlobs.size(); ++i)
                    {
                        inps[i] = *ld.inputBlobs[i];
                    }
                    layer->forward(inps, ld.outputBlobs, ld.internals);
3619

3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
                    if (DNN_CHECK_NAN_INF)
                    {
                        bool fail = false;
                        for (size_t i = 0; i < ld.outputBlobs.size(); ++i)
                        {
                            const Mat& m = ld.outputBlobs[i];
                            if (!checkRange(m))
                            {
                                std::cerr << "WARNING: NaN detected in layer output: id=" << ld.id << " name=" << layer->name << std::endl;
                                std::cerr << "output id=" << i << " output shape=" << shape(m) << std::endl;
                                fail = true;
                            }
                            else if (!checkRange(m, true, NULL, -1e6, 1e6))
                            {
                                std::cerr << "WARNING: Inf detected in layer output: id=" << ld.id << " name=" << layer->name << std::endl;
                                std::cerr << "output id=" << i << " output shape=" << shape(m) << std::endl;
                                fail = true;
                            }
                        }
                        if (fail)
                        {
                            for (size_t i = 0; i < ld.inputBlobs.size(); ++i)
                            {
                                const Mat* pM = ld.inputBlobs[i];
                                if (!pM)
                                {
                                    std::cout << "INPUT " << i << " is NULL" << std::endl;
                                    continue;
                                }
                                const Mat& m = *pM;
                                std::cout << "INPUT " << i << " " << cv::typeToString(m.type()) << " " << shape(m) << std::endl;
                                if (DNN_CHECK_NAN_INF_DUMP) std::cout << m.reshape(1, 1) << std::endl;
                            }
                            for (size_t i = 0; i < ld.outputBlobs.size(); ++i)
                            {
                                const Mat& m = ld.outputBlobs[i];
                                std::cout << "OUTPUT " << i << " " << cv::typeToString(m.type()) << " " << shape(m) << std::endl;
                                if (DNN_CHECK_NAN_INF_DUMP) std::cout << m.reshape(1, 1) << std::endl;
                            }
                            for (size_t i = 0; i < ld.internals.size(); ++i)
                            {
                                const Mat& m = ld.internals[i];
                                std::cout << "INTERNAL " << i << " " << cv::typeToString(m.type()) << " " << shape(m) << std::endl;
                                if (DNN_CHECK_NAN_INF_DUMP) std::cout << m.reshape(1, 1) << std::endl;
                            }
                            if (DNN_CHECK_NAN_INF_RAISE_ERROR)
                                CV_Assert(!fail);
                        }
                    }

3670 3671 3672 3673 3674
                    for (int i = 0, n = ld.outputBlobsWrappers.size(); i < n; ++i)
                    {
                        if (!ld.outputBlobsWrappers[i].empty())
                            ld.outputBlobsWrappers[i]->setHostDirty();
                    }
3675 3676
                }
            }
3677
            else
3678
            {
3679 3680
                Ptr<BackendNode> node = it->second;
                CV_Assert(!node.empty());
3681 3682 3683 3684 3685 3686 3687 3688 3689
                if (preferableBackend == DNN_BACKEND_CUDA)
                {
                    CV_Assert(haveCUDA());

#ifdef HAVE_CUDA
                    Ptr<CUDABackendNode> cudaNode = node.dynamicCast<CUDABackendNode>();
                    CV_Assert(!cudaNode.empty());

                    cudaNode->forward(ld.inputBlobsWrappers, ld.outputBlobsWrappers, cudaInfo->workspace);
3690 3691 3692 3693 3694 3695

                    for (auto id : ld.cudaD2HBackgroundTransfers)
                    {
                        auto wrapper = ld.outputBlobsWrappers[id].dynamicCast<CUDABackendWrapper>();
                        wrapper->copyToHostInBackground();
                    }
3696 3697 3698
#endif
                }
                else if (preferableBackend == DNN_BACKEND_HALIDE)
3699 3700 3701
                {
                    forwardHalide(ld.outputBlobsWrappers, node);
                }
3702
                else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019)
3703
                {
3704
                    forwardInfEngine(ld.outputBlobsWrappers, node, isAsync);
3705
                }
3706 3707 3708
                else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
                {
                    forwardNgraph(ld.outputBlobsWrappers, node, isAsync);
3709 3710 3711 3712
                }
                 else if (preferableBackend == DNN_BACKEND_WEBNN)
                {
                    forwardWebnn(ld.outputBlobsWrappers, node, isAsync);
3713
                }
3714 3715
                else if (preferableBackend == DNN_BACKEND_VKCOM)
                {
3716 3717 3718 3719 3720 3721 3722 3723 3724 3725
                    try
                    {
                        forwardVkCom(ld.outputBlobsWrappers, node);
                    }
                    catch (const cv::Exception& e)
                    {
                        CV_LOG_ERROR(NULL, "forwardVkCom failed, fallback to CPU implementation. " << e.what());
                        it->second = Ptr<BackendNode>();
                        forwardLayer(ld);
                    }
3726
                }
3727 3728 3729 3730
                else
                {
                    CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
                }
3731
            }
3732 3733 3734 3735

            tm.stop();
            int64 t = tm.getTimeTicks();
            layersTimings[ld.id] = (t > 0) ? t : t + 1;  // zero for skipped layers only
3736
        }
3737
        else
3738 3739 3740
        {
            layersTimings[ld.id] = 0;
        }
3741

3742 3743 3744 3745 3746
        ld.flag = 1;
    }

    void forwardToLayer(LayerData &ld, bool clearFlags = true)
    {
A
Alexander Alekhin 已提交
3747 3748
        CV_TRACE_FUNCTION();

3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
        if (clearFlags)
        {
            MapIdToLayerData::iterator it;
            for (it = layers.begin(); it != layers.end(); it++)
                it->second.flag = 0;
        }

        //already was forwarded
        if (ld.flag)
            return;

        //forward parents
        MapIdToLayerData::iterator it;
3762
        for (it = layers.begin(); it != layers.end() && (it->second.id < ld.id); ++it)
3763 3764 3765 3766 3767 3768 3769 3770 3771
        {
            LayerData &ld = it->second;
            if (ld.flag)
                continue;
            forwardLayer(ld);
        }

        //forward itself
        forwardLayer(ld);
3772 3773 3774 3775 3776

#ifdef HAVE_CUDA
        if (preferableBackend == DNN_BACKEND_CUDA)
            cudaInfo->context.stream.synchronize();
#endif
3777 3778
    }

3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797
    void getQuantizationParams(const Mat& src, std::vector<float>& scales, std::vector<int>& zeropoints)
    {
        const int qmin = -128; // INT8_MIN
        const int qmax = 127;  // INT8_MAX

        double rmin, rmax, sc, zp;
        cv::minMaxIdx(src, &rmin, &rmax);

        // 0 must be present in the range [rmin, rmax]
        rmin = std::min(rmin, 0.0);
        rmax = std::max(rmax, 0.0);

        sc = (rmax == rmin) ? 1.0 : (rmax - rmin)/(qmax - qmin);
        zp = qmin - (rmin/sc);

        scales.push_back((float)sc);
        zeropoints.push_back((int)std::round(zp));
    }

3798 3799
    void getLayerShapesRecursively(int id, LayersShapesMap& inOutShapes)
    {
3800 3801 3802 3803 3804
        CV_CheckGE(id, 0, "");
        CV_CheckLT(id, (int)layers.size(), "");
        LayerData& layerData = layers[id];
        std::vector<LayerPin>& inputLayerIds = layerData.inputBlobsId;
        LayerShapes& layerShapes = inOutShapes[id];
3805

3806
        if (id == 0 && layerShapes.in[0].empty())
3807
        {
3808
            if (!layerData.outputBlobs.empty())
3809
            {
3810
                ShapesVec shapes;
3811
                for (int i = 0; i < layerData.outputBlobs.size(); i++)
3812
                {
3813 3814
                    Mat& inp = layerData.outputBlobs[i];
                    CV_Assert(!inp.empty());
3815 3816
                    shapes.push_back(shape(inp));
                }
3817
                layerShapes.in = shapes;
3818
            }
3819 3820
            else
            {
3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832
                const std::vector<MatShape>& inputShapes = netInputLayer->shapes;
                bool none = true;
                for (size_t i = 0; i < inputShapes.size(); i++)
                {
                    if (!inputShapes[i].empty())
                    {
                        none = false;
                        break;
                    }
                }
                if (none)
                {
3833
                    layerShapes.out.clear();
3834 3835 3836 3837
                    return;
                }
                else
                {
3838
                    layerShapes.in = inputShapes;
3839
                }
3840 3841
            }
        }
3842

3843
        if (layerShapes.in.empty())
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855
        {
            for(int i = 0; i < inputLayerIds.size(); i++)
            {
                int layerId = inputLayerIds[i].lid;
                LayersShapesMap::iterator it =
                        inOutShapes.find(layerId);
                if(it == inOutShapes.end() ||
                        it->second.out.empty())
                {
                    getLayerShapesRecursively(layerId, inOutShapes);
                }
                const MatShape& shape = inOutShapes[layerId].out[inputLayerIds[i].oid];
3856
                layerShapes.in.push_back(shape);
3857 3858
            }
        }
3859 3860 3861 3862 3863
        const ShapesVec& is = layerShapes.in;
        ShapesVec& os = layerShapes.out;
        ShapesVec& ints = layerShapes.internal;
        int requiredOutputs = layerData.requiredOutputs.size();
        Ptr<Layer> l = layerData.getLayerInstance();
3864 3865 3866 3867 3868 3869 3870 3871 3872
        CV_Assert(l);
        bool layerSupportInPlace = false;
        try
        {
            layerSupportInPlace = l->getMemoryShapes(is, requiredOutputs, os, ints);
        }
        catch (const cv::Exception& e)
        {
            CV_LOG_ERROR(NULL, "OPENCV/DNN: [" << l->type << "]:(" << l->name << "): getMemoryShapes() throws exception." <<
3873 3874 3875
                    " inputs=" << is.size() <<
                    " outputs=" << os.size() << "/" << requiredOutputs <<
                    " blobs=" << l->blobs.size());
3876 3877 3878 3879 3880 3881 3882 3883
            for (size_t i = 0; i < is.size(); ++i)
            {
                CV_LOG_ERROR(NULL, "    input[" << i << "] = " << toString(is[i]));
            }
            for (size_t i = 0; i < os.size(); ++i)
            {
                CV_LOG_ERROR(NULL, "    output[" << i << "] = " << toString(os[i]));
            }
3884 3885 3886 3887
            for (size_t i = 0; i < l->blobs.size(); ++i)
            {
                CV_LOG_ERROR(NULL, "    blobs[" << i << "] = " << typeToString(l->blobs[i].type()) << " " << toString(shape(l->blobs[i])));
            }
3888 3889 3890
            CV_LOG_ERROR(NULL, "Exception message: " << e.what());
            throw;
        }
3891
        layerShapes.supportInPlace = layerSupportInPlace;
3892

3893 3894 3895 3896
        try
        {
            for (int i = 0; i < ints.size(); i++)
                CV_CheckGT(total(ints[i]), 0, "");
3897

3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922
            for (int i = 0; i < os.size(); i++)
                CV_CheckGT(total(os[i]), 0, "");
        }
        catch (const cv::Exception& e)
        {
            CV_LOG_ERROR(NULL, "OPENCV/DNN: [" << l->type << "]:(" << l->name << "): getMemoryShapes() post validation failed." <<
                    " inputs=" << is.size() <<
                    " outputs=" << os.size() << "/" << requiredOutputs <<
                    " blobs=" << l->blobs.size() <<
                    " inplace=" << layerSupportInPlace);
            for (size_t i = 0; i < is.size(); ++i)
            {
                CV_LOG_ERROR(NULL, "    input[" << i << "] = " << toString(is[i]));
            }
            for (size_t i = 0; i < os.size(); ++i)
            {
                CV_LOG_ERROR(NULL, "    output[" << i << "] = " << toString(os[i]));
            }
            for (size_t i = 0; i < l->blobs.size(); ++i)
            {
                CV_LOG_ERROR(NULL, "    blobs[" << i << "] = " << typeToString(l->blobs[i].type()) << " " << toString(shape(l->blobs[i])));
            }
            CV_LOG_ERROR(NULL, "Exception message: " << e.what());
            throw;
        }
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947
    }

    void getLayersShapes(const ShapesVec& netInputShapes,
                         LayersShapesMap& inOutShapes)
    {
        inOutShapes.clear();

        inOutShapes[0].in = netInputShapes; //insert shape for first input layer
        for (MapIdToLayerData::iterator it = layers.begin();
             it != layers.end(); it++)
        {
            getLayerShapesRecursively(it->first, inOutShapes);
        }
    }

    void getLayerShapes(const ShapesVec& netInputShapes,
                        const int layerId,
                        LayerShapes& shapes)
    {
        LayersShapesMap inOutShapes;
        inOutShapes[0].in = netInputShapes; //insert shape for first input layer
        getLayerShapesRecursively(layerId, inOutShapes);
        shapes = inOutShapes[layerId];
    }

3948 3949
    void updateLayersShapes()
    {
3950 3951 3952 3953 3954 3955
        CV_LOG_DEBUG(NULL, "updateLayersShapes() with layers.size=" << layers.size());
        CV_Assert(netInputLayer);
        DataLayer& inputLayer = *netInputLayer;
        LayerData& inputLayerData = layers[0];
        CV_Assert(inputLayerData.layerInstance.get() == &inputLayer);
        CV_Assert(!inputLayerData.outputBlobs.empty());
3956
        ShapesVec inputShapes;
3957
        for(int i = 0; i < inputLayerData.outputBlobs.size(); i++)
3958
        {
3959 3960 3961
            Mat& inp = inputLayerData.outputBlobs[i];
            CV_Assert(!inp.empty());
            if (preferableBackend == DNN_BACKEND_OPENCV &&  // FIXIT: wrong place for output allocation
3962
                preferableTarget == DNN_TARGET_OPENCL_FP16 &&
3963
                inputLayerData.dtype == CV_32F)
3964
            {
3965
                inp.create(inp.dims, inp.size, CV_16S);
3966 3967 3968
            }
            inputShapes.push_back(shape(inp));
        }
3969
        CV_LOG_DEBUG(NULL, toString(inputShapes, "Network input shapes"));
3970 3971 3972 3973 3974 3975
        LayersShapesMap layersShapes;
        layersShapes[0].in = inputShapes;
        for (MapIdToLayerData::iterator it = layers.begin();
             it != layers.end(); it++)
        {
            int layerId = it->first;
3976 3977 3978 3979 3980
            LayerData& layerData = it->second;
            std::vector<LayerPin>& inputLayerIds = layerData.inputBlobsId;
            LayerShapes& layerShapes = layersShapes[layerId];
            CV_LOG_DEBUG(NULL, "layer " << layerId << ": [" << layerData.type << "]:(" << layerData.name << ") with inputs.size=" << inputLayerIds.size());
            if (layerShapes.in.empty())
3981 3982 3983
            {
                for(int i = 0; i < inputLayerIds.size(); i++)
                {
3984 3985 3986
                    const LayerPin& inputPin = inputLayerIds[i];
                    int inputLayerId = inputPin.lid;
                    CV_LOG_DEBUG(NULL, "    input[" << i << "] " << inputLayerId << ":" << inputPin.oid << " as [" << layers[inputLayerId].type << "]:(" << layers[inputLayerId].name << ")");
3987
                    LayersShapesMap::iterator inputIt = layersShapes.find(inputLayerId);
3988
                    if (inputIt == layersShapes.end() || inputIt->second.out.empty())
3989 3990 3991
                    {
                        getLayerShapesRecursively(inputLayerId, layersShapes);
                    }
3992 3993
                    const MatShape& shape = layersShapes[inputLayerId].out[inputPin.oid];
                    layerShapes.in.push_back(shape);
3994
                }
3995
                layerData.getLayerInstance()->updateMemoryShapes(layerShapes.in);
3996
            }
3997 3998 3999
            CV_LOG_DEBUG(NULL, "Layer " << layerId << ": " << toString(layerShapes.in, "input shapes"));
            CV_LOG_IF_DEBUG(NULL, !layerShapes.out.empty(), "Layer " << layerId << ": " << toString(layerShapes.out, "output shapes"));
            CV_LOG_IF_DEBUG(NULL, !layerShapes.internal.empty(), "Layer " << layerId << ": " << toString(layerShapes.internal, "internal shapes"));
4000
        }
4001
        CV_LOG_DEBUG(NULL, "updateLayersShapes() - DONE");
4002 4003
    }

4004 4005 4006 4007 4008 4009 4010
    LayerPin getLatestLayerPin(const std::vector<LayerPin>& pins)
    {
        return *std::max_element(pins.begin(), pins.end());
    }

    Mat getBlob(const LayerPin& pin)
    {
A
Alexander Alekhin 已提交
4011 4012
        CV_TRACE_FUNCTION();

4013 4014 4015 4016 4017 4018
        if (!pin.valid())
            CV_Error(Error::StsObjectNotFound, "Requested blob not found");

        LayerData &ld = layers[pin.lid];
        if ((size_t)pin.oid >= ld.outputBlobs.size())
        {
4019
            CV_Error(Error::StsOutOfRange, format("Layer \"%s\" produce only %zu outputs, "
L
luz.paz 已提交
4020
                                           "the #%d was requested", ld.name.c_str(),
4021
                                           ld.outputBlobs.size(), pin.oid));
4022
        }
4023
        if (preferableTarget != DNN_TARGET_CPU)
4024
        {
4025
            CV_Assert(!ld.outputBlobsWrappers.empty() && !ld.outputBlobsWrappers[pin.oid].empty());
4026
            // Transfer data to CPU if it's require.
4027
            ld.outputBlobsWrappers[pin.oid]->copyToHost();
4028
        }
L
Li Peng 已提交
4029 4030 4031 4032 4033 4034 4035 4036

        if (ld.outputBlobs[pin.oid].depth() == CV_16S)
        {
            convertFp16(ld.outputBlobs[pin.oid], output_blob);
            return output_blob;
        }
        else
            return ld.outputBlobs[pin.oid];
4037 4038 4039 4040 4041 4042
    }

    Mat getBlob(String outputName)
    {
        return getBlob(getPinByAlias(outputName));
    }
4043 4044

#ifdef CV_CXX11
A
Alexander Alekhin 已提交
4045
    AsyncArray getBlobAsync(const LayerPin& pin)
4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056
    {
        CV_TRACE_FUNCTION();
#ifdef HAVE_INF_ENGINE
        if (!pin.valid())
            CV_Error(Error::StsObjectNotFound, "Requested blob not found");

        LayerData &ld = layers[pin.lid];
        if ((size_t)pin.oid >= ld.outputBlobs.size())
        {
            CV_Error(Error::StsOutOfRange, format("Layer \"%s\" produce only %d outputs, "
                                           "the #%d was requested", ld.name.c_str(),
4057
                                           (int)ld.outputBlobs.size(), (int)pin.oid));
4058 4059 4060 4061 4062 4063 4064
        }
        if (preferableTarget != DNN_TARGET_CPU)
        {
            CV_Assert(!ld.outputBlobsWrappers.empty() && !ld.outputBlobsWrappers[pin.oid].empty());
            // Transfer data to CPU if it's require.
            ld.outputBlobsWrappers[pin.oid]->copyToHost();
        }
4065
        CV_Assert(preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 || preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH);
4066

4067
        if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019) {
4068
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
4069 4070
            Ptr<InfEngineBackendWrapper> wrapper = ld.outputBlobsWrappers[pin.oid].dynamicCast<InfEngineBackendWrapper>();
            return std::move(wrapper->futureMat);
4071 4072 4073
#else
            CV_Error(Error::StsNotImplemented, "This OpenCV version is built without Inference Engine NN Builder API support");
#endif
4074 4075 4076 4077 4078 4079
        }
        else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH)
        {
#ifdef HAVE_DNN_NGRAPH
            Ptr<NgraphBackendWrapper> wrapper = ld.outputBlobsWrappers[pin.oid].dynamicCast<NgraphBackendWrapper>();
            return std::move(wrapper->futureMat);
4080
#else
4081
            CV_Error(Error::StsNotImplemented, "This OpenCV version is built without support of Inference Engine + nGraph");
4082
#endif
4083 4084 4085
        }
#endif  // HAVE_INF_ENGINE
        CV_Error(Error::StsNotImplemented, "DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 backend is required");
4086 4087
    }

A
Alexander Alekhin 已提交
4088
    AsyncArray getBlobAsync(String outputName)
4089 4090 4091 4092
    {
        return getBlobAsync(getPinByAlias(outputName));
    }
#endif  // CV_CXX11
4093 4094 4095 4096 4097

#ifdef HAVE_INF_ENGINE
    static
    Net createNetworkFromModelOptimizer(InferenceEngine::CNNNetwork& ieNet);
#endif
4098 4099 4100 4101 4102 4103

    string dump();

    void dumpNetworkToFile()
    {
#ifndef OPENCV_DNN_DISABLE_NETWORK_AUTO_DUMP
4104 4105
        string dumpFileNameBase = getDumpFileNameBase();
        string dumpFileName = dumpFileNameBase + ".dot";
4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123
        try
        {
            string dumpStr = dump();
            std::ofstream out(dumpFileName.c_str(), std::ios::out | std::ios::binary);
            out << dumpStr;
        }
        catch (const std::exception& e)
        {
            std::ofstream out((dumpFileName + ".error").c_str(), std::ios::out);
            out << "Exception: " << e.what() << std::endl;
        }
        catch (...)
        {
            std::ofstream out((dumpFileName + ".error").c_str(), std::ios::out);
            out << "Can't dump: unknown exception" << std::endl;
        }
#endif
    }
4124 4125 4126 4127 4128 4129
};

Net::Net() : impl(new Net::Impl)
{
}

4130 4131 4132
#ifdef HAVE_INF_ENGINE
/*static*/
Net Net::Impl::createNetworkFromModelOptimizer(InferenceEngine::CNNNetwork& ieNet)
4133
{
4134
    CV_TRACE_FUNCTION();
4135

4136 4137
    CV_TRACE_REGION("register_inputs");

4138
    std::vector<String> inputsNames;
4139
    std::vector<MatShape> inp_shapes;
4140 4141 4142
    for (auto& it : ieNet.getInputsInfo())
    {
        inputsNames.push_back(it.first);
4143 4144
        std::vector<size_t> dims = it.second->getTensorDesc().getDims();
        inp_shapes.push_back(std::vector<int>(dims.begin(), dims.end()));
4145 4146
    }

4147
    Net cvNet;
4148 4149
    cvNet.setInputsNames(inputsNames);

4150 4151 4152
    // set empty input to determine input shapes
    for (int inp_id = 0; inp_id < inputsNames.size(); ++inp_id)
    {
4153
        cvNet.setInputShape(inputsNames[inp_id], inp_shapes[inp_id]);
4154 4155
    }

4156 4157
    CV_TRACE_REGION_NEXT("backendNode");

4158 4159 4160 4161 4162 4163
    Ptr<BackendNode> backendNode;
#ifdef HAVE_DNN_NGRAPH
    if (DNN_BACKEND_INFERENCE_ENGINE_NGRAPH == getInferenceEngineBackendTypeParam())
    {
        auto fake_node = std::make_shared<ngraph::op::Parameter>(ngraph::element::f32, ngraph::Shape{});
        Ptr<InfEngineNgraphNode> backendNodeNGraph(new InfEngineNgraphNode(fake_node));
4164
        backendNodeNGraph->net = Ptr<InfEngineNgraphNet>(new InfEngineNgraphNet(*(cvNet.impl), ieNet));
4165 4166 4167 4168
        backendNode = backendNodeNGraph;
    }
    else
#endif
4169
    {
4170
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
4171 4172 4173
        Ptr<InfEngineBackendNode> backendNodeNN(new InfEngineBackendNode(InferenceEngine::Builder::Layer("")));
        backendNodeNN->net = Ptr<InfEngineBackendNet>(new InfEngineBackendNet(ieNet));
        backendNode = backendNodeNN;
4174 4175 4176
#else
        CV_Error(Error::StsNotImplemented, "This OpenCV version is built without Inference Engine NN Builder API support");
#endif
4177
    }
4178

4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
    CV_TRACE_REGION_NEXT("register_outputs");

#ifdef HAVE_DNN_NGRAPH
    auto ngraphFunction = ieNet.getFunction();
#if INF_ENGINE_VER_MAJOR_LT(INF_ENGINE_RELEASE_2020_2)
    std::list< std::shared_ptr<ngraph::Node> > ngraphOperations;
#else
    std::vector< std::shared_ptr<ngraph::Node> > ngraphOperations;
#endif
    if (ngraphFunction)
    {
        ngraphOperations = ngraphFunction->get_ops();
    }
#endif

4194 4195
    for (auto& it : ieNet.getOutputsInfo())
    {
4196
        CV_TRACE_REGION("output");
4197
        const auto& outputName = it.first;
4198

4199 4200 4201 4202
        LayerParams lp;
        int lid = cvNet.addLayer(it.first, "", lp);

        LayerData& ld = cvNet.impl->layers[lid];
4203 4204 4205 4206 4207

#ifdef HAVE_DNN_NGRAPH
        if (DNN_BACKEND_INFERENCE_ENGINE_NGRAPH == getInferenceEngineBackendTypeParam())
        {
            Ptr<Layer> cvLayer(new NgraphBackendLayer(ieNet));
4208 4209
            cvLayer->name = outputName;
            cvLayer->type = "_unknown_";
4210

4211
            auto process_layer = [&](const std::string& name) -> bool
4212
            {
4213
                if (ngraphFunction)
4214
                {
4215 4216
                    CV_TRACE_REGION("ngraph_function");
                    for (const auto& op : ngraphOperations)
4217
                    {
4218 4219 4220 4221 4222 4223 4224
                        CV_Assert(op);
                        if (op->get_friendly_name() == name)
                        {
                            const std::string typeName = op->get_type_info().name;
                            cvLayer->type = typeName;
                            return true;
                        }
4225
                    }
4226
                    return false;
4227
                }
4228 4229
                else
                {
4230 4231 4232
#if INF_ENGINE_VER_MAJOR_GT(INF_ENGINE_RELEASE_2020_4)
                    CV_Error(Error::StsNotImplemented, "This OpenCV version is built with Inference Engine which has dropped IR v7 support");
#else
4233 4234 4235 4236 4237
                    CV_TRACE_REGION("legacy_cnn_layer");
                    try
                    {
                        InferenceEngine::CNNLayerPtr ieLayer = ieNet.getLayerByName(name.c_str());
                        CV_Assert(ieLayer);
4238

4239 4240 4241 4242 4243 4244 4245 4246 4247
                        cvLayer->type = ieLayer->type;
                        return true;
                    }
                    catch (const std::exception& e)
                    {
                        CV_UNUSED(e);
                        CV_LOG_DEBUG(NULL, "IE layer extraction failure: '" << name << "' - " << e.what());
                        return false;
                    }
4248 4249
#endif

4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261
                }
            };

            bool found = process_layer(outputName);
            if (!found)
            {
                auto pos = outputName.rfind('.');  // cut port number: ".0"
                if (pos != std::string::npos)
                {
                    std::string layerName = outputName.substr(0, pos);
                    found = process_layer(layerName);
                }
4262
            }
4263 4264 4265
            if (!found)
                CV_LOG_WARNING(NULL, "DNN/IE: Can't determine output layer type: '" << outputName << "'");

4266 4267 4268 4269 4270 4271
            ld.layerInstance = cvLayer;
            ld.backendNodes[DNN_BACKEND_INFERENCE_ENGINE_NGRAPH] = backendNode;
        }
        else
#endif
        {
4272
#ifdef HAVE_DNN_IE_NN_BUILDER_2019
4273 4274
            Ptr<Layer> cvLayer(new InfEngineBackendLayer(ieNet));

4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288
            InferenceEngine::CNNLayerPtr ieLayer;
            try
            {
                ieLayer = ieNet.getLayerByName(outputName.c_str());
            }
            catch (...)
            {
                auto pos = outputName.rfind('.');  // cut port number: ".0"
                if (pos != std::string::npos)
                {
                    std::string layerName = outputName.substr(0, pos);
                    ieLayer = ieNet.getLayerByName(layerName.c_str());
                }
            }
4289 4290
            CV_Assert(ieLayer);

4291
            cvLayer->name = outputName;
4292 4293 4294 4295
            cvLayer->type = ieLayer->type;
            ld.layerInstance = cvLayer;

            ld.backendNodes[DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019] = backendNode;
4296 4297 4298
#else
            CV_Error(Error::StsNotImplemented, "This OpenCV version is built without Inference Engine NN Builder API support");
#endif
4299
        }
4300

4301 4302
        for (int i = 0; i < inputsNames.size(); ++i)
            cvNet.connect(0, i, lid, i);
4303
    }
4304 4305 4306

    CV_TRACE_REGION_NEXT("finalize");

4307
    cvNet.setPreferableBackend(getInferenceEngineBackendTypeParam());
4308 4309 4310

    cvNet.impl->skipInfEngineInit = true;
    return cvNet;
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327
}
#endif  // HAVE_INF_ENGINE

Net Net::readFromModelOptimizer(const String& xml, const String& bin)
{
    CV_TRACE_FUNCTION();
#ifndef HAVE_INF_ENGINE
    CV_UNUSED(xml); CV_UNUSED(bin);
    CV_Error(Error::StsError, "Build OpenCV with Inference Engine to enable loading models from Model Optimizer.");
#else
#if INF_ENGINE_VER_MAJOR_LE(INF_ENGINE_RELEASE_2019R3)
    InferenceEngine::CNNNetReader reader;
    reader.ReadNetwork(xml);
    reader.ReadWeights(bin);

    InferenceEngine::CNNNetwork ieNet = reader.getNetwork();
#else
4328
    InferenceEngine::Core& ie = getCore("");
4329 4330 4331 4332
    InferenceEngine::CNNNetwork ieNet = ie.ReadNetwork(xml, bin);
#endif

    return Impl::createNetworkFromModelOptimizer(ieNet);
4333
#endif  // HAVE_INF_ENGINE
4334 4335
}

4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376
Net Net::readFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights)
{
    CV_TRACE_FUNCTION();
    CV_Assert(!bufferModelConfig.empty());
    CV_Assert(!bufferWeights.empty());
    return readFromModelOptimizer(bufferModelConfig.data(), bufferModelConfig.size(),
                                           bufferWeights.data(), bufferWeights.size());
}

Net Net::readFromModelOptimizer(
        const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize,
        const uchar* bufferWeightsPtr, size_t bufferWeightsSize
)
{
    CV_TRACE_FUNCTION();
#ifndef HAVE_INF_ENGINE
    CV_UNUSED(bufferModelConfigPtr); CV_UNUSED(bufferWeightsPtr);
    CV_UNUSED(bufferModelConfigSize); CV_UNUSED(bufferModelConfigSize);
    CV_Error(Error::StsError, "Build OpenCV with Inference Engine to enable loading models from Model Optimizer.");
#else

#if INF_ENGINE_VER_MAJOR_LE(INF_ENGINE_RELEASE_2019R3)
    InferenceEngine::CNNNetReader reader;

    try
    {
        reader.ReadNetwork(bufferModelConfigPtr, bufferModelConfigSize);

        InferenceEngine::TensorDesc tensorDesc(InferenceEngine::Precision::U8, { bufferWeightsSize }, InferenceEngine::Layout::C);
        InferenceEngine::TBlob<uint8_t>::Ptr weightsBlobPtr(new InferenceEngine::TBlob<uint8_t>(tensorDesc));
        weightsBlobPtr->allocate();
        std::memcpy(weightsBlobPtr->buffer(), (uchar*)bufferWeightsPtr, bufferWeightsSize);
        reader.SetWeights(weightsBlobPtr);
    }
    catch (const std::exception& e)
    {
        CV_Error(Error::StsError, std::string("DNN: IE failed to load model: ") + e.what());
    }

    InferenceEngine::CNNNetwork ieNet = reader.getNetwork();
#else
4377
    InferenceEngine::Core& ie = getCore("");
4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399

    std::string model; model.assign((char*)bufferModelConfigPtr, bufferModelConfigSize);

    InferenceEngine::CNNNetwork ieNet;
    try
    {
        InferenceEngine::TensorDesc tensorDesc(InferenceEngine::Precision::U8, { bufferWeightsSize }, InferenceEngine::Layout::C);
        InferenceEngine::Blob::CPtr weights_blob = InferenceEngine::make_shared_blob<uint8_t>(tensorDesc, (uint8_t*)bufferWeightsPtr, bufferWeightsSize);

        ieNet = ie.ReadNetwork(model, weights_blob);
    }
    catch (const std::exception& e)
    {
        CV_Error(Error::StsError, std::string("DNN: IE failed to load model: ") + e.what());
    }
#endif

    return Impl::createNetworkFromModelOptimizer(ieNet);
#endif  // HAVE_INF_ENGINE
}


4400 4401 4402 4403
Net::~Net()
{
}

4404
int Net::addLayer(const String &name, const String &type, const int &dtype, LayerParams &params)
4405
{
A
Alexander Alekhin 已提交
4406 4407
    CV_TRACE_FUNCTION();

S
Smirnov Egor 已提交
4408 4409
    int id = impl->getLayerId(name);
    if (id >= 0)
4410
    {
S
Smirnov Egor 已提交
4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422
        if (!DNN_DIAGNOSTICS_RUN || type != "NotImplemented")
        {
            CV_Error(Error::StsBadArg, "Layer \"" + name + "\" already into net");
            return -1;
        }
        else
        {
            LayerData& ld = impl->layers.find(id)->second;
            ld.type = type;
            ld.params = params;
            return -1;
        }
4423 4424
    }

S
Smirnov Egor 已提交
4425
    id = ++impl->lastLayerId;
4426
    impl->layerNameToId.insert(std::make_pair(name, id));
4427
    impl->layers.insert(std::make_pair(id, LayerData(id, name, type, dtype, params)));
4428 4429
    if (params.get<bool>("has_dynamic_shapes", false))
        impl->hasDynamicShapes = true;
4430

4431 4432 4433
    if (dtype == CV_8S)
        impl->netWasQuantized = true;

4434 4435 4436
    return id;
}

4437 4438 4439 4440 4441 4442 4443
int Net::addLayer(const String &name, const String &type, LayerParams &params)
{
    CV_TRACE_FUNCTION();
    return addLayer(name, type, CV_32F, params);
}

int Net::addLayerToPrev(const String &name, const String &type, const int &dtype, LayerParams &params)
4444
{
A
Alexander Alekhin 已提交
4445 4446
    CV_TRACE_FUNCTION();

4447
    int prvLid = impl->lastLayerId;
4448
    int newLid = this->addLayer(name, type, dtype, params);
4449 4450 4451 4452
    this->connect(prvLid, 0, newLid, 0);
    return newLid;
}

4453 4454 4455 4456 4457 4458
int Net::addLayerToPrev(const String &name, const String &type, LayerParams &params)
{
    CV_TRACE_FUNCTION();
    return addLayerToPrev(name, type, CV_32F, params);
}

4459 4460
void Net::connect(int outLayerId, int outNum, int inpLayerId, int inpNum)
{
A
Alexander Alekhin 已提交
4461 4462
    CV_TRACE_FUNCTION();

4463 4464 4465 4466 4467
    impl->connect(outLayerId, outNum, inpLayerId, inpNum);
}

void Net::connect(String _outPin, String _inPin)
{
A
Alexander Alekhin 已提交
4468 4469
    CV_TRACE_FUNCTION();

4470 4471 4472 4473 4474 4475 4476 4477 4478 4479
    LayerPin outPin = impl->getPinByAlias(_outPin);
    LayerPin inpPin = impl->getPinByAlias(_inPin);

    CV_Assert(outPin.valid() && inpPin.valid());

    impl->connect(outPin.lid, outPin.oid, inpPin.lid, inpPin.oid);
}

Mat Net::forward(const String& outputName)
{
A
Alexander Alekhin 已提交
4480
    CV_TRACE_FUNCTION();
4481
    CV_Assert(!empty());
A
Alexander Alekhin 已提交
4482

4483 4484 4485
    String layerName = outputName;

    if (layerName.empty())
4486 4487 4488 4489 4490
    {
        std::vector<String> layerNames = getLayerNames();
        CV_Assert(!layerNames.empty());
        layerName = layerNames.back();
    }
4491

D
Dmitry Kurtaev 已提交
4492 4493
    std::vector<LayerPin> pins(1, impl->getPinByAlias(layerName));
    impl->setUpNet(pins);
4494 4495 4496 4497 4498
    impl->forwardToLayer(impl->getLayerData(layerName));

    return impl->getBlob(layerName);
}

A
Alexander Alekhin 已提交
4499
AsyncArray Net::forwardAsync(const String& outputName)
4500 4501
{
    CV_TRACE_FUNCTION();
4502 4503
    CV_Assert(!empty());

4504 4505 4506 4507
#ifdef CV_CXX11
    String layerName = outputName;

    if (layerName.empty())
4508 4509 4510 4511 4512
    {
        std::vector<String> layerNames = getLayerNames();
        CV_Assert(!layerNames.empty());
        layerName = layerNames.back();
    }
4513 4514 4515 4516

    std::vector<LayerPin> pins(1, impl->getPinByAlias(layerName));
    impl->setUpNet(pins);

4517 4518
    if (!(impl->preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 || impl->preferableBackend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH))
        CV_Error(Error::StsNotImplemented, "DNN: Asynchronous forward is supported for Inference Engine backends only");
4519

4520 4521 4522 4523 4524 4525
    impl->isAsync = true;
    impl->forwardToLayer(impl->getLayerData(layerName));
    impl->isAsync = false;

    return impl->getBlobAsync(layerName);
#else
4526
    CV_Error(Error::StsNotImplemented, "DNN: Asynchronous forward requires build with enabled C++11");
4527 4528 4529
#endif  // CV_CXX11
}

4530
void Net::forward(OutputArrayOfArrays outputBlobs, const String& outputName)
4531
{
A
Alexander Alekhin 已提交
4532
    CV_TRACE_FUNCTION();
4533
    CV_Assert(!empty());
A
Alexander Alekhin 已提交
4534

4535 4536 4537
    String layerName = outputName;

    if (layerName.empty())
4538 4539 4540 4541 4542
    {
        std::vector<String> layerNames = getLayerNames();
        CV_Assert(!layerNames.empty());
        layerName = layerNames.back();
    }
4543

D
Dmitry Kurtaev 已提交
4544 4545
    std::vector<LayerPin> pins(1, impl->getPinByAlias(layerName));
    impl->setUpNet(pins);
4546 4547 4548 4549
    impl->forwardToLayer(impl->getLayerData(layerName));

    LayerPin pin = impl->getPinByAlias(layerName);
    LayerData &ld = impl->layers[pin.lid];
L
Li Peng 已提交
4550

4551
    if (outputBlobs.isUMat())
L
Li Peng 已提交
4552
    {
4553
        impl->getBlob(layerName).copyTo(outputBlobs);
4554 4555 4556 4557 4558 4559 4560
    }
    else if (outputBlobs.isMat())
    {
        outputBlobs.assign(impl->getBlob(layerName));
    }
    else if (outputBlobs.isMatVector())
    {
4561
        if (impl->preferableTarget != DNN_TARGET_CPU)
4562
        {
4563 4564 4565 4566 4567
            for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
            {
                CV_Assert(!ld.outputBlobsWrappers[i].empty());
                ld.outputBlobsWrappers[i]->copyToHost();
            }
4568
        }
4569
        if (ld.outputBlobs[0].depth() == CV_16S)
L
Li Peng 已提交
4570 4571 4572 4573 4574 4575
        {
            std::vector<Mat> & outputvec = *(std::vector<Mat> *)outputBlobs.getObj();
            outputvec.resize(ld.outputBlobs.size());
            for (int i = 0; i < outputvec.size(); i++)
                convertFp16(ld.outputBlobs[i], outputvec[i]);
        }
4576 4577 4578 4579 4580 4581
        else
        {
            // Output depth can be CV_32F or CV_8S
            std::vector<Mat> & outputvec = *(std::vector<Mat> *)outputBlobs.getObj();
            outputvec = ld.outputBlobs;
        }
4582 4583 4584
    }
    else if (outputBlobs.isUMatVector())
    {
4585 4586
        std::vector<UMat> & outputvec = *(std::vector<UMat> *)outputBlobs.getObj();

4587
#ifdef HAVE_OPENCL
4588
        if (impl->preferableBackend == DNN_BACKEND_OPENCV &&
L
Li Peng 已提交
4589
            IS_DNN_OPENCL_TARGET(impl->preferableTarget))
4590
        {
L
Li Peng 已提交
4591 4592 4593 4594 4595 4596 4597 4598 4599
            if (impl->preferableTarget == DNN_TARGET_OPENCL)
                outputvec = OpenCLBackendWrapper::getUMatVector(ld.outputBlobsWrappers);
            else if (impl->preferableTarget == DNN_TARGET_OPENCL_FP16)
            {
                std::vector<UMat> out_vec = OpenCLBackendWrapper::getUMatVector(ld.outputBlobsWrappers);
                outputvec.resize(out_vec.size());
                for (int i = 0; i < out_vec.size(); i++)
                    convertFp16(out_vec[i], outputvec[i]);
            }
4600 4601
        }
        else
4602
#endif
4603
        {
4604 4605
            outputvec.resize(ld.outputBlobs.size());
            for (int i = 0; i < outputvec.size(); ++i)
4606
                ld.outputBlobs[i].copyTo(outputvec[i]);
4607
        }
L
Li Peng 已提交
4608
    }
4609 4610
}

4611
void Net::forward(OutputArrayOfArrays outputBlobs,
4612 4613
                  const std::vector<String>& outBlobNames)
{
A
Alexander Alekhin 已提交
4614 4615
    CV_TRACE_FUNCTION();

4616 4617 4618
    std::vector<LayerPin> pins;
    for (int i = 0; i < outBlobNames.size(); i++)
    {
4619
        pins.push_back(impl->getPinByAlias(outBlobNames[i]));
4620 4621 4622 4623 4624 4625 4626 4627
    }

    impl->setUpNet(pins);

    LayerPin out = impl->getLatestLayerPin(pins);

    impl->forwardToLayer(impl->getLayerData(out.lid));

4628
    std::vector<Mat> matvec;
4629 4630
    for (int i = 0; i < pins.size(); i++)
    {
4631
        matvec.push_back(impl->getBlob(pins[i]));
4632
    }
4633

4634 4635
    outputBlobs.create((int)matvec.size(), 1, CV_32F/*FIXIT*/, -1);  // allocate vector
    outputBlobs.assign(matvec);
4636 4637 4638 4639 4640
}

void Net::forward(std::vector<std::vector<Mat> >& outputBlobs,
                     const std::vector<String>& outBlobNames)
{
A
Alexander Alekhin 已提交
4641 4642
    CV_TRACE_FUNCTION();

4643 4644 4645
    std::vector<LayerPin> pins;
    for (int i = 0; i < outBlobNames.size(); i++)
    {
4646
        pins.push_back(impl->getPinByAlias(outBlobNames[i]));
4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658
    }

    impl->setUpNet(pins);

    LayerPin out = impl->getLatestLayerPin(pins);

    impl->forwardToLayer(impl->getLayerData(out.lid));

    outputBlobs.resize(outBlobNames.size());
    for (int i = 0; i < outBlobNames.size(); i++)
    {
        std::vector<LayerPin> lp = impl->getLayerOutPins(outBlobNames[i]);
4659 4660
        outputBlobs[i].resize(lp.size());
        for (int j = 0; j < lp.size(); j++)
4661
        {
4662
            outputBlobs[i][j] = impl->getBlob(lp[j]);
4663 4664 4665 4666
        }
    }
}

4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767
Net Net::quantize(InputArrayOfArrays calibData, int inputsDtype, int outputsDtype)
{
    CV_TRACE_FUNCTION();

    // Net can be quantized only once.
    if (impl->netWasQuantized)
        CV_Error(Error::StsBadArg, "Cannot quantize a quantized net");

    CV_CheckType(inputsDtype, inputsDtype == CV_32F || inputsDtype == CV_8S, "Input depth should be CV_32F or CV_8S");
    CV_CheckType(outputsDtype, outputsDtype == CV_32F || outputsDtype == CV_8S, "Output depth should be CV_32F or CV_8S");

    bool originalFusion = impl->fusion;
    int prefBackend = impl->preferableBackend;
    int prefTarget = impl->preferableTarget;

    // Disable fusions and use CPU backend to quantize net
    setPreferableBackend(DNN_BACKEND_OPENCV);
    setPreferableTarget(DNN_TARGET_CPU);
    enableFusion(false);

    if (calibData.isMat())
    {
        setInput(calibData.getMat());
    }
    else if (calibData.isMatVector())
    {
        std::vector<Mat> calibDataVec;
        calibData.getMatVector(calibDataVec);

        std::vector<String> inpNames = impl->netInputLayer->outNames;
        CV_CheckEQ(calibDataVec.size(), inpNames.size(), "Calibration data size should be equal to number of inputs");
        for (int i = 0; i < calibDataVec.size(); i++)
            setInput(calibDataVec[i], inpNames[i]);
    }

    std::vector<String> outNames = getUnconnectedOutLayersNames();
    std::vector<LayerPin> pins;
    for (int i = 0; i < outNames.size(); i++)
        pins.push_back(impl->getPinByAlias(outNames[i]));
    impl->setUpNet(pins);

    // Compute scales and zeropoints for all the layers
    std::vector<std::vector<float> > scales;
    std::vector<std::vector<int> > zeropoints;
    for (Impl::MapIdToLayerData::iterator it = impl->layers.begin(); it != impl->layers.end(); it++)
    {
        LayerData& ld = it->second;
        if (!ld.skip)
        {
            Ptr<Layer> layer = ld.layerInstance;
            std::vector<Mat> inps(ld.inputBlobs.size());
            for (int i = 0; i < ld.inputBlobs.size(); ++i)
                inps[i] = *ld.inputBlobs[i];
            layer->forward(inps, ld.outputBlobs, ld.internals);
        }

        std::vector<float> sc;
        std::vector<int> zp;
        if (ld.type == "TanH")
        {
            sc.push_back(1.f/128);
            zp.push_back(0);
        }
        else if (ld.type == "Sigmoid" || ld.type == "Softmax" || ld.type == "SoftMax")
        {
            if (ld.params.get<bool>("log_softmax", false))
            {
                sc.push_back(16.f/256);
                zp.push_back(127);
            }
            else
            {
                sc.push_back(1.f/256);
                zp.push_back(-128);
            }
        }
        else if (ld.type == "Split" || ld.type == "Slice" || ld.type == "Crop")
        {
            std::vector<float> inp_sc; std::vector<int> inp_zp;
            impl->getQuantizationParams(*ld.inputBlobs[0], inp_sc, inp_zp);
            sc.assign(ld.outputBlobs.size(), inp_sc[0]);
            zp.assign(ld.outputBlobs.size(), inp_zp[0]);
        }
        else
        {
            for (int i = 0; i < ld.outputBlobs.size(); i++)
                impl->getQuantizationParams(ld.outputBlobs[i], sc, zp);
        }
        scales.push_back(sc);
        zeropoints.push_back(zp);
    }

    // For some layers, the input and output scales/zeropoints must be equal so that rescaling of inputs
    // is not needed during quantized inference. We start from the last layer and modify the layer's input scales/zeropoints
    // TODO : Need a different approach. Current solution fails when 2 such layers have the same input layer
    for (Impl::MapIdToLayerData::reverse_iterator it = impl->layers.rbegin(); it != impl->layers.rend(); ++it)
    {
        LayerData& ld = it->second;
        // Layers with multiple outputs. Number of outputs is equal to number of inputs
        if (ld.type == "Blank" || ld.type == "Dropout" || ld.type == "Identity" || ld.type == "Silence" ||
            ld.type == "Flatten" || ld.type == "Padding" || ld.type == "Permute" || ld.type == "Reshape" ||
4768
            ld.type == "ReLU6" || ld.type == "Reorg" || ld.type == "ShuffleChannel" || ld.type == "Resize" ||
4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923
           (ld.type == "ReLU" && !ld.params.get<float>("negative_slope", 0.f)) /* ReLU with negative slope 0 */)
        {
            for (int i = 0; i < ld.outputBlobs.size(); i++)
            {
                LayerPin &pin = ld.inputBlobsId[i];
                scales[pin.lid][pin.oid] = scales[ld.id][i];
                zeropoints[pin.lid][pin.oid] = zeropoints[ld.id][i];
            }
        }
        // Layers with multiple inputs and single output.
        else if ((ld.type == "Pooling" && toLowerCase(ld.params.get<String>("pool", "max")) == "max") /* Max Pooling */ ||
                 (ld.type == "Eltwise" && toLowerCase(ld.params.get<String>("operation", "sum")) == "max") /* Elementwise max */ ||
                  ld.type == "Concat")
        {
            for (int i = 0; i < ld.inputBlobsId.size(); i++)
            {
                LayerPin &pin = ld.inputBlobsId[i];
                scales[pin.lid][pin.oid] = scales[ld.id][0];
                zeropoints[pin.lid][pin.oid] = zeropoints[ld.id][0];
            }
        }
    }

    // Create a new Net and add quantized layers to it.
    Net dstNet;
    dstNet.impl->netWasQuantized = true;
    dstNet.setInputsNames(impl->netInputLayer->outNames);
    dstNet.setPreferableBackend(prefBackend);
    dstNet.setPreferableTarget(prefTarget);
    dstNet.enableFusion(originalFusion);

    for (Impl::MapIdToLayerData::iterator it = impl->layers.begin(); it != impl->layers.end(); it++)
    {
        LayerData ld = it->second;
        if (ld.id == 0)
        {
            LayerData &quantInpLd = dstNet.impl->layers[0];
            quantInpLd.dtype = inputsDtype;
            quantInpLd.params.set("scales", DictValue::arrayReal(scales[0].data(), scales[0].size()));
            quantInpLd.params.set("zeropoints", DictValue::arrayInt(zeropoints[0].data(), zeropoints[0].size()));
            continue;
        }

        std::vector<LayerPin> inpPins = ld.inputBlobsId;
        // Fill input and output scales/zeropoints for the layer
        std::vector<std::vector<float> > inp_out_sc(2);
        std::vector<std::vector<int> > inp_out_zp(2);
        for (int i = 0; i < inpPins.size(); i++)
        {
            LayerPin &pin = inpPins[i];
            inp_out_sc[0].push_back(scales[pin.lid][pin.oid]);
            inp_out_zp[0].push_back(zeropoints[pin.lid][pin.oid]);
        }
        inp_out_sc[1] = scales[ld.id];
        inp_out_zp[1] = zeropoints[ld.id];

        // Quantize layer
        Ptr<Layer> layer = ld.layerInstance;
        if (layer->tryQuantize(inp_out_sc, inp_out_zp, ld.params))
        {
            ld.type += "Int8";
            ld.dtype = CV_8S;
        }
        ld.params.set("scales", DictValue::arrayReal(inp_out_sc[1].data(), inp_out_sc[1].size()));
        ld.params.set("zeropoints", DictValue::arrayInt(inp_out_zp[1].data(), inp_out_zp[1].size()));

        // Check and add quantize/dequantize node before layer
        for (int i = 0; i < inpPins.size(); i++)
        {
            LayerPin &pin = inpPins[i];
            LayerData &inpLd = dstNet.impl->getLayerData(impl->getLayerName(pin.lid));
            pin.lid = inpLd.id;
            if (inpLd.dtype != ld.dtype)
            {
                String layerName = (inpLd.dtype == CV_32F && ld.dtype == CV_8S) ? cv::format("quantize/%s/%d", inpLd.name.c_str(), pin.oid)
                                                                                : cv::format("dequantize/%s/%d", inpLd.name.c_str(), pin.oid);
                // Check if quantize/dequantize node for the input layer already exists
                if (dstNet.impl->getLayerId(layerName) >= 0)
                {
                    pin.lid = dstNet.impl->getLayerId(layerName);
                    pin.oid = 0;
                }
                else
                {
                    LayerParams lp;
                    lp.set("scales", inp_out_sc[0][i]);
                    lp.set("zeropoints", inp_out_zp[0][i]);
                    lp.name = layerName;
                    lp.type = (inpLd.dtype == CV_32F && ld.dtype == CV_8S) ? "Quantize" : "Dequantize";
                    int newLid = dstNet.addLayer(lp.name, lp.type, ld.dtype, lp);
                    dstNet.connect(pin.lid, pin.oid, newLid, 0);
                    pin.lid = newLid; pin.oid = 0;
                }
            }
        }

        // Add quantized layer to Net and connect to its inputs.
        int newLid = dstNet.addLayer(ld.name, ld.type, ld.dtype, ld.params);
        for( int i = 0; i < inpPins.size(); i++ )
            dstNet.connect(inpPins[i].lid, inpPins[i].oid, newLid, i);

        // If the layer is a output layer, add quantize/dequantize node after it based on output's data type.
        if (ld.requiredOutputs.size() == 0 && ld.dtype != outputsDtype)
        {
            LayerParams lp;
            lp.set("scales", inp_out_sc[1][0]);
            lp.set("zeropoints", inp_out_zp[1][0]);
            lp.name = ((ld.dtype == CV_32F && outputsDtype == CV_8S) ? "quantize/" : "dequantize/") + ld.name;
            lp.type = (ld.dtype == CV_32F && outputsDtype == CV_8S) ? "Quantize" : "Dequantize";
            dstNet.addLayerToPrev(lp.name, lp.type, outputsDtype, lp);
        }
    }
    // Restore FP32 Net's backend, target and fusion
    setPreferableBackend(prefBackend);
    setPreferableTarget(prefTarget);
    enableFusion(originalFusion);
    return dstNet;
}

void Net::getInputDetails(std::vector<float>& scales, std::vector<int>& zeropoints) const
{
    if (!impl->netWasQuantized)
        CV_Error(Error::StsBadFunc, "Net isn't quantized");

    LayerParams &lp = impl->layers[0].params;
    DictValue sc = lp.get("scales");
    DictValue zp = lp.get("zeropoints");

    for (int i = 0; i < sc.size(); i++)
    {
        scales.push_back(sc.get<float>(i));
        zeropoints.push_back(zp.get<int>(i));
    }
}

void Net::getOutputDetails(std::vector<float>& scales, std::vector<int>& zeropoints) const
{
    if (!impl->netWasQuantized)
        CV_Error(Error::StsBadFunc, "Net isn't quantized");

    std::vector<int> outLayerIds = getUnconnectedOutLayers();
    for (auto &lid : outLayerIds)
    {
        LayerParams &lp = impl->layers[lid].params;
        DictValue sc = lp.get("scales");
        DictValue zp = lp.get("zeropoints");

        for (int i = 0; i < sc.size(); i++)
        {
            scales.push_back(sc.get<float>(i));
            zeropoints.push_back(zp.get<int>(i));
        }
    }
}

4924 4925
void Net::setPreferableBackend(int backendId)
{
A
Alexander Alekhin 已提交
4926 4927 4928
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG(backendId);

4929 4930 4931 4932 4933 4934 4935 4936 4937
    if (backendId == DNN_BACKEND_DEFAULT)
        backendId = (Backend)PARAM_DNN_BACKEND_DEFAULT;

    if (impl->netWasQuantized && backendId != DNN_BACKEND_OPENCV)
    {
        CV_LOG_WARNING(NULL, "DNN: Only default backend supports quantized networks");
        backendId = DNN_BACKEND_OPENCV;
    }

4938 4939 4940 4941 4942
#ifdef HAVE_INF_ENGINE
    if (backendId == DNN_BACKEND_INFERENCE_ENGINE)
        backendId = getInferenceEngineBackendTypeParam();
#endif

4943 4944 4945 4946 4947
    if( impl->preferableBackend != backendId )
    {
        impl->preferableBackend = backendId;
        impl->clear();
    }
4948 4949 4950 4951
}

void Net::setPreferableTarget(int targetId)
{
A
Alexander Alekhin 已提交
4952 4953 4954
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG(targetId);

4955 4956 4957 4958 4959 4960 4961
    if (impl->netWasQuantized && targetId != DNN_TARGET_CPU &&
        targetId != DNN_TARGET_OPENCL && targetId != DNN_TARGET_OPENCL_FP16)
    {
        CV_LOG_WARNING(NULL, "DNN: Only CPU and OpenCL/OpenCL FP16 target is supported by quantized networks");
        targetId = DNN_TARGET_CPU;
    }

4962 4963 4964
    if( impl->preferableTarget != targetId )
    {
        impl->preferableTarget = targetId;
L
Li Peng 已提交
4965 4966 4967
        if (IS_DNN_OPENCL_TARGET(targetId))
        {
#ifndef HAVE_OPENCL
4968 4969 4970 4971 4972 4973 4974
#ifdef HAVE_INF_ENGINE
            if (impl->preferableBackend == DNN_BACKEND_OPENCV)
#else
            if (impl->preferableBackend == DNN_BACKEND_DEFAULT ||
                impl->preferableBackend == DNN_BACKEND_OPENCV)
#endif  // HAVE_INF_ENGINE
                impl->preferableTarget = DNN_TARGET_CPU;
L
Li Peng 已提交
4975 4976 4977 4978 4979 4980
#else
            bool fp16 = ocl::Device::getDefault().isExtensionSupported("cl_khr_fp16");
            if (!fp16 && targetId == DNN_TARGET_OPENCL_FP16)
                impl->preferableTarget = DNN_TARGET_OPENCL;
#endif
        }
4981 4982
        impl->clear();
    }
4983 4984 4985 4986
}

void Net::setInputsNames(const std::vector<String> &inputBlobNames)
{
A
Alexander Alekhin 已提交
4987 4988
    CV_TRACE_FUNCTION();

4989 4990 4991
    impl->netInputLayer->setNames(inputBlobNames);
}

4992 4993 4994 4995 4996 4997 4998
void Net::setInputShape(const String &inputName, const MatShape& shape)
{
    CV_TRACE_FUNCTION();

    impl->netInputLayer->setInputShape(inputName, shape);
}

4999
void Net::setInput(InputArray blob, const String& name, double scalefactor, const Scalar& mean)
5000
{
A
Alexander Alekhin 已提交
5001 5002 5003
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(name, "name", name.c_str());

5004 5005 5006 5007 5008 5009 5010
    LayerPin pin;
    pin.lid = 0;
    pin.oid = impl->resolvePinOutputName(impl->getLayerData(pin.lid), name);

    if (!pin.valid())
        CV_Error(Error::StsObjectNotFound, "Requested blob \"" + name + "\" not found");

5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037
    Mat blob_ = blob.getMat();  // can't use InputArray directly due MatExpr stuff
    MatShape blobShape = shape(blob_);

    if (pin.lid == 0)
    {
        CV_Assert(!impl->netInputLayer.empty());
        const DataLayer& netInputLayer = *impl->netInputLayer.get();
        if (!netInputLayer.shapes.empty())
        {
            CV_CheckLT(pin.oid, (int)netInputLayer.shapes.size(), "");
            const MatShape& inputShapeLimitation = netInputLayer.shapes[pin.oid];
            if (!inputShapeLimitation.empty())
            {
                CV_CheckEQ(inputShapeLimitation.size(), blobShape.size(), "");
#if 0  // TODO: DNNTestNetwork.MobileNet_SSD_Caffe_Different_Width_Height/0
                const size_t dims = inputShapeLimitation.size();
                for (size_t dim = 0; dim < dims; dim++)
                {
                    if (dims >= 3 && dim == 0 && inputShapeLimitation[0] == 1)
                        continue;  // don't limit batch
                    CV_CheckEQ(inputShapeLimitation[dim], blobShape[dim], "");
                }
#endif
            }
        }
    }

5038
    LayerData &ld = impl->layers[pin.lid];
5039 5040 5041 5042
    const int numInputs = std::max(pin.oid+1, (int)ld.requiredOutputs.size());
    ld.outputBlobs.resize(numInputs);
    ld.outputBlobsWrappers.resize(numInputs);
    impl->netInputLayer->inputsData.resize(numInputs);
5043 5044
    impl->netInputLayer->scaleFactors.resize(numInputs);
    impl->netInputLayer->means.resize(numInputs);
5045 5046

    MatShape prevShape = shape(impl->netInputLayer->inputsData[pin.oid]);
5047 5048 5049
    bool oldShape = prevShape == blobShape;

    blob_.copyTo(impl->netInputLayer->inputsData[pin.oid]);
5050
    if (!oldShape)
5051
        ld.outputBlobs[pin.oid] = impl->netInputLayer->inputsData[pin.oid];
5052

5053 5054 5055 5056
    if (!ld.outputBlobsWrappers[pin.oid].empty())
    {
        ld.outputBlobsWrappers[pin.oid]->setHostDirty();
    }
5057 5058
    impl->netInputLayer->scaleFactors[pin.oid] = scalefactor;
    impl->netInputLayer->means[pin.oid] = mean;
5059 5060 5061 5062 5063 5064
    impl->netWasAllocated = impl->netWasAllocated && oldShape;
}

Mat Net::getParam(LayerId layer, int numParam)
{
    LayerData &ld = impl->getLayerData(layer);
D
Dmitry Kurtaev 已提交
5065
    std::vector<Mat> &layerBlobs = ld.getLayerInstance()->blobs;
5066 5067 5068 5069 5070 5071 5072 5073
    CV_Assert(numParam < (int)layerBlobs.size());
    return layerBlobs[numParam];
}

void Net::setParam(LayerId layer, int numParam, const Mat &blob)
{
    LayerData &ld = impl->getLayerData(layer);

D
Dmitry Kurtaev 已提交
5074
    std::vector<Mat> &layerBlobs = ld.getLayerInstance()->blobs;
5075 5076 5077 5078 5079 5080 5081 5082 5083 5084
    CV_Assert(numParam < (int)layerBlobs.size());
    //we don't make strong checks, use this function carefully
    layerBlobs[numParam] = blob;
}

int Net::getLayerId(const String &layer)
{
    return impl->getLayerId(layer);
}

5085 5086 5087 5088
static
string dumpLayerParameterSize(const string& name, const LayerParams& lp)
{
    std::ostringstream out(name, std::ios::ate);
5089
    DictValue param = lp.get(name);
5090 5091 5092 5093 5094 5095 5096 5097
    switch (param.size())
    {
        case 1: out << " : "; break;
        case 2: out << " (HxW): "; break;
        case 3: out << " (DxHxW): "; break;
        default:
            CV_LOG_INFO(NULL, format("DNN/dumpLayerParameterSize(): Unsupported '%s' size = %d", name.c_str(), param.size()));
            out << ": ";
5098
    }
5099 5100 5101 5102 5103
    for (size_t i = 0; i < param.size(); i++)
    {
        if (i > 0)
            out << " x ";
        out << param.get<int>(i);
5104 5105 5106 5107
    }
    return out.str();
}

5108 5109 5110
String Net::dump()
{
    CV_Assert(!empty());
5111

5112
    bool hasInput = !impl->netInputLayer->inputsData.empty();
5113

5114 5115 5116 5117 5118
    if (hasInput)
    {
        if (!impl->netWasAllocated)
            impl->setUpNet();
    }
5119

5120 5121
    return impl->dump();
}
5122

5123 5124 5125
string Net::Impl::dump()
{
    bool hasInput = !netInputLayer->inputsData.empty();
5126

5127
    std::ostringstream out;
5128
    const std::map<int, LayerData>& map = layers;
5129

5130
    Backend prefBackend = (Backend)preferableBackend;
5131 5132 5133 5134 5135
    std::vector<std::vector<int> > skippedLayers;
    std::vector<int> skipId;
    std::vector<int> allLayers(map.size(), -1);
    int idPrev = -1;
    Ptr<BackendNode> prevNode;
5136
    for (std::map<int, LayerData>::const_reverse_iterator rit = map.rbegin(); rit != map.rend(); ++rit)
5137
    {
5138
        std::map<int, Ptr<BackendNode> >::const_iterator itBackend = rit->second.backendNodes.find(prefBackend);
5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176
        if (prefBackend == DNN_BACKEND_OPENCV || itBackend == rit->second.backendNodes.end() ||
            itBackend->second.empty())
        {
                if (rit->second.skip)
                    skipId.push_back(rit->first);
                else if (!skipId.empty())
                {
                    if (prefBackend == DNN_BACKEND_OPENCV || prevNode.empty())
                        skipId.push_back(rit->first);
                    else if (idPrev != -1)
                        skipId.push_back(idPrev);

                    std::sort(skipId.begin(), skipId.end());
                    for (int i = 0; i < skipId.size(); i++) {
                        allLayers[skipId[i]] = skippedLayers.size();
                    }
                    skippedLayers.push_back(skipId);
                    skipId.clear();
                }
        }
        else
        {
            if (itBackend->second == prevNode)
                skipId.push_back(idPrev);
            else if (!skipId.empty())
            {
                skipId.push_back(idPrev);
                std::sort(skipId.begin(), skipId.end());
                for (int i = 0; i < skipId.size(); i++) {
                    allLayers[skipId[i]] = skippedLayers.size();
                }
                skippedLayers.push_back(skipId);
                skipId.clear();
            }
            idPrev = rit->first;
            prevNode = itBackend->second;
        }
    }
5177
    std::vector<string> colors = {"#ffffb3", "#fccde5", "#8dd3c7", "#bebada", "#80b1d3", "#fdb462", "#ff4848", "#b35151", "#b266ff"};
5178 5179 5180
    string backend;
    switch (prefBackend)
    {
5181 5182
        case DNN_BACKEND_DEFAULT: backend = "DEFAULT/"; break;
        case DNN_BACKEND_HALIDE: backend = "HALIDE/"; break;
5183 5184 5185
        case DNN_BACKEND_INFERENCE_ENGINE: // fallthru
        case DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019: backend = "DLIE/"; break;
        case DNN_BACKEND_INFERENCE_ENGINE_NGRAPH: backend = "NGRAPH/"; break;
5186
        case DNN_BACKEND_OPENCV: backend = "OCV/"; break;
5187
        case DNN_BACKEND_VKCOM: backend = "VULKAN/"; break;
5188
        case DNN_BACKEND_CUDA: backend = "CUDA/"; break;
5189
        case DNN_BACKEND_WEBNN: backend = "WEBNN/"; break;
5190
        // don't use default:
5191
    }
5192
    out << "digraph G {\n";
5193
    // Add nodes
5194
    for (std::map<int, LayerData>::const_iterator it = map.begin(); it != map.end(); ++it)
5195
    {
5196 5197 5198 5199 5200 5201
        const LayerData& ld = it->second;
        string name = ld.params.name;
        std::vector<int> clusterIds(1, it->first);
        if (allLayers[it->first] == -1 && !name.empty())
        {
            out << "\t\"" << name << "\" [label=\"";
5202 5203
        }
        else if (name.empty() || it->first != skippedLayers[allLayers[it->first]][0])
5204
        {
5205
            continue;
5206 5207 5208
        }
        else // first node in cluster : it->first == skippedLayers[allLayers[it->first]][0]
        {
5209
            int cluster = allLayers[it->first];
5210 5211
            out << "\t\"" << "cluster_" << cluster << "\" [label=\"{";
            clusterIds = skippedLayers[allLayers[it->first]]; // vertices in current cluster
5212
        }
5213
        for (int i = 0; i < clusterIds.size(); i++)
5214
        {
5215 5216
            CV_DbgAssert(map.find(clusterIds[i]) != map.end());
            const LayerParams& lp = map.find(clusterIds[i])->second.params;
5217 5218 5219 5220
            if (!lp.name.empty()) {
                if (i > 0) {
                    out << " | ";
                }
5221 5222 5223 5224
                out << lp.name << "\\n" << lp.type << "\\n";  // align center
                if (lp.has("kernel_size"))
                {
                    string kernel = dumpLayerParameterSize("kernel_size", lp);
5225
                    out << kernel;
5226
                    out << "\\l";  // align left
5227 5228 5229
                } else if (lp.has("kernel_h") && lp.has("kernel_w")) {
                    DictValue h = lp.get("kernel_h");
                    DictValue w = lp.get("kernel_w");
5230 5231
                    out << "kernel (HxW): " << h << " x " << w;
                    out << "\\l";  // align left
5232 5233
                }
                if (lp.has("stride")) {
5234
                    string stride = dumpLayerParameterSize("stride", lp);
5235
                    out << stride;
5236
                    out << "\\l";  // align left
5237 5238 5239
                } else if (lp.has("stride_h") && lp.has("stride_w")) {
                    DictValue h = lp.get("stride_h");
                    DictValue w = lp.get("stride_w");
5240 5241
                    out << "stride (HxW): " << h << " x " << w;
                    out << "\\l";  // align left
5242 5243
                }
                if (lp.has("dilation")) {
5244
                    string dilation = dumpLayerParameterSize("dilation", lp);
5245
                    out << dilation;
5246
                    out << "\\l";  // align left
5247 5248 5249
                } else if (lp.has("dilation_h") && lp.has("dilation_w")) {
                    DictValue h = lp.get("dilation_h");
                    DictValue w = lp.get("dilation_w");
5250 5251
                    out << "dilation (HxW): " << h << " x " << w;
                    out << "\\l";  // align left
5252 5253 5254 5255
                }
                if (lp.has("pad")) {
                    DictValue pad = lp.get("pad");
                    out << "pad ";
5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270
                    switch (pad.size())
                    {
                        case 1: out << ": " << pad; break;
                        case 2:
                            out << "(HxW): (" << pad.get<int>(0) << " x " << pad.get<int>(1) << ")";
                            break;
                        case 4:
                            out << "(HxW): (" << pad.get<int>(0) << ", " << pad.get<int>(2)
                                << ") x (" << pad.get<int>(1) << ", " << pad.get<int>(3) << ")";
                            break;
                        case 6:
                            out << "(DxHxW): (" << pad.get<int>(0) << ", " << pad.get<int>(3)
                                << ") x (" << pad.get<int>(1) << ", " << pad.get<int>(4)
                                << ") x (" << pad.get<int>(2) << ", " << pad.get<int>(5) << ")";
                            break;
5271 5272
                        default: CV_Error(Error::StsNotImplemented,  format("Unsupported pad size = %d", pad.size()));
                    }
5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322
                    out << "\\l";  // align left
                } else if (lp.has("pad_l") && lp.has("pad_t") && lp.has("pad_r") && lp.has("pad_b")) {
                    DictValue l = lp.get("pad_l");
                    DictValue t = lp.get("pad_t");
                    DictValue r = lp.get("pad_r");
                    DictValue b = lp.get("pad_b");
                    out << "pad (HxW): (" << t << ", " << b << ") x (" << l << ", " << r << ")";
                    out << "\\l";  // align left
                }
                else if (lp.has("pooled_w") || lp.has("pooled_h")) {
                    DictValue h = lp.get("pooled_h");
                    DictValue w = lp.get("pooled_w");
                    out << "pad pooled (HxW): " << h << " x " << w;
                    out << "\\l";  // align left
                }
                if (lp.has("pool")) {
                    out << "pool: " << lp.get("pool");
                    out << "\\l";  // align left
                }
                if (lp.has("global_pooling")) {
                    out << "global_pooling: " << lp.get("global_pooling");
                    out << "\\l";  // align left
                }
                if (lp.has("group")) {
                    out << "group: " << lp.get("group");
                    out << "\\l";  // align left
                }
            }
        }
        if (!ld.outputBlobs.empty())
        {
            out << "output: " << ld.outputBlobs[0].size;
            out << "\\l";  // align left
        }

        Ptr<BackendNode> layerBackend;
        std::map<int, Ptr<BackendNode> >::const_iterator ibn = ld.backendNodes.find(prefBackend);
        if (ibn != ld.backendNodes.end())
            layerBackend = ibn->second;
        out << (!layerBackend.empty() ? backend : "OCV/");
        int colorId = 0;
        const Target target = ld.layerInstance.empty()
                         ? DNN_TARGET_CPU
                                 : (Target)(ld.layerInstance->preferableTarget);  // TODO fix preferableTarget type
        switch (target)
        {
            case DNN_TARGET_CPU: out << "CPU"; colorId = layerBackend.empty() ? 0 : 5; break;
            case DNN_TARGET_OPENCL: out << "OCL"; colorId = 1; break;
            case DNN_TARGET_OPENCL_FP16: out << "OCL_FP16"; colorId = 2; break;
            case DNN_TARGET_MYRIAD: out << "MYRIAD"; colorId = 3; break;
5323
            case DNN_TARGET_HDDL: out << "HDDL"; colorId = 8; break;
5324
            case DNN_TARGET_VULKAN: out << "VULKAN"; colorId = 7; break;
5325
            case DNN_TARGET_FPGA: out << "FPGA"; colorId = 4; break;
5326 5327
            case DNN_TARGET_CUDA: out << "CUDA"; colorId = 5; break;
            case DNN_TARGET_CUDA_FP16: out << "CUDA_FP16"; colorId = 6; break;
5328 5329
            // don't use default:
        }
5330
        CV_Assert(colorId < colors.size());
5331 5332 5333 5334 5335
        out << "\\n";  // align center
        out << ((clusterIds.size() == 1)? "\" " : " }\" ");
        out << "fillcolor=\"" << colors[colorId] << "\" ";
        out << "style=filled ";
        out << "shape=" << ((clusterIds.size() == 1)? "box" : "record") << "]\n";
5336 5337 5338
    }
    out << '\n';
    // Add edges
5339
    int inputsSize = hasInput ? netInputLayer->outNames.size() : 0;
5340
    for (std::map<int, LayerData>::const_iterator it = map.begin(); it != map.end(); ++it)
5341
    {
5342
        const LayerData& ld = it->second;
5343 5344
        if (allLayers[it->first] == -1)  // node
        {
5345
            for (int i = 0; i < ld.consumers.size(); i++)
5346
            {
5347
                int outId = ld.consumers[i].lid;
5348
                if (it == map.begin() && inputsSize > 1)
5349
                    out << "\t\"" << ld.name << "_" << i << "\"" << " -> ";
5350
                else
5351
                    out << "\t\"" << ld.name << "\"" << " -> ";
5352
                if (allLayers[outId] == -1)  // node
5353 5354 5355 5356
                {
                    CV_DbgAssert(map.find(outId) != map.end());
                    out << "\"" << map.find(outId)->second.name << "\"\n";
                }
5357
                else  // cluster
5358 5359 5360
                {
                    out << "\"" << "cluster_" << allLayers[outId] << "\"\n";
                }
5361 5362 5363 5364
            }
        }
        else if (it->first == skippedLayers[allLayers[it->first]].back())  // edges from last layer in cluster
        {
5365
            for (int i = 0; i < ld.consumers.size(); i++)
5366
            {
5367 5368 5369 5370 5371 5372
                int outId = ld.consumers[i].lid;
                if (allLayers[outId] == -1) // node
                {
                    CV_DbgAssert(map.find(outId) != map.end());
                    out << "\t\"" << "cluster_" << allLayers[it->first] << "\"" << " -> ";
                    out << "\"" << map.find(outId)->second.name << "\"\n";
5373 5374
                }
                else if (allLayers[outId] != allLayers[it->first]) { // another cluster
5375 5376
                    out << "\t\"" << "cluster_" << allLayers[it->first] << "\"" << " -> ";
                    out << "\"" << "cluster_" << allLayers[outId] << "\"\n";
5377 5378 5379 5380
                }
            }
        }
    }
5381
    out << "}\n";
5382 5383 5384 5385 5386 5387 5388 5389 5390
    return out.str();
}

void Net::dumpToFile(const String& path) {
    std::ofstream file(path.c_str());
    file << dump();
    file.close();
}

5391 5392 5393
Ptr<Layer> Net::getLayer(LayerId layerId)
{
    LayerData &ld = impl->getLayerData(layerId);
A
abratchik 已提交
5394
    return ld.getLayerInstance();
5395 5396 5397 5398 5399 5400 5401
}

std::vector<Ptr<Layer> > Net::getLayerInputs(LayerId layerId)
{
    LayerData &ld = impl->getLayerData(layerId);

    std::vector<Ptr<Layer> > inputLayers;
D
Dimitri Gerin 已提交
5402 5403 5404
    inputLayers.reserve(ld.inputBlobsId.size());
    for (int i = 0; i < ld.inputBlobsId.size(); ++i) {
        inputLayers.push_back(getLayer(ld.inputBlobsId[i].lid));
5405 5406 5407 5408 5409 5410
    }
    return inputLayers;
}

std::vector<String> Net::getLayerNames() const
{
5411 5412
    CV_TRACE_FUNCTION();

5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447
    std::vector<String> res;
    res.reserve(impl->layers.size());

    Impl::MapIdToLayerData::iterator it;
    for (it = impl->layers.begin(); it != impl->layers.end(); it++)
    {
        if (it->second.id) //skip Data layer
            res.push_back(it->second.name);
    }

    return res;
}

bool Net::empty() const
{
    return impl->layers.size() <= 1; //first layer is default Data layer
}

std::vector<int> Net::getUnconnectedOutLayers() const
{
    std::vector<int> layersIds;

    Impl::MapIdToLayerData::iterator it;
    for (it = impl->layers.begin(); it != impl->layers.end(); it++)
    {
        int lid = it->first;
        LayerData &ld = it->second;

        if (ld.requiredOutputs.size() == 0)
            layersIds.push_back(lid);
    }

    return layersIds;
}

5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459
std::vector<String> Net::getUnconnectedOutLayersNames() const
{
    std::vector<int> ids = getUnconnectedOutLayers();
    const size_t n = ids.size();
    std::vector<String> names(n);
    for (size_t i = 0; i < n; ++i)
    {
        names[i] = impl->layers[ids[i]].name;
    }
    return names;
}

5460
void Net::getLayersShapes(const ShapesVec& netInputShapes,
5461 5462 5463
                          std::vector<int>& layersIds,
                          std::vector<ShapesVec>& inLayersShapes,
                          std::vector<ShapesVec>& outLayersShapes) const
5464
{
5465 5466 5467
    layersIds.clear();
    inLayersShapes.clear();
    outLayersShapes.clear();
5468 5469 5470 5471 5472 5473 5474

    Impl::LayersShapesMap inOutShapes;
    impl->getLayersShapes(netInputShapes, inOutShapes);

    for(Impl::LayersShapesMap::const_iterator it = inOutShapes.begin();
        it != inOutShapes.end(); it++)
    {
5475 5476 5477
        layersIds.push_back(it->first);
        inLayersShapes.push_back(it->second.in);
        outLayersShapes.push_back(it->second.out);
5478 5479 5480 5481
    }
}

void Net::getLayersShapes(const MatShape& netInputShape,
5482 5483 5484
                          std::vector<int>& layerIds,
                          std::vector<ShapesVec>& inLayersShapes,
                          std::vector<ShapesVec>& outLayersShapes) const
5485 5486 5487 5488 5489 5490 5491
{
    getLayersShapes(ShapesVec(1, netInputShape),
                    layerIds, inLayersShapes, outLayersShapes);
}

void Net::getLayerShapes(const MatShape& netInputShape,
                         const int layerId,
5492 5493
                         ShapesVec& inLayerShapes,
                         ShapesVec& outLayerShapes) const
5494 5495 5496 5497 5498 5499 5500 5501
{
    getLayerShapes(ShapesVec(1, netInputShape),
                   layerId, inLayerShapes, outLayerShapes);

}

void Net::getLayerShapes(const ShapesVec& netInputShapes,
                    const int layerId,
5502 5503
                    ShapesVec& inLayerShapes,
                    ShapesVec& outLayerShapes) const
5504 5505 5506
{
    LayerShapes shapes;
    impl->getLayerShapes(netInputShapes, layerId, shapes);
5507 5508
    inLayerShapes = shapes.in;
    outLayerShapes = shapes.out;
5509 5510 5511 5512
}

int64 Net::getFLOPS(const std::vector<MatShape>& netInputShapes) const
{
A
Alexander Alekhin 已提交
5513 5514
    CV_TRACE_FUNCTION();

5515 5516 5517
    int64 flops = 0;
    std::vector<int> ids;
    std::vector<std::vector<MatShape> > inShapes, outShapes;
5518
    getLayersShapes(netInputShapes, ids, inShapes, outShapes);
5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589
    CV_Assert(inShapes.size() == outShapes.size());
    CV_Assert(inShapes.size() == ids.size());

    for(int i = 0; i < ids.size(); i++)
    {
        flops += impl->layers[ids[i]].getLayerInstance()->getFLOPS(inShapes[i],
                                                                   outShapes[i]);
    }

    return flops;
}

int64 Net::getFLOPS(const MatShape& netInputShape) const
{
    return getFLOPS(std::vector<MatShape>(1, netInputShape));
}

int64 Net::getFLOPS(const int layerId,
              const std::vector<MatShape>& netInputShapes) const
{
    Impl::MapIdToLayerData::iterator layer = impl->layers.find(layerId);
    CV_Assert(layer != impl->layers.end());

    LayerShapes shapes;
    impl->getLayerShapes(netInputShapes, layerId, shapes);

    return layer->second.getLayerInstance()->getFLOPS(shapes.in, shapes.out);
}

int64 Net::getFLOPS(const int layerId,
              const MatShape& netInputShape) const
{
    return getFLOPS(layerId, std::vector<MatShape>(1, netInputShape));
}

void Net::getLayerTypes(std::vector<String>& layersTypes) const
{
    layersTypes.clear();

    std::map<String, int> layers;
    for (Impl::MapIdToLayerData::iterator it = impl->layers.begin();
         it != impl->layers.end(); it++)
    {
        if (layers.find(it->second.type) == layers.end())
            layers[it->second.type] = 0;
        layers[it->second.type]++;
    }

    for (std::map<String, int>::iterator it = layers.begin();
         it != layers.end(); it++)
    {
        layersTypes.push_back(it->first);
    }
}

int Net::getLayersCount(const String& layerType) const
{
    int count = 0;
    for (Impl::MapIdToLayerData::iterator it = impl->layers.begin();
         it != impl->layers.end(); it++)
    {
        if (it->second.type == layerType)
            count++;
    }
    return count;
}

void Net::getMemoryConsumption(const int layerId,
                               const std::vector<MatShape>& netInputShapes,
                               size_t& weights, size_t& blobs) const
{
A
Alexander Alekhin 已提交
5590 5591
    CV_TRACE_FUNCTION();

5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602
    Impl::MapIdToLayerData::iterator layer = impl->layers.find(layerId);
    CV_Assert(layer != impl->layers.end());

    weights = blobs = 0;

    for(int i = 0; i < layer->second.params.blobs.size(); i++)
    {
        const Mat& weightsBlob = layer->second.params.blobs[i];
        weights += weightsBlob.total()*weightsBlob.elemSize();
    }

5603 5604
    ShapesVec inLayerShapes, outLayerShapes;
    getLayerShapes(netInputShapes, layerId, inLayerShapes, outLayerShapes);
5605
    size_t elemSize = (impl->netWasQuantized) ? sizeof(char) : sizeof(float);
5606 5607
    for(int i = 0; i < outLayerShapes.size(); i++)
    {
5608
        blobs += total(outLayerShapes[i]) * elemSize;
5609 5610 5611 5612 5613 5614
    }
}

void Net::getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
                               size_t& weights, size_t& blobs) const
{
A
Alexander Alekhin 已提交
5615 5616
    CV_TRACE_FUNCTION();

5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647
    std::vector<int> layerIds;
    std::vector<size_t> w, b;
    getMemoryConsumption(netInputShapes, layerIds, w, b);

    weights = blobs = 0;
    for(int i = 0; i < layerIds.size(); i++)
    {
        weights += w[i];
        blobs += b[i];
    }
}

void Net::getMemoryConsumption(const int layerId,
                               const MatShape& netInputShape,
                               size_t& weights, size_t& blobs) const
{
    getMemoryConsumption(layerId, std::vector<MatShape>(1, netInputShape),
                         weights, blobs);
}

void Net::getMemoryConsumption(const MatShape& netInputShape,
                               size_t& weights, size_t& blobs) const
{
    getMemoryConsumption(std::vector<MatShape>(1, netInputShape),
                         weights, blobs);
}

void Net::getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
                                  std::vector<int>& layerIds, std::vector<size_t>& weights,
                                  std::vector<size_t>& blobs) const
{
A
Alexander Alekhin 已提交
5648 5649
    CV_TRACE_FUNCTION();

5650 5651 5652 5653
    layerIds.clear();
    weights.clear();
    blobs.clear();

5654
    std::vector<std::vector<MatShape> > inLayerShapes, outLayerShapes;
5655

5656
    getLayersShapes(netInputShapes, layerIds, inLayerShapes, outLayerShapes);
5657
    size_t elemSize = (impl->netWasQuantized) ? sizeof(char) : sizeof(float);
5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671
    for(int i = 0; i < layerIds.size(); i++)
    {
        int w = 0, b = 0;
        Impl::MapIdToLayerData::iterator layer = impl->layers.find(layerIds[i]);
        CV_Assert(layer != impl->layers.end());

        for(int j = 0; j < layer->second.params.blobs.size(); j++)
        {
            const Mat& weightsBlob = layer->second.params.blobs[j];
            w += weightsBlob.total()*weightsBlob.elemSize();
        }

        for(int j = 0; j < outLayerShapes[i].size(); j++)
        {
5672
            b += total(outLayerShapes[i][j]) * elemSize;
5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686
        }

        weights.push_back(w);
        blobs.push_back(b);
    }
}

void Net::getMemoryConsumption(const MatShape& netInputShape, std::vector<int>& layerIds,
                               std::vector<size_t>& weights, std::vector<size_t>& blobs) const
{
    getMemoryConsumption(std::vector<MatShape>(1, netInputShape), layerIds,
                         weights, blobs);
}

5687 5688 5689 5690 5691 5692 5693 5694 5695
void Net::enableFusion(bool fusion)
{
    if( impl->fusion != fusion )
    {
        impl->fusion = fusion;
        impl->clear();
    }
}

5696 5697
void Net::setHalideScheduler(const String& scheduler)
{
A
Alexander Alekhin 已提交
5698 5699 5700
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(scheduler, "scheduler", scheduler.c_str());

5701 5702 5703
    impl->halideConfigFile = scheduler;
}

5704 5705 5706
int64 Net::getPerfProfile(std::vector<double>& timings)
{
    timings = std::vector<double>(impl->layersTimings.begin() + 1, impl->layersTimings.end());
5707
    int64 total = (int64)std::accumulate(timings.begin(), timings.end(), 0.0);
5708 5709 5710
    return total;
}

5711 5712
//////////////////////////////////////////////////////////////////////////

5713
Layer::Layer() { preferableTarget = DNN_TARGET_CPU; }
5714 5715 5716 5717

Layer::Layer(const LayerParams &params)
    : blobs(params.blobs), name(params.name), type(params.type)
{
5718
    preferableTarget = DNN_TARGET_CPU;
5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732
}

void Layer::setParamsFrom(const LayerParams &params)
{
    blobs = params.blobs;
    name = params.name;
    type = params.type;
}

int Layer::inputNameToIndex(String)
{
    return -1;
}

5733
int Layer::outputNameToIndex(const String&)
5734
{
5735
    return 0;
5736 5737 5738 5739
}

bool Layer::supportBackend(int backendId)
{
5740
    return backendId == DNN_BACKEND_OPENCV;
5741 5742
}

5743 5744 5745 5746 5747 5748 5749 5750 5751 5752
Ptr<BackendNode> Layer::initCUDA(
    void*,
    const std::vector<Ptr<BackendWrapper>>&,
    const std::vector<Ptr<BackendWrapper>>&)
{
    CV_Error(Error::StsNotImplemented, "CUDA pipeline of " + type +
                                       " layers is not defined.");
    return Ptr<BackendNode>();
}

5753 5754 5755 5756 5757 5758 5759
Ptr<BackendNode> Layer::initVkCom(const std::vector<Ptr<BackendWrapper> > &)
{
    CV_Error(Error::StsNotImplemented, "VkCom pipeline of " + type +
                                       " layers is not defined.");
    return Ptr<BackendNode>();
}

5760 5761 5762 5763 5764 5765 5766
Ptr<BackendNode> Layer::initHalide(const std::vector<Ptr<BackendWrapper> > &)
{
    CV_Error(Error::StsNotImplemented, "Halide pipeline of " + type +
                                       " layers is not defined.");
    return Ptr<BackendNode>();
}

5767 5768 5769 5770 5771 5772 5773
Ptr<BackendNode> Layer::initInfEngine(const std::vector<Ptr<BackendWrapper> > &)
{
    CV_Error(Error::StsNotImplemented, "Inference Engine pipeline of " + type +
                                       " layers is not defined.");
    return Ptr<BackendNode>();
}

5774
Ptr<BackendNode> Layer::initNgraph(const std::vector<Ptr<BackendWrapper> > & inputs, const std::vector<Ptr<BackendNode> >& nodes)
5775 5776 5777 5778 5779 5780
{
    CV_Error(Error::StsNotImplemented, "Inference Engine pipeline of " + type +
                                       " layers is not defined.");
    return Ptr<BackendNode>();
}

5781 5782 5783 5784 5785 5786 5787
Ptr<BackendNode> Layer::initWebnn(const std::vector<Ptr<BackendWrapper> > & inputs, const std::vector<Ptr<BackendNode> >& nodes)
{
    CV_Error(Error::StsNotImplemented, "WebNN pipeline of " + type +
                                       " layers is not defined.");
    return Ptr<BackendNode>();
}

5788 5789 5790 5791
void Layer::applyHalideScheduler(Ptr<BackendNode>& node, const std::vector<Mat*> &inputs,
                                 const std::vector<Mat> &outputs, int targetId) const
{
#ifdef  HAVE_HALIDE
A
Alexander Alekhin 已提交
5792 5793
    CV_TRACE_FUNCTION();

5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833
    Halide::Var x("x"), y("y"), c("c"), n("n"), co("co"), ci("ci"),
                xo("xo"), xi("xi"), yo("yo"), yi("yi"), tile("tile");
    Halide::Func& top = node.dynamicCast<HalideBackendNode>()->funcs.back();

    int outW, outH, outC, outN;
    getCanonicalSize(outputs[0].size, &outW, &outH, &outC, &outN);

    if (targetId == DNN_TARGET_CPU)
    {
        if (outW == 1 && outH == 1)
        {
            if (outC + outN == 1)
                return;

            if (outC > 8)
              top.split(c, co, ci, 8)
                 .fuse(x, y, tile).fuse(co, tile, tile).fuse(n, tile, tile)
                 .parallel(tile)
                 .vectorize(ci, 8);
            else
              top.fuse(x, y, tile).fuse(c, tile, tile).fuse(n, tile, tile)
                 .parallel(tile);
        }
        else
        {
            if (outH > 2)
            {
                top.reorder(x, c, y)
                   .split(y, yo, yi, 2)
                   .fuse(yo, n, tile)
                   .parallel(tile)
                   .unroll(yi)
                   .vectorize(x, outW >= 16 ? 16 : outW);
            }
        }
    }
    else if (targetId == DNN_TARGET_OPENCL)
    {
        if (outW == 1 && outH == 1)
        {
D
Dmitry Kurtaev 已提交
5834
            int c_split = outC > 8 ? (outC > 16 ? 8 : 4) : outC;
5835 5836 5837 5838 5839 5840 5841 5842 5843
            top.split(c, co, ci, c_split)
               .fuse(x, y, tile).fuse(co, tile, tile).fuse(n, tile, tile)
               .gpu_blocks(tile)
               .gpu_threads(ci);
        }
        else
        {
            int x_split = outW > 8 ? (outW >= 32 ? 16 : 8) : outW;
            int y_split = outH > 8 ? (outH >= 32 ? 16 : 8) : outH;
D
Dmitry Kurtaev 已提交
5844 5845
            // Supported vectorization widths: 2, 3, 4, 8, 16
            int c_split = outC > 8 ? (outC > 16 ? 8 : 4) : std::min(4, outC);
5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863
            top.split(x, xo, xi, x_split).split(y, yo, yi, y_split)
               .split(c, co, ci, c_split)
               .gpu_blocks(xo, yo, co)
               .gpu_threads(xi, yi)
               .reorder(xi, yi, ci, xo, yo, co)
               .vectorize(ci);
        }
    }
    else
        CV_Error(Error::StsNotImplemented, "Unknown target identifier");
#endif  // HAVE_HALIDE
}

Ptr<BackendNode> Layer::tryAttach(const Ptr<BackendNode>& node)
{
    return Ptr<BackendNode>();
}

5864
bool Layer::setActivation(const Ptr<ActivationLayer>&) { return false; }
5865 5866 5867 5868 5869 5870 5871
bool Layer::tryFuse(Ptr<Layer>&) { return false; }
void Layer::getScaleShift(Mat& scale, Mat& shift) const
{
    scale = Mat();
    shift = Mat();
}

5872 5873 5874 5875 5876 5877
void Layer::getScaleZeropoint(float& scale, int& zeropoint) const
{
    scale = 1.f;
    zeropoint = 0;
}

5878 5879 5880 5881
void Layer::unsetAttached()
{
    setActivation(Ptr<ActivationLayer>());
}
5882

5883 5884 5885 5886 5887 5888 5889 5890 5891 5892
template <typename T>
static void vecToPVec(const std::vector<T> &v, std::vector<T*> &pv)
{
    pv.resize(v.size());
    for (size_t i = 0; i < v.size(); i++)
        pv[i] = const_cast<T*>(&v[i]);
}

void Layer::finalize(const std::vector<Mat> &inputs, std::vector<Mat> &outputs)
{
A
Alexander Alekhin 已提交
5893
    CV_TRACE_FUNCTION();
5894
    this->finalize((InputArrayOfArrays)inputs, (OutputArrayOfArrays)outputs);
5895 5896 5897 5898
}

void Layer::finalize(const std::vector<Mat*> &input, std::vector<Mat> &output)
{
H
Hamdi Sahloul 已提交
5899
    CV_UNUSED(input);CV_UNUSED(output);
5900 5901
}

5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913
void Layer::finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr)
{
    CV_TRACE_FUNCTION();
    std::vector<Mat> inputs, outputs;
    inputs_arr.getMatVector(inputs);
    outputs_arr.getMatVector(outputs);

    std::vector<Mat*> inputsp;
    vecToPVec(inputs, inputsp);
    this->finalize(inputsp, outputs);
}

5914 5915
std::vector<Mat> Layer::finalize(const std::vector<Mat> &inputs)
{
A
Alexander Alekhin 已提交
5916 5917
    CV_TRACE_FUNCTION();

5918 5919 5920 5921 5922
    std::vector<Mat> outputs;
    this->finalize(inputs, outputs);
    return outputs;
}

5923 5924 5925 5926 5927 5928
void Layer::forward(std::vector<Mat*> &input, std::vector<Mat> &output, std::vector<Mat> &internals)
{
    // We kept this method for compatibility. DNN calls it now only to support users' implementations.
}

void Layer::forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr)
5929 5930 5931 5932
{
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(name, "name", name.c_str());

5933
    Layer::forward_fallback(inputs_arr, outputs_arr, internals_arr);
5934 5935
}

L
Li Peng 已提交
5936
void Layer::forward_fallback(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr)
5937
{
A
Alexander Alekhin 已提交
5938
    CV_TRACE_FUNCTION();
L
Li Peng 已提交
5939
    CV_TRACE_ARG_VALUE(name, "name", name.c_str());
A
Alexander Alekhin 已提交
5940

L
Li Peng 已提交
5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976
    if (preferableTarget == DNN_TARGET_OPENCL_FP16 && inputs_arr.depth() == CV_16S)
    {
        std::vector<UMat> inputs;
        std::vector<UMat> outputs;
        std::vector<UMat> internals;

        std::vector<UMat> orig_inputs;
        std::vector<UMat> orig_outputs;
        std::vector<UMat> orig_internals;

        inputs_arr.getUMatVector(orig_inputs);
        outputs_arr.getUMatVector(orig_outputs);
        internals_arr.getUMatVector(orig_internals);

        inputs.resize(orig_inputs.size());
        for (size_t i = 0; i < orig_inputs.size(); i++)
            convertFp16(orig_inputs[i], inputs[i]);

        outputs.resize(orig_outputs.size());
        for (size_t i = 0; i < orig_outputs.size(); i++)
            outputs[i].create(shape(orig_outputs[i]), CV_32F);

        internals.resize(orig_internals.size());
        for (size_t i = 0; i < orig_internals.size(); i++)
            internals[i].create(shape(orig_internals[i]), CV_32F);

        forward(inputs, outputs, internals);

        for (size_t i = 0; i < outputs.size(); i++)
            convertFp16(outputs[i], orig_outputs[i]);

        // sync results back
        outputs_arr.assign(orig_outputs);
        internals_arr.assign(orig_internals);
        return;
    }
L
Li Peng 已提交
5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989
    std::vector<Mat> inpvec;
    std::vector<Mat> outputs;
    std::vector<Mat> internals;

    inputs_arr.getMatVector(inpvec);
    outputs_arr.getMatVector(outputs);
    internals_arr.getMatVector(internals);

    std::vector<Mat*> inputs(inpvec.size());
    for (int i = 0; i < inpvec.size(); i++)
        inputs[i] = &inpvec[i];

    this->forward(inputs, outputs, internals);
5990 5991 5992 5993

    // sync results back
    outputs_arr.assign(outputs);
    internals_arr.assign(internals);
5994 5995 5996 5997
}

void Layer::run(const std::vector<Mat> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals)
{
A
Alexander Alekhin 已提交
5998 5999
    CV_TRACE_FUNCTION();

6000 6001
    this->finalize(inputs, outputs);
    this->forward(inputs, outputs, internals);
6002 6003
}

6004 6005 6006 6007 6008 6009
bool Layer::tryQuantize(const std::vector<std::vector<float> > &scales,
                        const std::vector<std::vector<int> > &zeropoints, LayerParams& params)
{
    return false;
}

6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021
Layer::~Layer() {}

bool Layer::getMemoryShapes(const std::vector<MatShape> &inputs,
                            const int requiredOutputs,
                            std::vector<MatShape> &outputs,
                            std::vector<MatShape> &internals) const
{
    CV_Assert(inputs.size());
    outputs.assign(std::max(requiredOutputs, (int)inputs.size()), inputs[0]);
    return false;
}

6022 6023 6024 6025
bool Layer::updateMemoryShapes(const std::vector<MatShape> &inputs)
{
    return true;
}
6026 6027
//////////////////////////////////////////////////////////////////////////

6028
Mutex& getLayerFactoryMutex()
6029
{
6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044
    static Mutex* volatile instance = NULL;
    if (instance == NULL)
    {
        cv::AutoLock lock(getInitializationMutex());
        if (instance == NULL)
            instance = new Mutex();
    }
    return *instance;
}

static LayerFactory_Impl& getLayerFactoryImpl_()
{
    static LayerFactory_Impl impl;
    return impl;
}
6045

6046
LayerFactory_Impl& getLayerFactoryImpl()
6047
{
6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058
    static LayerFactory_Impl* volatile instance = NULL;
    if (instance == NULL)
    {
        cv::AutoLock lock(getLayerFactoryMutex());
        if (instance == NULL)
        {
            instance = &getLayerFactoryImpl_();
            initializeLayerFactory();
        }
    }
    return *instance;
6059 6060
}

6061
void LayerFactory::registerLayer(const String &type, Constructor constructor)
6062
{
A
Alexander Alekhin 已提交
6063 6064 6065
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

6066
    cv::AutoLock lock(getLayerFactoryMutex());
D
Dmitry Kurtaev 已提交
6067
    LayerFactory_Impl::iterator it = getLayerFactoryImpl().find(type);
6068

6069
    if (it != getLayerFactoryImpl().end())
6070
    {
6071
        if (it->second.back() == constructor)
D
Dmitry Kurtaev 已提交
6072
            CV_Error(cv::Error::StsBadArg, "Layer \"" + type + "\" already was registered");
6073
        it->second.push_back(constructor);
6074
    }
D
Dmitry Kurtaev 已提交
6075
    getLayerFactoryImpl().insert(std::make_pair(type, std::vector<Constructor>(1, constructor)));
6076 6077
}

A
Alexander Alekhin 已提交
6078
void LayerFactory::unregisterLayer(const String &type)
6079
{
A
Alexander Alekhin 已提交
6080 6081 6082
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

6083
    cv::AutoLock lock(getLayerFactoryMutex());
6084

D
Dmitry Kurtaev 已提交
6085
    LayerFactory_Impl::iterator it = getLayerFactoryImpl().find(type);
6086 6087 6088 6089 6090 6091 6092
    if (it != getLayerFactoryImpl().end())
    {
        if (it->second.size() > 1)
            it->second.pop_back();
        else
            getLayerFactoryImpl().erase(it);
    }
6093 6094
}

R
rogday 已提交
6095 6096 6097 6098 6099 6100 6101
bool LayerFactory::isLayerRegistered(const std::string& type)
{
    cv::AutoLock lock(getLayerFactoryMutex());
    auto& registeredLayers = getLayerFactoryImpl();
    return registeredLayers.find(type) != registeredLayers.end();
}

A
Alexander Alekhin 已提交
6102
Ptr<Layer> LayerFactory::createLayerInstance(const String &type, LayerParams& params)
6103
{
A
Alexander Alekhin 已提交
6104 6105 6106
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

6107
    cv::AutoLock lock(getLayerFactoryMutex());
D
Dmitry Kurtaev 已提交
6108
    LayerFactory_Impl::const_iterator it = getLayerFactoryImpl().find(type);
6109

6110
    if (it != getLayerFactoryImpl().end())
6111
    {
6112 6113
        CV_Assert(!it->second.empty());
        return it->second.back()(params);
6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141
    }
    else
    {
        return Ptr<Layer>(); //NULL
    }
}

BackendNode::BackendNode(int backendId) : backendId(backendId) {}

BackendNode::~BackendNode() {};

BackendWrapper::BackendWrapper(int backendId, int targetId)
    : backendId(backendId), targetId(targetId) {}

BackendWrapper::BackendWrapper(int targetId, const cv::Mat& m)
{
    CV_Error(Error::StsNotImplemented,
             "Constructor of backend wrapper must be implemented");
}

BackendWrapper::BackendWrapper(const Ptr<BackendWrapper>& base, const MatShape& shape)
{
    CV_Error(Error::StsNotImplemented,
             "Constructor of backend wrapper must be implemented");
}

BackendWrapper::~BackendWrapper() {}

6142
Net readNet(const String& _model, const String& _config, const String& _framework)
6143
{
6144
    String framework = toLowerCase(_framework);
6145 6146
    String model = _model;
    String config = _config;
6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174
    const std::string modelExt = model.substr(model.rfind('.') + 1);
    const std::string configExt = config.substr(config.rfind('.') + 1);
    if (framework == "caffe" || modelExt == "caffemodel" || configExt == "caffemodel" ||
                                modelExt == "prototxt" || configExt == "prototxt")
    {
        if (modelExt == "prototxt" || configExt == "caffemodel")
            std::swap(model, config);
        return readNetFromCaffe(config, model);
    }
    if (framework == "tensorflow" || modelExt == "pb" || configExt == "pb" ||
                                     modelExt == "pbtxt" || configExt == "pbtxt")
    {
        if (modelExt == "pbtxt" || configExt == "pb")
            std::swap(model, config);
        return readNetFromTensorflow(model, config);
    }
    if (framework == "torch" || modelExt == "t7" || modelExt == "net" ||
                                configExt == "t7" || configExt == "net")
    {
        return readNetFromTorch(model.empty() ? config : model);
    }
    if (framework == "darknet" || modelExt == "weights" || configExt == "weights" ||
                                  modelExt == "cfg" || configExt == "cfg")
    {
        if (modelExt == "cfg" || configExt == "weights")
            std::swap(model, config);
        return readNetFromDarknet(config, model);
    }
6175 6176 6177 6178 6179 6180 6181
    if (framework == "dldt" || modelExt == "bin" || configExt == "bin" ||
                               modelExt == "xml" || configExt == "xml")
    {
        if (modelExt == "xml" || configExt == "bin")
            std::swap(model, config);
        return readNetFromModelOptimizer(config, model);
    }
6182 6183 6184 6185
    if (framework == "onnx" || modelExt == "onnx")
    {
        return readNetFromONNX(model);
    }
6186
    CV_Error(Error::StsError, "Cannot determine an origin framework of files: " +
6187
                                      model + (config.empty() ? "" : ", " + config));
6188 6189
}

6190 6191
Net readNet(const String& _framework, const std::vector<uchar>& bufferModel,
            const std::vector<uchar>& bufferConfig)
6192
{
6193
    String framework = toLowerCase(_framework);
6194 6195 6196 6197 6198 6199 6200 6201 6202
    if (framework == "caffe")
        return readNetFromCaffe(bufferConfig, bufferModel);
    else if (framework == "tensorflow")
        return readNetFromTensorflow(bufferModel, bufferConfig);
    else if (framework == "darknet")
        return readNetFromDarknet(bufferConfig, bufferModel);
    else if (framework == "torch")
        CV_Error(Error::StsNotImplemented, "Reading Torch models from buffers");
    else if (framework == "dldt")
6203
        return readNetFromModelOptimizer(bufferConfig, bufferModel);
6204 6205 6206
    CV_Error(Error::StsError, "Cannot determine an origin framework with a name " + framework);
}

6207 6208 6209 6210 6211
Net readNetFromModelOptimizer(const String &xml, const String &bin)
{
    return Net::readFromModelOptimizer(xml, bin);
}

6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227
Net readNetFromModelOptimizer(const std::vector<uchar>& bufferCfg, const std::vector<uchar>& bufferModel)
{
    return Net::readFromModelOptimizer(bufferCfg, bufferModel);
}

Net readNetFromModelOptimizer(
        const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize,
        const uchar* bufferWeightsPtr, size_t bufferWeightsSize
)
{
    return Net::readFromModelOptimizer(
        bufferModelConfigPtr, bufferModelConfigSize,
        bufferWeightsPtr, bufferWeightsSize
    );
}

6228
CV__DNN_INLINE_NS_END
6229
}} // namespace