dnn.cpp 129 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 "op_vkcom.hpp"
46 47 48 49 50 51
#include "halide_scheduler.hpp"
#include <set>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <iterator>
52
#include <numeric>
53 54 55
#include <opencv2/dnn/shape_utils.hpp>
#include <opencv2/imgproc.hpp>

56
#include <opencv2/core/utils/configuration.private.hpp>
57
#include <opencv2/core/utils/logger.hpp>
58

59 60
namespace cv {
namespace dnn {
61
CV__DNN_INLINE_NS_BEGIN
62

luz.paz's avatar
luz.paz committed
63
// this option is useful to run valgrind memory errors detection
64 65
static bool DNN_DISABLE_MEMORY_OPTIMIZATIONS = utils::getConfigurationParameterBool("OPENCV_DNN_DISABLE_MEMORY_OPTIMIZATIONS", false);

Alexander Alekhin's avatar
Alexander Alekhin committed
66
#ifdef HAVE_OPENCL
67
static bool DNN_OPENCL_ALLOW_ALL_DEVICES = utils::getConfigurationParameterBool("OPENCV_DNN_OPENCL_ALLOW_ALL_DEVICES", false);
Alexander Alekhin's avatar
Alexander Alekhin committed
68
#endif
69

70 71 72 73 74 75 76 77
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
);

78 79 80 81
// 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);
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
using std::vector;
using std::map;
using std::make_pair;
using std::set;

namespace
{
    typedef std::vector<MatShape> ShapesVec;

    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;}
    };
}

104
Mat blobFromImage(InputArray image, double scalefactor, const Size& size,
105
                  const Scalar& mean, bool swapRB, bool crop, int ddepth)
106
{
107 108
    CV_TRACE_FUNCTION();
    Mat blob;
109
    blobFromImage(image, blob, scalefactor, size, mean, swapRB, crop, ddepth);
110
    return blob;
111 112
}

113
void blobFromImage(InputArray image, OutputArray blob, double scalefactor,
114
                   const Size& size, const Scalar& mean, bool swapRB, bool crop, int ddepth)
115
{
116
    CV_TRACE_FUNCTION();
117
    std::vector<Mat> images(1, image.getMat());
118
    blobFromImages(images, blob, scalefactor, size, mean, swapRB, crop, ddepth);
119 120
}

121
Mat blobFromImages(InputArrayOfArrays images, double scalefactor, Size size,
122
                   const Scalar& mean, bool swapRB, bool crop, int ddepth)
123
{
124
    CV_TRACE_FUNCTION();
125
    Mat blob;
126
    blobFromImages(images, blob, scalefactor, size, mean, swapRB, crop, ddepth);
127 128 129 130
    return blob;
}

void blobFromImages(InputArrayOfArrays images_, OutputArray blob_, double scalefactor,
131
                    Size size, const Scalar& mean_, bool swapRB, bool crop, int ddepth)
132 133
{
    CV_TRACE_FUNCTION();
134 135 136 137
    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");
138
        CV_Assert(mean_ == Scalar() && "Mean subtraction is not supported for CV_8U blob depth");
139 140
    }

141 142 143
    std::vector<Mat> images;
    images_.getMatVector(images);
    CV_Assert(!images.empty());
144 145 146 147 148 149 150
    for (int i = 0; i < images.size(); i++)
    {
        Size imgSize = images[i].size();
        if (size == Size())
            size = imgSize;
        if (size != imgSize)
        {
151 152 153 154
            if(crop)
            {
              float resizeFactor = std::max(size.width / (float)imgSize.width,
                                            size.height / (float)imgSize.height);
155
              resize(images[i], images[i], Size(), resizeFactor, resizeFactor, INTER_LINEAR);
156 157 158 159 160 161
              Rect crop(Point(0.5 * (images[i].cols - size.width),
                              0.5 * (images[i].rows - size.height)),
                        size);
              images[i] = images[i](crop);
            }
            else
162
              resize(images[i], images[i], size, 0, 0, INTER_LINEAR);
163
        }
164
        if(images[i].depth() == CV_8U && ddepth == CV_32F)
165 166 167 168 169 170 171 172 173 174 175 176 177
            images[i].convertTo(images[i], CV_32F);
        Scalar mean = mean_;
        if (swapRB)
            std::swap(mean[0], mean[2]);

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

    size_t i, nimages = images.size();
    Mat image0 = images[0];
    int nch = image0.channels();
    CV_Assert(image0.dims == 2);
178
    Mat image;
179 180
    if (nch == 3 || nch == 4)
    {
181
        int sz[] = { (int)nimages, nch, image0.rows, image0.cols };
182
        blob_.create(4, sz, ddepth);
183
        Mat blob = blob_.getMat();
184 185 186 187 188
        Mat ch[4];

        for( i = 0; i < nimages; i++ )
        {
            image = images[i];
189
            CV_Assert(image.depth() == blob_.depth());
190 191 192 193
            nch = image.channels();
            CV_Assert(image.dims == 2 && (nch == 3 || nch == 4));
            CV_Assert(image.size() == image0.size());

194
            for( int j = 0; j < nch; j++ )
195
                ch[j] = Mat(image.rows, image.cols, ddepth, blob.ptr((int)i, j));
196 197 198 199 200 201 202 203 204
            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 };
205
       blob_.create(4, sz, ddepth);
206
       Mat blob = blob_.getMat();
207 208 209 210

       for( i = 0; i < nimages; i++ )
       {
           Mat image = images[i];
211
           CV_Assert(image.depth() == blob_.depth());
212 213 214 215
           nch = image.channels();
           CV_Assert(image.dims == 2 && (nch == 1));
           CV_Assert(image.size() == image0.size());

216
           image.copyTo(Mat(image.rows, image.cols, ddepth, blob.ptr((int)i, 0)));
217 218 219 220
       }
    }
}

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
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));
    }
}

246 247 248
class OpenCLBackendWrapper : public BackendWrapper
{
public:
249
    OpenCLBackendWrapper(Mat& m) : BackendWrapper(DNN_BACKEND_OPENCV, DNN_TARGET_OPENCL)
250 251 252 253 254 255 256
    {
        m.copyTo(umat);
        host = &m;
        hostDirty = false;
    }

    OpenCLBackendWrapper(const Ptr<BackendWrapper>& baseBuffer, Mat& m)
257
        : BackendWrapper(DNN_BACKEND_OPENCV, DNN_TARGET_OPENCL)
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    {
        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.
311
    virtual void copyToHost() CV_OVERRIDE
312 313 314 315
    {
        umat.copyTo(*host);
    }

316
    virtual void setHostDirty() CV_OVERRIDE
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    {
        hostDirty = true;
    };

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

private:
    UMat umat;
    Mat* host;
    bool hostDirty;
};

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
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
    {
        return lid < r.lid || lid == r.lid && oid < r.oid;
    }

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

struct LayerData
{
367
    LayerData() : id(-1), skip(false), flag(0) {}
368
    LayerData(int _id, const String &_name, const String &_type, LayerParams &_params)
369
        : id(_id), name(_name), type(_type), params(_params), skip(false), flag(0)
370
    {
371 372
        CV_TRACE_FUNCTION();

373 374 375 376 377 378 379 380 381 382 383 384 385 386
        //add logging info
        params.name = name;
        params.type = type;
    }

    int id;
    String name;
    String type;
    LayerParams params;

    std::vector<LayerPin> inputBlobsId;
    std::set<int> inputLayersId;
    std::set<int> requiredOutputs;
    std::vector<LayerPin> consumers;
387 388
    std::vector<Ptr<BackendWrapper> > outputBlobsWrappers;
    std::vector<Ptr<BackendWrapper> > inputBlobsWrappers;
389
    std::vector<Ptr<BackendWrapper> > internalBlobsWrappers;
390 391 392 393 394 395 396 397

    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.
398
    bool skip;
399 400 401 402 403

    int flag;

    Ptr<Layer> getLayerInstance()
    {
404 405 406
        CV_TRACE_FUNCTION();
        CV_TRACE_ARG_VALUE(type, "type", type.c_str());

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        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
{
423 424 425 426 427 428 429 430 431 432
    DataLayer() : Layer()
    {
        skip = false;
    }

    virtual bool supportBackend(int backendId) CV_OVERRIDE
    {
        return backendId == DNN_BACKEND_OPENCV ||
               backendId == DNN_BACKEND_INFERENCE_ENGINE && inputsData.size() == 1;
    }
433

434
    void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
435 436 437 438 439
    {
        CV_TRACE_FUNCTION();
        CV_TRACE_ARG_VALUE(name, "name", name.c_str());

        CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
440
                   forward_ocl(inputs_arr, outputs_arr, internals_arr))
441

442 443 444 445 446 447 448 449 450
        if (outputs_arr.depth() == CV_16S)
        {
            forward_fallback(inputs_arr, outputs_arr, internals_arr);
            return;
        }

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

452 453 454 455
        // Supported modes:
        // | Input type | Output type |
        // |       fp32 |        fp32 |
        // |      uint8 |        fp32 |
456 457
        for (int i = 0; i < inputsData.size(); ++i)
        {
458 459
            double scale = scaleFactors[i];
            Scalar& mean = means[i];
460 461
            CV_Assert(mean == Scalar() || inputsData[i].size[1] <= 4);
            CV_CheckTypeEQ(outputs[i].type(), CV_32FC1, "");
462 463 464 465 466 467 468 469 470 471 472 473

            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)
            {
                inputsData[i].convertTo(outputs[i], CV_32F, scale, -mean[0] * scale);
            }
            else
474
            {
475 476 477 478 479 480 481
                for (int n = 0; n < inputsData[i].size[0]; ++n)
                    for (int c = 0; c < inputsData[i].size[1]; ++c)
                    {
                        Mat inp = getPlane(inputsData[i], n, c);
                        Mat out = getPlane(outputs[i], n, c);
                        inp.convertTo(out, CV_32F, scale, -mean[c] * scale);
                    }
482 483 484 485 486
            }
        }
    }

#ifdef HAVE_OPENCL
487
    std::vector<Mat> tmp_expressions;
488 489
    bool forward_ocl(InputArrayOfArrays, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
    {
490 491 492 493 494 495 496 497
        // Supported modes:
        // | Input type | Output type |
        // |       fp32 |        fp32 |
        // |       fp32 |        fp16 |
        // |      uint8 |        fp32 |
        std::vector<UMat> outputs;
        outputs_.getUMatVector(outputs);

498
        tmp_expressions.clear();
499
        for (int i = 0; i < inputsData.size(); ++i)
500
        {
501 502
            Mat inputData = inputsData[i];

503 504 505 506 507 508
            double scale = scaleFactors[i];
            Scalar& mean = means[i];

            CV_Assert(mean == Scalar() || inputsData[i].size[1] <= 4);
            bool singleMean = true;
            for (int j = 1; j < std::min(4, inputsData[i].size[1]) && singleMean; ++j)
509
            {
510 511 512 513 514 515
                singleMean = mean[j] == mean[j - 1];
            }

            if (outputs_.depth() == CV_16S)
            {
                if (singleMean)
516 517 518 519
                {
                    tmp_expressions.push_back(Mat(scale * (inputsData[i] - mean[0])));
                    convertFp16(tmp_expressions.back(), outputs[i]);
                }
520 521 522 523 524 525 526 527 528 529 530 531
                else
                {
                    for (int n = 0; n < inputsData[i].size[0]; ++n)
                        for (int c = 0; c < inputsData[i].size[1]; ++c)
                        {
                            Mat inp = getPlane(inputsData[i], n, c);

                            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);

532 533
                            tmp_expressions.push_back(scale * (inp - mean[c]));
                            convertFp16(tmp_expressions.back(), out);
534 535 536 537 538 539 540
                        }
                }
            }
            else
            {
                CV_Assert(outputs_.depth() == CV_32F);
                if (singleMean)
541
                {
542
                    inputsData[i].convertTo(outputs[i], CV_32F, scale, -mean[0] * scale);
543
                }
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
                else
                {
                    for (int n = 0; n < inputsData[i].size[0]; ++n)
                        for (int c = 0; c < inputsData[i].size[1]; ++c)
                        {
                            Mat inp = getPlane(inputsData[i], n, c);

                            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);

                            inp.convertTo(out, CV_32F, scale, -mean[c] * scale);
                        }
                }
559 560 561 562 563
            }
        }
        return true;
    }
#endif
564

565
    int outputNameToIndex(const String& tgtName) CV_OVERRIDE
566 567 568 569 570 571 572 573 574 575
    {
        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());
    }

576 577 578
    bool getMemoryShapes(const std::vector<MatShape> &inputs,
                         const int requiredOutputs,
                         std::vector<MatShape> &outputs,
579
                         std::vector<MatShape> &internals) const CV_OVERRIDE
580 581 582 583 584 585
    {
        CV_Assert(inputs.size() == requiredOutputs);
        outputs.assign(inputs.begin(), inputs.end());
        return false;
    }

586
    virtual void finalize(InputArrayOfArrays, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
587
    {
588 589 590
        std::vector<Mat> outputs;
        outputs_arr.getMatVector(outputs);

591
        CV_Assert_N(outputs.size() == scaleFactors.size(), outputs.size() == means.size(),
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
                  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;
        }
    }

    virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >&) CV_OVERRIDE
    {
#ifdef HAVE_INF_ENGINE
        InferenceEngine::LayerParams lp;
        lp.name = name;
        lp.type = "ScaleShift";
        lp.precision = InferenceEngine::Precision::FP32;
        std::shared_ptr<InferenceEngine::ScaleShiftLayer> ieLayer(new InferenceEngine::ScaleShiftLayer(lp));

610 611
        CV_CheckEQ(inputsData.size(), (size_t)1, "");
        CV_CheckEQ(inputsData[0].dims, 4, "");
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
        const size_t numChannels = inputsData[0].size[1];
        CV_Assert(numChannels <= 4);

        // Scale
        auto weights = InferenceEngine::make_shared_blob<float>(InferenceEngine::Precision::FP32,
                                                                {numChannels});
        weights->allocate();
        weights->set(std::vector<float>(numChannels, scaleFactors[0]));
        ieLayer->_weights = weights;

        // Mean subtraction
        auto biases = InferenceEngine::make_shared_blob<float>(InferenceEngine::Precision::FP32,
                                                               {numChannels});
        biases->allocate();
        std::vector<float> biasesVec(numChannels);
        for (int i = 0; i < numChannels; ++i)
        {
            biasesVec[i] = -means[0][i] * scaleFactors[0];
        }
        biases->set(biasesVec);
        ieLayer->_biases = biases;

        return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
#endif  // HAVE_INF_ENGINE
        return Ptr<BackendNode>();
    }

639
    std::vector<String> outNames;
640 641 642
    // Preprocessing parameters for each network's input.
    std::vector<double> scaleFactors;
    std::vector<Scalar> means;
643
    std::vector<Mat> inputsData;
644
    bool skip;
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
};

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]);
        }
    }

721
    void reuseOrCreate(const MatShape& shape, const LayerPin& lp, Mat& dst, bool use_half)
722
    {
723
        if (!DNN_DISABLE_MEMORY_OPTIMIZATIONS)
724 725 726
        {
            Mat bestBlob;
            LayerPin bestBlobPin;
727

728 729
            std::map<LayerPin, Mat>::iterator hostIt;
            std::map<LayerPin, int>::iterator refIt;
730

731 732
            const int targetTotal = total(shape);
            int bestBlobTotal = INT_MAX;
733

734
            for (hostIt = memHosts.begin(); hostIt != memHosts.end(); ++hostIt)
735
            {
736 737 738 739
                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)
740
                {
741 742 743 744 745 746 747 748
                    Mat& unusedBlob = hostIt->second;
                    if (unusedBlob.total() >= targetTotal &&
                        unusedBlob.total() < bestBlobTotal)
                    {
                        bestBlobPin = hostIt->first;
                        bestBlob = unusedBlob;
                        bestBlobTotal = unusedBlob.total();
                    }
749 750
                }
            }
751 752 753 754 755 756
            if (!bestBlob.empty())
            {
                reuse(bestBlobPin, lp);
                dst = bestBlob.reshape(1, 1).colRange(0, targetTotal).reshape(1, shape);
                return;
            }
757
        }
758

759 760
        {
            // if dst already has been allocated with total(shape) elements,
Kuang Fangjun's avatar
Kuang Fangjun committed
761
            // it won't be recreated and pointer of dst.data remains the same.
Li Peng's avatar
Li Peng committed
762
            dst.create(shape, use_half ? CV_16S : CV_32F);
763 764 765 766 767
            addHost(lp, dst);
        }
    }

    void allocateBlobsForLayer(LayerData &ld, const LayerShapes& layerShapes,
768
                               std::vector<LayerPin>& pinsForInternalBlobs,
769
                               bool use_half = false)
770
    {
771 772
        CV_TRACE_FUNCTION();

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
        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);
833
                    if (index < outShapes.size() && inPlace)
834
                    {
835 836
                        CV_Assert(ld.inputBlobs[0]->total() == total(shapes[index]));
                        ld.outputBlobs[index] = ld.inputBlobs[0]->reshape(1, shapes[index]);
837 838 839
                        reuse(ld.inputBlobsId[0], blobPin);
                    }
                    else
840
                        reuseOrCreate(shapes[index], blobPin, *blobs[index], use_half);
841 842 843 844 845 846 847 848
                }
            }
        }
    }

    // Clear internal state. Calls before an every reallocation.
    void reset()
    {
849 850
        CV_TRACE_FUNCTION();

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
        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;
};

872
static Ptr<BackendWrapper> wrapMat(int backendId, int targetId, cv::Mat& m)
873
{
874
    if (backendId == DNN_BACKEND_OPENCV)
875
    {
876 877
        if (targetId == DNN_TARGET_CPU)
            return Ptr<BackendWrapper>();
Li Peng's avatar
Li Peng committed
878
        else if (IS_DNN_OPENCL_TARGET(targetId))
879 880 881
            return OpenCLBackendWrapper::create(m);
        else
            CV_Error(Error::StsNotImplemented, "Unknown target identifier");
882 883 884 885 886 887 888
    }
    else if (backendId == DNN_BACKEND_HALIDE)
    {
        CV_Assert(haveHalide());
#ifdef HAVE_HALIDE
        return Ptr<BackendWrapper>(new HalideBackendWrapper(targetId, m));
#endif  // HAVE_HALIDE
889 890 891 892 893 894 895
    }
    else if (backendId == DNN_BACKEND_INFERENCE_ENGINE)
    {
        CV_Assert(haveInfEngine());
#ifdef HAVE_INF_ENGINE
        return Ptr<BackendWrapper>(new InfEngineBackendWrapper(targetId, m));
#endif  // HAVE_INF_ENGINE
896 897 898 899 900 901 902
    }
    else if (backendId == DNN_BACKEND_VKCOM)
    {
        CV_Assert(haveVulkan());
#ifdef HAVE_VULKAN
        return Ptr<BackendWrapper>(new VkComBackendWrapper(m));
#endif  // HAVE_VULKAN
903 904 905 906 907 908
    }
    else
        CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
    return Ptr<BackendWrapper>();
}

909 910 911 912 913
struct Net::Impl
{
    typedef std::map<int, LayerShapes> LayersShapesMap;
    typedef std::map<int, LayerData> MapIdToLayerData;

914 915 916 917 918 919 920 921 922 923
    ~Impl()
    {
#ifdef HAVE_VULKAN
        // Vulkan requires explicit releasing the child objects of
        // VkDevice object prior to releasing VkDevice object itself.
        layers.clear();
        backendWrappers.clear();
        vkcom::deinitPerThread();
#endif
    }
924 925
    Impl()
    {
926 927 928
#ifdef HAVE_VULKAN
        vkcom::initPerThread();
#endif
929 930 931 932
        //allocate fake net input layer
        netInputLayer = Ptr<DataLayer>(new DataLayer());
        LayerData &inpl = layers.insert( make_pair(0, LayerData()) ).first->second;
        inpl.id = 0;
933
        netInputLayer->name = inpl.name = "_input";
934 935 936 937
        inpl.type = "__NetInputLayer__";
        inpl.layerInstance = netInputLayer;
        layerNameToId.insert(std::make_pair(inpl.name, inpl.id));

938
        lastLayerId = 0;
939
        netWasAllocated = false;
940
        fusion = true;
941 942
        preferableBackend = DNN_BACKEND_DEFAULT;
        preferableTarget = DNN_TARGET_CPU;
943
        skipInfEngineInit = false;
944 945 946 947 948 949 950 951 952 953
    }

    Ptr<DataLayer> netInputLayer;
    std::vector<LayerPin> blobsToKeep;
    MapIdToLayerData layers;
    std::map<String, int> layerNameToId;
    BlobManager blobManager;
    int preferableBackend;
    int preferableTarget;
    String halideConfigFile;
954
    bool skipInfEngineInit;
955 956
    // Map host data to backend specific wrapper.
    std::map<void*, Ptr<BackendWrapper> > backendWrappers;
957 958 959 960

    int lastLayerId;

    bool netWasAllocated;
961
    bool fusion;
962
    std::vector<int64> layersTimings;
Li Peng's avatar
Li Peng committed
963
    Mat output_blob;
964

965
    Ptr<BackendWrapper> wrap(Mat& host)
966
    {
967
        if (preferableBackend == DNN_BACKEND_OPENCV && preferableTarget == DNN_TARGET_CPU)
968 969 970 971 972 973 974 975 976 977
            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];
978
            if (preferableBackend == DNN_BACKEND_OPENCV)
979
            {
Li Peng's avatar
Li Peng committed
980
                CV_Assert(IS_DNN_OPENCL_TARGET(preferableTarget));
981 982 983
                return OpenCLBackendWrapper::create(baseBuffer, host);
            }
            else if (preferableBackend == DNN_BACKEND_HALIDE)
984 985 986 987 988 989
            {
                CV_Assert(haveHalide());
  #ifdef HAVE_HALIDE
                return Ptr<BackendWrapper>(new HalideBackendWrapper(baseBuffer, shape));
  #endif  // HAVE_HALIDE
            }
990 991 992 993
            else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE)
            {
                return wrapMat(preferableBackend, preferableTarget, host);
            }
994 995 996 997 998 999
            else if (preferableBackend == DNN_BACKEND_VKCOM)
            {
  #ifdef HAVE_VULKAN
                return Ptr<BackendWrapper>(new VkComBackendWrapper(baseBuffer, host));
  #endif
            }
1000 1001 1002 1003 1004 1005 1006 1007 1008
            else
                CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
        }

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

1009
#ifdef HAVE_HALIDE
1010 1011
    void compileHalide()
    {
1012 1013
        CV_TRACE_FUNCTION();

1014 1015 1016
        CV_Assert(preferableBackend == DNN_BACKEND_HALIDE);

        HalideScheduler scheduler(halideConfigFile);
1017 1018
        std::vector< std::reference_wrapper<LayerData> > compileList; compileList.reserve(64);
        for (MapIdToLayerData::iterator it = layers.begin(); it != layers.end(); ++it)
1019 1020 1021
        {
            LayerData &ld = it->second;
            Ptr<Layer> layer = ld.layerInstance;
1022
            if (layer->supportBackend(DNN_BACKEND_HALIDE) && !ld.skip)
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
            {
                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);
                }
1033
                compileList.emplace_back(ld);
1034 1035
            }
        }
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
        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();
1055
    }
1056
#endif
1057 1058 1059

    void clear()
    {
1060 1061
        CV_TRACE_FUNCTION();

1062 1063 1064 1065
        MapIdToLayerData::iterator it;
        for (it = layers.begin(); it != layers.end(); it++)
        {
            if (it->second.id != 0) {
1066
                it->second.inputBlobs.clear();
1067 1068 1069
                it->second.outputBlobs.clear();
                it->second.internals.clear();
            }
1070
            it->second.skip = false;
1071 1072
            //it->second.consumers.clear();
            Ptr<Layer> currLayer = it->second.layerInstance;
1073

1074 1075 1076
            if( currLayer.empty() )
                continue;

1077
            currLayer->unsetAttached();
1078

1079
            Ptr<PoolingLayer> poolingLayer = currLayer.dynamicCast<PoolingLayer>();
1080 1081 1082 1083 1084
            if( !poolingLayer.empty() )
            {
                poolingLayer->computeMaxIdx = true;
            }
        }
1085 1086

        layersTimings.clear();
1087 1088 1089 1090
    }

    void setUpNet(const std::vector<LayerPin>& blobsToKeep_ = std::vector<LayerPin>())
    {
1091 1092
        CV_TRACE_FUNCTION();

1093
        if (preferableBackend == DNN_BACKEND_DEFAULT)
1094 1095
            preferableBackend = (Backend)PARAM_DNN_BACKEND_DEFAULT;

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
        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);
        CV_Assert(preferableBackend != DNN_BACKEND_INFERENCE_ENGINE ||
                  preferableTarget == DNN_TARGET_CPU ||
                  preferableTarget == DNN_TARGET_OPENCL ||
                  preferableTarget == DNN_TARGET_OPENCL_FP16 ||
                  preferableTarget == DNN_TARGET_MYRIAD);
1108 1109
        CV_Assert(preferableBackend != DNN_BACKEND_VKCOM ||
                  preferableTarget == DNN_TARGET_VULKAN);
1110 1111
        if (!netWasAllocated || this->blobsToKeep != blobsToKeep_)
        {
1112
            if (preferableBackend == DNN_BACKEND_OPENCV && IS_DNN_OPENCL_TARGET(preferableTarget))
1113
#ifndef HAVE_OPENCL
1114
            {
1115
                CV_LOG_WARNING(NULL, "DNN: OpenCL target is not available in this OpenCV build, switching to CPU.");
1116 1117
                preferableTarget = DNN_TARGET_CPU;
            }
1118 1119
#else
            {
1120
                if (!DNN_OPENCL_ALLOW_ALL_DEVICES)
1121
                {
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
                    // 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;
                    }
1136 1137
                }
            }
1138
#endif
1139 1140 1141 1142 1143 1144
            if (preferableBackend == DNN_BACKEND_VKCOM && !haveVulkan())
            {
                preferableBackend = DNN_BACKEND_OPENCV;
                preferableTarget = DNN_TARGET_CPU;
            }

1145 1146 1147
            clear();

            allocateLayers(blobsToKeep_);
1148 1149 1150 1151 1152

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

1153 1154 1155 1156
            initBackend();

            if (!netWasAllocated )
            {
1157
#ifdef HAVE_HALIDE
1158 1159
                if (preferableBackend == DNN_BACKEND_HALIDE)
                    compileHalide();
1160 1161 1162
#else
                CV_Assert(preferableBackend != DNN_BACKEND_HALIDE);
#endif
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
            }

            netWasAllocated = true;
            this->blobsToKeep = blobsToKeep_;
        }
    }

    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)
luz.paz's avatar
luz.paz committed
1214
            CV_Error(Error::StsError, "Requested layer \"" + layerName + "\" not found");
1215 1216 1217 1218 1219 1220

        return getLayerData(id);
    }

    LayerData& getLayerData(const DictValue &layerDesc)
    {
1221
        CV_Assert(layerDesc.isInt() || layerDesc.isString());
1222 1223
        if (layerDesc.isInt())
            return getLayerData(layerDesc.get<int>());
1224
        else /*if (layerDesc.isString())*/
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
            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))
1238 1239
                CV_Error(Error::StsError, format("Input #%d of layer \"%s\" already was connected",
                                                 inNum, ld.name.c_str()));
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
        }

        ld.inputBlobsId[inNum] = from;
    }

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

1252
    LayerPin getPinByAlias(const String &layerName)
1253 1254 1255 1256 1257
    {
        LayerPin pin;
        pin.lid = (layerName.empty()) ? 0 : getLayerId(layerName);

        if (pin.lid >= 0)
1258
            pin.oid = resolvePinOutputName(getLayerData(pin.lid), layerName);
1259 1260 1261 1262

        return pin;
    }

1263
    std::vector<LayerPin> getLayerOutPins(const String &layerName)
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
    {
        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));
    }

    void initBackend()
    {
1290
        CV_TRACE_FUNCTION();
1291
        if (preferableBackend == DNN_BACKEND_OPENCV)
Li Peng's avatar
Li Peng committed
1292
            CV_Assert(preferableTarget == DNN_TARGET_CPU || IS_DNN_OPENCL_TARGET(preferableTarget));
1293 1294 1295 1296
        else if (preferableBackend == DNN_BACKEND_HALIDE)
            initHalideBackend();
        else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE)
            initInfEngineBackend();
1297 1298
        else if (preferableBackend == DNN_BACKEND_VKCOM)
            initVkComBackend();
1299 1300 1301 1302 1303 1304 1305
        else
            CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
    }

    void initHalideBackend()
    {
        CV_TRACE_FUNCTION();
1306
        CV_Assert_N(preferableBackend == DNN_BACKEND_HALIDE, haveHalide());
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342

        // 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())
                    {
1343
                        ldTop.skip = true;
1344
                        ldBot.backendNodes[preferableBackend] = fusedNode;
1345
                        ldBot.outputBlobsWrappers = ldTop.outputBlobsWrappers;
1346 1347 1348 1349 1350
                        continue;
                    }
                }
            }
            // No layers fusion.
1351
            ldTop.skip = false;
1352 1353 1354 1355 1356 1357
            ldTop.backendNodes[DNN_BACKEND_HALIDE] =
                layerTop->initHalide(ldTop.inputBlobsWrappers);
            baseIt = it;
        }
    }

1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
#ifdef HAVE_INF_ENGINE
    // 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)
    {
        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>();
1371
                CV_Assert(!ieNode.empty()); CV_Assert(!ieNode->net.empty());
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
                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>();
1385
                CV_Assert(!ieInpNode.empty()); CV_Assert(!ieInpNode->net.empty());
1386 1387 1388
                if (layerNet != ieInpNode->net)
                {
                    // layerNet is empty or nodes are from different graphs.
1389
                    ieInpNode->net->addOutput(ieInpNode->layer->name);
1390 1391 1392 1393 1394 1395
                }
            }
        }
    }
#endif  // HAVE_INF_ENGINE

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
    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;
            }

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
            if (ld.type == "Convolution")
            {
                std::vector<MatShape> in_shapes;
                std::vector<MatShape> out_shapes;
                CV_Assert(ld.inputBlobs.size() == ld.outputBlobs.size());

                for (int i = 0; i < ld.inputBlobs.size(); i++)
                {
                    in_shapes.push_back(shape(*ld.inputBlobs[i]));
                    out_shapes.push_back(shape(ld.outputBlobs[i]));
                }
                int64 flops = layer->getFLOPS(in_shapes, out_shapes);
                // FIXME
                //
                // This is a workaround for GPU hang on heavy convolution workload ( > 10 GFLOPS).
                // For the long time task, vkWaitForFences() return without error but next call on
                // vkQueueSubmit() return -4, i.e. "VK_ERROR_DEVICE_LOST" and driver reports GPU hang.
                //
                // Need more investigation on root cause of GPU hang and need to optimize convolution shader
                // to reduce process time.
                if (flops > CV_BIG_INT(10) * 1000 * 1000 * 1000)
                {
                    continue;
                }
            }

1440
            ld.skip = false;
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451

            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>();
            }
1452 1453 1454 1455
        }
#endif
    }

1456 1457 1458
    void initInfEngineBackend()
    {
        CV_TRACE_FUNCTION();
1459
        CV_Assert_N(preferableBackend == DNN_BACKEND_INFERENCE_ENGINE, haveInfEngine());
1460 1461 1462
#ifdef HAVE_INF_ENGINE
        MapIdToLayerData::iterator it;
        Ptr<InfEngineBackendNet> net;
1463

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
        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]);
                    dataPtr->name = netInputLayer->outNames.empty() ? ld.name : netInputLayer->outNames[i];
                }
            }
            else
            {
                for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                {
                    InferenceEngine::DataPtr dataPtr = infEngineDataNode(ld.outputBlobsWrappers[i]);
                    dataPtr->name = ld.name;
                }
            }
        }

1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
        if (skipInfEngineInit)
        {
            Ptr<BackendNode> node = layers[lastLayerId].backendNodes[preferableBackend];
            CV_Assert(!node.empty());

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

            for (it = layers.begin(); it != layers.end(); ++it)
            {
                LayerData &ld = it->second;
1498
                if (ld.id == 0)
1499
                {
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
                    for (int i = 0; i < ld.inputBlobsWrappers.size(); ++i)
                    {
                        InferenceEngine::DataPtr dataPtr = infEngineDataNode(ld.inputBlobsWrappers[i]);
                        dataPtr->name = netInputLayer->outNames[i];
                    }
                }
                else
                {
                    for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
                    {
                        InferenceEngine::DataPtr dataPtr = infEngineDataNode(ld.outputBlobsWrappers[i]);
                        dataPtr->name = ld.name;
                    }
1513 1514 1515 1516 1517 1518
                }
                ieNode->net->addBlobs(ld.inputBlobsWrappers);
                ieNode->net->addBlobs(ld.outputBlobsWrappers);
                ld.skip = true;
            }
            layers[lastLayerId].skip = false;
1519
            ieNode->net->init(preferableTarget);
1520 1521 1522 1523 1524 1525 1526
            return;
        }

        // 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 is not implemented.

1527
        // Set of all input and output blobs wrappers for current network.
1528
        std::map<LayerPin, Ptr<BackendWrapper> > netBlobsWrappers;
1529 1530 1531
        for (it = layers.begin(); it != layers.end(); ++it)
        {
            LayerData &ld = it->second;
1532
            if (ld.id == 0 && ld.skip)
1533 1534
                continue;
            bool fused = ld.skip;
1535

1536
            Ptr<Layer> layer = ld.layerInstance;
1537
            if (!fused && !layer->supportBackend(preferableBackend))
1538
            {
1539
                addInfEngineNetOutputs(ld);
1540
                net = Ptr<InfEngineBackendNet>();
1541
                netBlobsWrappers.clear();
1542
                layer->preferableTarget = DNN_TARGET_CPU;
1543 1544
                continue;
            }
1545
            ld.skip = true;  // Initially skip all Inference Engine supported layers.
1546

1547
            // Create a new network if one of inputs from different Inference Engine graph.
1548 1549 1550 1551 1552 1553 1554
            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>();
1555
                    CV_Assert(!ieInpNode.empty()); CV_Assert(!ieInpNode->net.empty());
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
                    if (ieInpNode->net != net)
                    {
                        net = Ptr<InfEngineBackendNet>();
                        netBlobsWrappers.clear();
                        break;
                    }
                }
            }

            // The same blobs wrappers cannot be shared between two Inference Engine
            // networks because of explicit references between layers and blobs.
            // So we need to rewrap all the external blobs.
            for (int i = 0; i < ld.inputBlobsId.size(); ++i)
            {
1570 1571
                LayerPin inPin = ld.inputBlobsId[i];
                auto it = netBlobsWrappers.find(inPin);
1572 1573
                if (it == netBlobsWrappers.end())
                {
1574 1575
                    ld.inputBlobsWrappers[i] = InfEngineBackendWrapper::create(ld.inputBlobsWrappers[i]);
                    netBlobsWrappers[inPin] = ld.inputBlobsWrappers[i];
1576
                }
1577 1578
                else
                    ld.inputBlobsWrappers[i] = it->second;
1579
            }
1580
            netBlobsWrappers[LayerPin(ld.id, 0)] = ld.outputBlobsWrappers[0];
1581 1582 1583 1584

            Ptr<BackendNode> node;
            if (!net.empty())
            {
1585
                if (fused)
1586
                {
1587 1588 1589 1590 1591
                    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;
1592
                }
1593 1594
            }
            else
1595 1596 1597
                net = Ptr<InfEngineBackendNet>(new InfEngineBackendNet());

            if (!fused)
1598
            {
1599
                node = layer->initInfEngine(ld.inputBlobsWrappers);
1600
            }
1601 1602
            else if (node.empty())
                continue;
1603 1604 1605 1606 1607 1608 1609 1610

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

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

1611
            auto weightableLayer = std::dynamic_pointer_cast<InferenceEngine::WeightableLayer>(ieNode->layer);
1612
            if ((preferableTarget == DNN_TARGET_OPENCL_FP16 || preferableTarget == DNN_TARGET_MYRIAD) && !fused)
1613 1614 1615 1616 1617 1618 1619 1620 1621
            {
                ieNode->layer->precision = InferenceEngine::Precision::FP16;
                if (weightableLayer)
                {
                    if (weightableLayer->_weights)
                        weightableLayer->_weights = convertFp16(weightableLayer->_weights);
                    if (weightableLayer->_biases)
                        weightableLayer->_biases = convertFp16(weightableLayer->_biases);
                }
1622 1623 1624 1625 1626 1627 1628 1629 1630
                else
                {
                    for (const auto& weights : {"weights", "biases"})
                    {
                        auto it = ieNode->layer->blobs.find(weights);
                        if (it != ieNode->layer->blobs.end())
                            it->second = convertFp16(it->second);
                    }
                }
1631
            }
1632 1633 1634 1635 1636 1637 1638
            if (weightableLayer)
            {
                if (weightableLayer->_weights)
                    weightableLayer->blobs["weights"] = weightableLayer->_weights;
                if (weightableLayer->_biases)
                    weightableLayer->blobs["biases"] = weightableLayer->_biases;
            }
1639 1640 1641 1642 1643 1644
            ieNode->connect(ld.inputBlobsWrappers, ld.outputBlobsWrappers);
            net->addBlobs(ld.inputBlobsWrappers);
            net->addBlobs(ld.outputBlobsWrappers);

            if (!fused)
                net->addLayer(ieNode->layer);
1645
            addInfEngineNetOutputs(ld);
1646
        }
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667

        // Initialize all networks.
        std::set<InfEngineBackendNet> initializedNets;
        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())
            {
1668
                ieNode->net->init(preferableTarget);
1669 1670 1671 1672
                ld.skip = false;
            }
        }
#endif  // HAVE_INF_ENGINE
1673 1674 1675 1676
    }

    void allocateLayer(int lid, const LayersShapesMap& layersShapes)
    {
1677 1678
        CV_TRACE_FUNCTION();

1679 1680 1681 1682 1683 1684 1685 1686 1687 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
        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
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
        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
1723
        {
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
            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];
            }
1734 1735 1736 1737 1738 1739 1740
        }

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

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

        std::vector<LayerPin> pinsForInternalBlobs;
1741
        blobManager.allocateBlobsForLayer(ld, layerShapesIt->second, pinsForInternalBlobs,
1742
                                          preferableBackend == DNN_BACKEND_OPENCV &&
Li Peng's avatar
Li Peng committed
1743
                                          preferableTarget == DNN_TARGET_OPENCL_FP16);
1744 1745 1746 1747 1748
        ld.outputBlobsWrappers.resize(ld.outputBlobs.size());
        for (int i = 0; i < ld.outputBlobs.size(); ++i)
        {
            ld.outputBlobsWrappers[i] = wrap(ld.outputBlobs[i]);
        }
1749 1750 1751 1752 1753
        ld.internalBlobsWrappers.resize(ld.internals.size());
        for (int i = 0; i < ld.internals.size(); ++i)
        {
            ld.internalBlobsWrappers[i] = wrap(ld.internals[i]);
        }
1754 1755 1756

        Ptr<Layer> layerPtr = ld.getLayerInstance();
        {
1757 1758 1759 1760 1761 1762
            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);
1763
            layerPtr->preferableTarget = preferableTarget;
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
#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;
    }

1782 1783 1784 1785 1786 1787
#if 0
#define printf_(args) printf args
#else
#define printf_(args)
#endif

1788 1789
    void fuseLayers(const std::vector<LayerPin>& blobsToKeep_)
    {
1790
        if( !fusion || preferableBackend != DNN_BACKEND_OPENCV &&
1791
                       preferableBackend != DNN_BACKEND_INFERENCE_ENGINE)
1792 1793
            return;

1794 1795
        CV_TRACE_FUNCTION();

1796 1797 1798 1799 1800 1801 1802 1803 1804
        // 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];
1805
            if( ld.skip )
1806
            {
1807
                printf_(("skipped %s: %s\n", ld.layerInstance->name.c_str(), ld.layerInstance->type.c_str()));
1808 1809
                continue;
            }
1810
            printf_(("analyzing %s: %s\n", ld.layerInstance->name.c_str(), ld.layerInstance->type.c_str()));
1811

1812 1813 1814 1815
            // 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.
1816 1817
            Ptr<Layer>& currLayer = ld.layerInstance;
            if( ld.consumers.size() == 1 && pinsToKeep.count(LayerPin(lid, 0)) == 0 )
1818 1819 1820
            {
                LayerData* nextData = &layers[ld.consumers[0].lid];
                LayerPin lpNext(ld.consumers[0].lid, 0);
1821
                while (nextData)
1822
                {
1823 1824
                    Ptr<Layer> nextLayer = nextData->layerInstance;
                    if (currLayer->tryFuse(nextLayer))
1825
                    {
1826 1827
                        printf_(("\tfused with %s\n", nextLayer->name.c_str()));
                        nextData->skip = true;
1828 1829
                        ld.outputBlobs = layers[lpNext.lid].outputBlobs;
                        ld.outputBlobsWrappers = layers[lpNext.lid].outputBlobsWrappers;
1830
                        if (nextData->consumers.size() == 1)
1831
                        {
1832 1833 1834
                            int nextLayerId = nextData->consumers[0].lid;
                            nextData = &layers[nextLayerId];
                            lpNext = LayerPin(nextLayerId, 0);
1835
                        }
1836
                        else
1837
                        {
1838 1839
                            nextData = 0;
                            break;
1840
                        }
1841
                    }
1842 1843
                    else
                        break;
1844 1845
                }

1846
                if (preferableBackend != DNN_BACKEND_OPENCV)
1847 1848
                    continue;  // Go to the next layer.

1849 1850 1851 1852 1853 1854 1855
                // 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;

1856
                while (nextData)
1857
                {
1858 1859 1860 1861 1862 1863 1864 1865
                    // 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;
1866

1867 1868 1869
                    Ptr<ActivationLayer> nextActivLayer = nextData->layerInstance.dynamicCast<ActivationLayer>();
                    if (nextActivLayer.empty())
                        break;
1870

1871
                    if (currLayer->setActivation(nextActivLayer))
1872 1873
                    {
                        printf_(("\tfused with %s\n", nextActivLayer->name.c_str()));
1874
                        nextData->skip = true;
1875 1876
                        ld.outputBlobs = layers[lpNext.lid].outputBlobs;
                        ld.outputBlobsWrappers = layers[lpNext.lid].outputBlobsWrappers;
1877
                        if (nextData->consumers.size() == 1)
1878
                        {
1879 1880 1881 1882 1883
                            int nextLayerId = nextData->consumers[0].lid;
                            nextData = &layers[nextLayerId];
                            lpNext = LayerPin(nextLayerId, 0);
                        }
                        else
1884
                        {
1885 1886
                            nextData = 0;
                            break;
1887 1888
                        }
                    }
1889 1890
                    else
                        break;
1891 1892
                }

Kuang Fangjun's avatar
Kuang Fangjun committed
1893
                // fuse convolution layer followed by eltwise + relu
Li Peng's avatar
Li Peng committed
1894
                if ( IS_DNN_OPENCL_TARGET(preferableTarget) )
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
                {
                    Ptr<EltwiseLayer> nextEltwiseLayer;
                    if( nextData )
                        nextEltwiseLayer = nextData->layerInstance.dynamicCast<EltwiseLayer>();

                    if( !nextEltwiseLayer.empty() && pinsToKeep.count(lpNext) == 0 )
                    {
                        LayerData *eltwiseData = nextData;
                        // go down from the second input and find the first non-skipped layer.
                        LayerData *downLayerData = &layers[eltwiseData->inputBlobsId[1].lid];
1905
                        CV_Assert(downLayerData);
1906
                        while (downLayerData->skip)
1907 1908 1909
                        {
                            downLayerData = &layers[downLayerData->inputBlobsId[0].lid];
                        }
1910
                        CV_Assert(downLayerData);
1911 1912 1913 1914 1915 1916

                        // second input layer is current layer.
                        if ( ld.id == downLayerData->id )
                        {
                            // go down from the first input and find the first non-skipped layer
                            downLayerData = &layers[eltwiseData->inputBlobsId[0].lid];
1917
                            while (downLayerData->skip)
1918 1919 1920 1921 1922 1923 1924
                            {
                                if ( !downLayerData->type.compare("Eltwise") )
                                    downLayerData = &layers[downLayerData->inputBlobsId[1].lid];
                                else
                                    downLayerData = &layers[downLayerData->inputBlobsId[0].lid];
                            }

1925
                            Ptr<ConvolutionLayer> convLayer = downLayerData->layerInstance.dynamicCast<ConvolutionLayer>();
1926 1927

                            //  first input layer is convolution layer
1928
                            if( !convLayer.empty() && eltwiseData->consumers.size() == 1 )
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
                            {
                                // fuse eltwise + activation layer
                                LayerData *firstConvLayerData = downLayerData;
                                {
                                    nextData = &layers[eltwiseData->consumers[0].lid];
                                    lpNext = LayerPin(eltwiseData->consumers[0].lid, 0);
                                    Ptr<ActivationLayer> nextActivLayer;
                                    if( nextData )
                                        nextActivLayer = nextData->layerInstance.dynamicCast<ActivationLayer>();

                                    if( !nextActivLayer.empty() && pinsToKeep.count(lpNext) == 0 &&
                                            (!nextData->type.compare("ReLU") ||
                                             !nextData->type.compare("ChannelsPReLU") ||
                                             !nextData->type.compare("Power")) &&
                                            currLayer->setActivation(nextActivLayer) )
                                    {
1945 1946
                                        CV_Assert(firstConvLayerData->outputBlobsWrappers.size() == 1 && ld.inputBlobsWrappers.size() == 1);
                                        ld.inputBlobsWrappers.push_back(firstConvLayerData->outputBlobsWrappers[0]);
1947 1948
                                        printf_(("\tfused with %s\n", nextEltwiseLayer->name.c_str()));
                                        printf_(("\tfused with %s\n", nextActivLayer->name.c_str()));
1949 1950
                                        eltwiseData->skip = true;
                                        nextData->skip = true;
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
                                        // 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.
1966
                                        CV_Assert_N(ld.outputBlobs.size() == 1, ld.outputBlobsWrappers.size() == 1);
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
                                        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;
                                                }
                                            }
                                        }
1989 1990 1991 1992
                                    }
                                }
                            }
                        }
1993
                    }
1994 1995
                }
            }
1996

1997
            if (preferableBackend != DNN_BACKEND_OPENCV)
1998 1999
                continue;  // Go to the next layer.

2000 2001 2002 2003
            // the optimization #2. if there is no layer that takes max pooling layer's computed
            // max indices (and only some semantical segmentation networks might need this;
            // many others only take the maximum values), then we switch the max pooling
            // layer to the faster operating mode.
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
            Ptr<PoolingLayer> poolingLayer = ld.layerInstance.dynamicCast<PoolingLayer>();
            if( !poolingLayer.empty() && !ld.consumers.empty() )
            {
                size_t i = 0, nconsumers = ld.consumers.size();
                for( ; i < nconsumers; i++ )
                    if( ld.consumers[i].oid > 0 )
                        break;
                // if there is no layer that takes the second output pin of the pooling layer
                // on input then we don't need to compute the indices
                if( i >= nconsumers )
2014
                {
2015
                    poolingLayer->computeMaxIdx = false;
2016 2017 2018 2019 2020 2021
                    printf_(("\tsimplified pooling layer %s\n", poolingLayer->name.c_str()));
                }
            }

            // the optimization #3. if there is concat layer that concatenates channels
            // from the inputs together (i.e. axis == 1) then we make the inputs of
Kuang Fangjun's avatar
Kuang Fangjun committed
2022
            // the concat layer to write to the concatenation output buffer
2023 2024 2025
            // (and so we eliminate the concatenation layer, because the channels
            // are concatenated implicitly).
            Ptr<ConcatLayer> concatLayer = ld.layerInstance.dynamicCast<ConcatLayer>();
2026
            if( !concatLayer.empty() && concatLayer->axis == 1 && !concatLayer->padding &&
2027 2028 2029
                ld.outputBlobs.size() == 1 )
            {
                Mat& output = ld.outputBlobs[0];
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
                UMat umat_output;
                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];
                }
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069

                // 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.
                if( output.dims == 4 && output.size[0] == 1 )
                {
                    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];
2070
                        while(inp_i_data->skip &&
2071 2072
                              inp_i_data->inputBlobsId.size() == 1 &&
                              inp_i_data->consumers.size() == 1)
2073 2074 2075 2076 2077 2078 2079 2080
                        {
                            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()));

2081
                        if(inp_i_data->skip || inp_i_data->consumers.size() != 1)
2082 2083 2084 2085 2086 2087
                            break;
                        realinputs[i] = pin;
                    }

                    if( i >= ninputs )
                    {
2088 2089 2090
                        // Allocate new memory to prevent collisions during memory
                        // reusing (see https://github.com/opencv/opencv/pull/10456).
                        output = output.clone();
2091 2092 2093 2094 2095 2096 2097 2098
                        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);
                        }
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
                        Range chrange[] = { Range::all(), Range::all(), Range::all(), Range::all() };
                        int ofs = 0;
                        for( i = 0; i < ninputs; i++ )
                        {
                            LayerPin pin = realinputs[i];
                            LayerData* inp_i_data = &layers[pin.lid];
                            int channels_i = ld.inputBlobs[i]->size[1];
                            chrange[1] = Range(ofs, ofs + channels_i);
                            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);
2113
                            Mat* oldPtr = &curr_output;
2114
                            curr_output = output_slice;
2115 2116 2117 2118 2119 2120
                            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);
                            }
2121 2122
                            // Layers that refer old input Mat will refer to the
                            // new data but the same Mat object.
2123
                            CV_Assert_N(curr_output.data == output_slice.data, oldPtr == &curr_output);
2124
                        }
2125
                        ld.skip = true;
2126 2127
                        printf_(("\toptimized out Concat layer %s\n", concatLayer->name.c_str()));
                    }
2128
                }
2129 2130 2131 2132 2133 2134
            }
        }
    }

    void allocateLayers(const std::vector<LayerPin>& blobsToKeep_)
    {
2135 2136
        CV_TRACE_FUNCTION();

2137 2138 2139 2140 2141 2142 2143 2144
        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++)
        {
2145 2146 2147
            Mat& inp = layers[0].outputBlobs[i];
            CV_Assert(inp.total());
            if (preferableBackend == DNN_BACKEND_OPENCV &&
Li Peng's avatar
Li Peng committed
2148 2149
                preferableTarget == DNN_TARGET_OPENCL_FP16)
            {
2150
                layers[0].outputBlobs[i].create(inp.dims, inp.size, CV_16S);
Li Peng's avatar
Li Peng committed
2151
            }
2152
            inputShapes.push_back(shape(inp));
2153 2154 2155 2156 2157
        }
        LayersShapesMap layersShapes;
        getLayersShapes(inputShapes, layersShapes);

        blobManager.reset();
2158
        backendWrappers.clear();
2159 2160 2161
        // Fake references to input blobs.
        for (int i = 0; i < layers[0].outputBlobs.size(); ++i)
            blobManager.addReference(LayerPin(0, i));
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
        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);
        }

2179
        layersTimings.resize(lastLayerId + 1, 0);
2180 2181 2182 2183 2184
        fuseLayers(blobsToKeep_);
    }

    void forwardLayer(LayerData &ld)
    {
2185 2186
        CV_TRACE_FUNCTION();

2187 2188
        Ptr<Layer> layer = ld.layerInstance;

2189 2190 2191
        TickMeter tm;
        tm.start();

2192
        if( !ld.skip )
2193
        {
2194 2195
            std::map<int, Ptr<BackendNode> >::iterator it = ld.backendNodes.find(preferableBackend);
            if (preferableBackend == DNN_BACKEND_OPENCV || it == ld.backendNodes.end() || it->second.empty())
2196
            {
2197
                if (preferableBackend == DNN_BACKEND_OPENCV && IS_DNN_OPENCL_TARGET(preferableTarget))
2198
                {
2199
                    std::vector<UMat> umat_inputBlobs = OpenCLBackendWrapper::getUMatVector(ld.inputBlobsWrappers);
2200
                    std::vector<UMat> umat_outputBlobs = OpenCLBackendWrapper::getUMatVector(ld.outputBlobsWrappers);
2201 2202
                    std::vector<UMat> umat_internalBlobs = OpenCLBackendWrapper::getUMatVector(ld.internalBlobsWrappers);
                    layer->forward(umat_inputBlobs,
2203
                                   umat_outputBlobs,
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
                                   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);
                        }
                    }
2268
                    OpenCLBackendWrapper::update(ld.outputBlobsWrappers, umat_outputBlobs);
2269
                }
2270
                else
2271
                {
2272 2273 2274 2275 2276 2277
                    for (int i = 0, n = ld.inputBlobsWrappers.size(); i < n; ++i)
                    {
                        if (!ld.inputBlobsWrappers[i].empty())
                            ld.inputBlobsWrappers[i]->copyToHost();
                    }

2278 2279 2280 2281 2282 2283
                    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);
2284

2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
                    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);
                        }
                    }

2335 2336 2337 2338 2339
                    for (int i = 0, n = ld.outputBlobsWrappers.size(); i < n; ++i)
                    {
                        if (!ld.outputBlobsWrappers[i].empty())
                            ld.outputBlobsWrappers[i]->setHostDirty();
                    }
2340 2341
                }
            }
2342
            else
2343
            {
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
                Ptr<BackendNode> node = it->second;
                CV_Assert(!node.empty());
                if (preferableBackend == DNN_BACKEND_HALIDE)
                {
                    forwardHalide(ld.outputBlobsWrappers, node);
                }
                else if (preferableBackend == DNN_BACKEND_INFERENCE_ENGINE)
                {
                    forwardInfEngine(node);
                }
2354 2355
                else if (preferableBackend == DNN_BACKEND_VKCOM)
                {
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
                    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);
                    }
2366
                }
2367 2368 2369 2370
                else
                {
                    CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
                }
2371 2372
            }
        }
2373 2374
        else
            tm.reset();
2375

2376 2377 2378
        tm.stop();
        layersTimings[ld.id] = tm.getTimeTicks();

2379 2380 2381 2382 2383
        ld.flag = 1;
    }

    void forwardToLayer(LayerData &ld, bool clearFlags = true)
    {
2384 2385
        CV_TRACE_FUNCTION();

2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
        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;
2399
        for (it = layers.begin(); it != layers.end() && (it->second.id < ld.id); ++it)
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
        {
            LayerData &ld = it->second;
            if (ld.flag)
                continue;
            forwardLayer(ld);
        }

        //forward itself
        forwardLayer(ld);
    }

    void forwardAll()
    {
2413 2414
        CV_TRACE_FUNCTION();

2415 2416 2417
        MapIdToLayerData::reverse_iterator last_layer = layers.rbegin();
        CV_Assert(last_layer != layers.rend());
        forwardToLayer(last_layer->second, true);
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
    }

    void getLayerShapesRecursively(int id, LayersShapesMap& inOutShapes)
    {
        std::vector<LayerPin>& inputLayerIds = layers[id].inputBlobsId;

        if (inOutShapes[id].in.empty())
        {
            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];
                inOutShapes[id].in.push_back(shape);
            }
        }
        const ShapesVec& is = inOutShapes[id].in;
        ShapesVec& os = inOutShapes[id].out;
        ShapesVec& ints = inOutShapes[id].internal;
        int requiredOutputs = layers[id].requiredOutputs.size();
        inOutShapes[id].supportInPlace =
                layers[id].getLayerInstance()->getMemoryShapes(is, requiredOutputs, os, ints);
    }

    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];
    }

    LayerPin getLatestLayerPin(const std::vector<LayerPin>& pins)
    {
        return *std::max_element(pins.begin(), pins.end());
    }

    Mat getBlob(const LayerPin& pin)
    {
2478 2479
        CV_TRACE_FUNCTION();

2480 2481 2482 2483 2484 2485
        if (!pin.valid())
            CV_Error(Error::StsObjectNotFound, "Requested blob not found");

        LayerData &ld = layers[pin.lid];
        if ((size_t)pin.oid >= ld.outputBlobs.size())
        {
2486
            CV_Error(Error::StsOutOfRange, format("Layer \"%s\" produce only %zu outputs, "
luz.paz's avatar
luz.paz committed
2487
                                           "the #%d was requested", ld.name.c_str(),
2488
                                           ld.outputBlobs.size(), pin.oid));
2489
        }
2490
        if (preferableTarget != DNN_TARGET_CPU)
2491
        {
2492
            CV_Assert(!ld.outputBlobsWrappers.empty() && !ld.outputBlobsWrappers[pin.oid].empty());
2493
            // Transfer data to CPU if it's require.
2494
            ld.outputBlobsWrappers[pin.oid]->copyToHost();
2495
        }
Li Peng's avatar
Li Peng committed
2496 2497 2498 2499 2500 2501 2502 2503

        if (ld.outputBlobs[pin.oid].depth() == CV_16S)
        {
            convertFp16(ld.outputBlobs[pin.oid], output_blob);
            return output_blob;
        }
        else
            return ld.outputBlobs[pin.oid];
2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
    }

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

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

2516 2517 2518
Net Net::readFromModelOptimizer(const String& xml, const String& bin)
{
#ifndef HAVE_INF_ENGINE
2519
    CV_Error(Error::StsError, "Build OpenCV with Inference Engine to enable loading models from Model Optimizer.");
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532
#else
    InferenceEngine::CNNNetReader reader;
    reader.ReadNetwork(xml);
    reader.ReadWeights(bin);

    InferenceEngine::CNNNetwork ieNet = reader.getNetwork();

    std::vector<String> inputsNames;
    for (auto& it : ieNet.getInputsInfo())
    {
        inputsNames.push_back(it.first);
    }

2533
    Net cvNet;
2534 2535 2536 2537 2538 2539
    cvNet.setInputsNames(inputsNames);

    Ptr<InfEngineBackendNode> backendNode(new InfEngineBackendNode(0));
    backendNode->net = Ptr<InfEngineBackendNet>(new InfEngineBackendNet(ieNet));
    for (auto& it : ieNet.getOutputsInfo())
    {
2540 2541 2542 2543
        Ptr<Layer> cvLayer(new InfEngineBackendLayer(it.second));
        InferenceEngine::CNNLayerPtr ieLayer = ieNet.getLayerByName(it.first.c_str());
        CV_Assert(ieLayer);

2544 2545 2546 2547
        LayerParams lp;
        int lid = cvNet.addLayer(it.first, "", lp);

        LayerData& ld = cvNet.impl->layers[lid];
2548 2549 2550
        cvLayer->name = it.first;
        cvLayer->type = ieLayer->type;
        ld.layerInstance = cvLayer;
2551 2552
        ld.backendNodes[DNN_BACKEND_INFERENCE_ENGINE] = backendNode;

2553 2554
        for (int i = 0; i < inputsNames.size(); ++i)
            cvNet.connect(0, i, lid, i);
2555 2556 2557 2558 2559
    }
    cvNet.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);

    cvNet.impl->skipInfEngineInit = true;
    return cvNet;
2560
#endif  // HAVE_INF_ENGINE
2561 2562
}

2563 2564 2565 2566 2567 2568
Net::~Net()
{
}

int Net::addLayer(const String &name, const String &type, LayerParams &params)
{
2569 2570
    CV_TRACE_FUNCTION();

2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
    if (impl->getLayerId(name) >= 0)
    {
        CV_Error(Error::StsBadArg, "Layer \"" + name + "\" already into net");
        return -1;
    }

    int id = ++impl->lastLayerId;
    impl->layerNameToId.insert(std::make_pair(name, id));
    impl->layers.insert(std::make_pair(id, LayerData(id, name, type, params)));

    return id;
}

int Net::addLayerToPrev(const String &name, const String &type, LayerParams &params)
{
2586 2587
    CV_TRACE_FUNCTION();

2588 2589 2590 2591 2592 2593 2594 2595
    int prvLid = impl->lastLayerId;
    int newLid = this->addLayer(name, type, params);
    this->connect(prvLid, 0, newLid, 0);
    return newLid;
}

void Net::connect(int outLayerId, int outNum, int inpLayerId, int inpNum)
{
2596 2597
    CV_TRACE_FUNCTION();

2598 2599 2600 2601 2602
    impl->connect(outLayerId, outNum, inpLayerId, inpNum);
}

void Net::connect(String _outPin, String _inPin)
{
2603 2604
    CV_TRACE_FUNCTION();

2605 2606 2607 2608 2609 2610 2611 2612 2613 2614
    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)
{
2615 2616
    CV_TRACE_FUNCTION();

2617 2618 2619 2620 2621
    String layerName = outputName;

    if (layerName.empty())
        layerName = getLayerNames().back();

2622 2623
    std::vector<LayerPin> pins(1, impl->getPinByAlias(layerName));
    impl->setUpNet(pins);
2624 2625 2626 2627 2628
    impl->forwardToLayer(impl->getLayerData(layerName));

    return impl->getBlob(layerName);
}

2629
void Net::forward(OutputArrayOfArrays outputBlobs, const String& outputName)
2630
{
2631 2632
    CV_TRACE_FUNCTION();

2633 2634 2635 2636 2637
    String layerName = outputName;

    if (layerName.empty())
        layerName = getLayerNames().back();

2638 2639
    std::vector<LayerPin> pins(1, impl->getPinByAlias(layerName));
    impl->setUpNet(pins);
2640 2641 2642 2643
    impl->forwardToLayer(impl->getLayerData(layerName));

    LayerPin pin = impl->getPinByAlias(layerName);
    LayerData &ld = impl->layers[pin.lid];
2644

2645
    if (outputBlobs.isUMat())
2646
    {
2647
        impl->getBlob(layerName).copyTo(outputBlobs);
2648 2649 2650 2651 2652 2653 2654
    }
    else if (outputBlobs.isMat())
    {
        outputBlobs.assign(impl->getBlob(layerName));
    }
    else if (outputBlobs.isMatVector())
    {
2655
        if (impl->preferableTarget != DNN_TARGET_CPU)
2656
        {
2657 2658 2659 2660 2661
            for (int i = 0; i < ld.outputBlobsWrappers.size(); ++i)
            {
                CV_Assert(!ld.outputBlobsWrappers[i].empty());
                ld.outputBlobsWrappers[i]->copyToHost();
            }
2662
        }
Li Peng's avatar
Li Peng committed
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
        if (ld.outputBlobs[0].depth() == CV_32F)
        {
            std::vector<Mat> & outputvec = *(std::vector<Mat> *)outputBlobs.getObj();
            outputvec = ld.outputBlobs;
        } else {
            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]);
        }
2673 2674 2675
    }
    else if (outputBlobs.isUMatVector())
    {
2676 2677
        std::vector<UMat> & outputvec = *(std::vector<UMat> *)outputBlobs.getObj();

2678
        if (impl->preferableBackend == DNN_BACKEND_OPENCV &&
Li Peng's avatar
Li Peng committed
2679
            IS_DNN_OPENCL_TARGET(impl->preferableTarget))
2680
        {
Li Peng's avatar
Li Peng committed
2681 2682 2683 2684 2685 2686 2687 2688 2689
            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]);
            }
2690 2691
        }
        else
2692
        {
2693 2694
            outputvec.resize(ld.outputBlobs.size());
            for (int i = 0; i < outputvec.size(); ++i)
2695
                ld.outputBlobs[i].copyTo(outputvec[i]);
2696
        }
2697
    }
2698 2699
}

2700
void Net::forward(OutputArrayOfArrays outputBlobs,
2701 2702
                  const std::vector<String>& outBlobNames)
{
2703 2704
    CV_TRACE_FUNCTION();

2705 2706 2707
    std::vector<LayerPin> pins;
    for (int i = 0; i < outBlobNames.size(); i++)
    {
2708
        pins.push_back(impl->getPinByAlias(outBlobNames[i]));
2709 2710 2711 2712 2713 2714 2715 2716
    }

    impl->setUpNet(pins);

    LayerPin out = impl->getLatestLayerPin(pins);

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

2717
    std::vector<Mat> matvec;
2718 2719
    for (int i = 0; i < pins.size(); i++)
    {
2720
        matvec.push_back(impl->getBlob(pins[i]));
2721
    }
2722 2723 2724

    std::vector<Mat> & outputvec = *(std::vector<Mat> *)outputBlobs.getObj();
    outputvec = matvec;
2725 2726 2727 2728 2729
}

void Net::forward(std::vector<std::vector<Mat> >& outputBlobs,
                     const std::vector<String>& outBlobNames)
{
2730 2731
    CV_TRACE_FUNCTION();

2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
    std::vector<LayerPin> pins;
    for (int i = 0; i < outBlobNames.size(); i++)
    {
        std::vector<LayerPin> lp = impl->getLayerOutPins(outBlobNames[i]);
        pins.insert(pins.end(), lp.begin(), lp.end());
    }

    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]);
        for (int i = 0; i < lp.size(); i++)
        {
            outputBlobs[i].push_back(impl->getBlob(lp[i]));
        }
    }
}

void Net::setPreferableBackend(int backendId)
{
2758 2759 2760
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG(backendId);

2761 2762 2763 2764 2765 2766
    if( impl->preferableBackend != backendId )
    {
        impl->preferableBackend = backendId;
        impl->netWasAllocated = false;
        impl->clear();
    }
2767 2768 2769 2770
}

void Net::setPreferableTarget(int targetId)
{
2771 2772 2773
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG(targetId);

2774 2775 2776
    if( impl->preferableTarget != targetId )
    {
        impl->preferableTarget = targetId;
Li Peng's avatar
Li Peng committed
2777 2778 2779
        if (IS_DNN_OPENCL_TARGET(targetId))
        {
#ifndef HAVE_OPENCL
2780 2781 2782 2783 2784 2785 2786
#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;
Li Peng's avatar
Li Peng committed
2787 2788 2789 2790 2791 2792
#else
            bool fp16 = ocl::Device::getDefault().isExtensionSupported("cl_khr_fp16");
            if (!fp16 && targetId == DNN_TARGET_OPENCL_FP16)
                impl->preferableTarget = DNN_TARGET_OPENCL;
#endif
        }
2793 2794 2795
        impl->netWasAllocated = false;
        impl->clear();
    }
2796 2797 2798 2799
}

void Net::setInputsNames(const std::vector<String> &inputBlobNames)
{
2800 2801
    CV_TRACE_FUNCTION();

2802 2803 2804
    impl->netInputLayer->setNames(inputBlobNames);
}

2805
void Net::setInput(InputArray blob, const String& name, double scalefactor, const Scalar& mean)
2806
{
2807 2808 2809
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(name, "name", name.c_str());

2810 2811 2812 2813 2814 2815 2816 2817
    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");

    LayerData &ld = impl->layers[pin.lid];
2818 2819 2820 2821
    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);
2822 2823
    impl->netInputLayer->scaleFactors.resize(numInputs);
    impl->netInputLayer->means.resize(numInputs);
2824 2825 2826

    MatShape prevShape = shape(impl->netInputLayer->inputsData[pin.oid]);
    Mat blob_ = blob.getMat();
2827 2828
    bool oldShape = prevShape == shape(blob_);
    if (oldShape)
2829
    {
2830
        blob_.copyTo(impl->netInputLayer->inputsData[pin.oid]);
2831
    }
2832
    else
2833
    {
2834
        ld.outputBlobs[pin.oid] = blob_.clone();
2835
        impl->netInputLayer->inputsData[pin.oid] = ld.outputBlobs[pin.oid];
2836
    }
2837

2838 2839 2840 2841
    if (!ld.outputBlobsWrappers[pin.oid].empty())
    {
        ld.outputBlobsWrappers[pin.oid]->setHostDirty();
    }
2842 2843
    impl->netInputLayer->scaleFactors[pin.oid] = scalefactor;
    impl->netInputLayer->means[pin.oid] = mean;
2844 2845 2846 2847 2848 2849
    impl->netWasAllocated = impl->netWasAllocated && oldShape;
}

Mat Net::getParam(LayerId layer, int numParam)
{
    LayerData &ld = impl->getLayerData(layer);
Dmitry Kurtaev's avatar
Dmitry Kurtaev committed
2850
    std::vector<Mat> &layerBlobs = ld.getLayerInstance()->blobs;
2851 2852 2853 2854 2855 2856 2857 2858
    CV_Assert(numParam < (int)layerBlobs.size());
    return layerBlobs[numParam];
}

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

Dmitry Kurtaev's avatar
Dmitry Kurtaev committed
2859
    std::vector<Mat> &layerBlobs = ld.getLayerInstance()->blobs;
2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
    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);
}

Ptr<Layer> Net::getLayer(LayerId layerId)
{
    LayerData &ld = impl->getLayerData(layerId);
2873
    return ld.getLayerInstance();
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
}

std::vector<Ptr<Layer> > Net::getLayerInputs(LayerId layerId)
{
    LayerData &ld = impl->getLayerData(layerId);
    if (!ld.layerInstance)
        CV_Error(Error::StsNullPtr, format("Requested layer \"%s\" was not initialized", ld.name.c_str()));

    std::vector<Ptr<Layer> > inputLayers;
    inputLayers.reserve(ld.inputLayersId.size());
    std::set<int>::iterator it;
    for (it = ld.inputLayersId.begin(); it != ld.inputLayersId.end(); ++it) {
        inputLayers.push_back(getLayer(*it));
    }
    return inputLayers;
}

std::vector<String> Net::getLayerNames() const
{
    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;
}

2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
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;
}

2940
void Net::getLayersShapes(const ShapesVec& netInputShapes,
2941 2942 2943
                          std::vector<int>& layersIds,
                          std::vector<ShapesVec>& inLayersShapes,
                          std::vector<ShapesVec>& outLayersShapes) const
2944
{
2945 2946 2947
    layersIds.clear();
    inLayersShapes.clear();
    outLayersShapes.clear();
2948 2949 2950 2951 2952 2953 2954

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

    for(Impl::LayersShapesMap::const_iterator it = inOutShapes.begin();
        it != inOutShapes.end(); it++)
    {
2955 2956 2957
        layersIds.push_back(it->first);
        inLayersShapes.push_back(it->second.in);
        outLayersShapes.push_back(it->second.out);
2958 2959 2960 2961
    }
}

void Net::getLayersShapes(const MatShape& netInputShape,
2962 2963 2964
                          std::vector<int>& layerIds,
                          std::vector<ShapesVec>& inLayersShapes,
                          std::vector<ShapesVec>& outLayersShapes) const
2965 2966 2967 2968 2969 2970 2971
{
    getLayersShapes(ShapesVec(1, netInputShape),
                    layerIds, inLayersShapes, outLayersShapes);
}

void Net::getLayerShapes(const MatShape& netInputShape,
                         const int layerId,
2972 2973
                         ShapesVec& inLayerShapes,
                         ShapesVec& outLayerShapes) const
2974 2975 2976 2977 2978 2979 2980 2981
{
    getLayerShapes(ShapesVec(1, netInputShape),
                   layerId, inLayerShapes, outLayerShapes);

}

void Net::getLayerShapes(const ShapesVec& netInputShapes,
                    const int layerId,
2982 2983
                    ShapesVec& inLayerShapes,
                    ShapesVec& outLayerShapes) const
2984 2985 2986
{
    LayerShapes shapes;
    impl->getLayerShapes(netInputShapes, layerId, shapes);
2987 2988
    inLayerShapes = shapes.in;
    outLayerShapes = shapes.out;
2989 2990 2991 2992
}

int64 Net::getFLOPS(const std::vector<MatShape>& netInputShapes) const
{
2993 2994
    CV_TRACE_FUNCTION();

2995 2996 2997
    int64 flops = 0;
    std::vector<int> ids;
    std::vector<std::vector<MatShape> > inShapes, outShapes;
2998
    getLayersShapes(netInputShapes, ids, inShapes, outShapes);
2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
    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
{
3070 3071
    CV_TRACE_FUNCTION();

3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
    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();
    }

3083 3084
    ShapesVec inLayerShapes, outLayerShapes;
    getLayerShapes(netInputShapes, layerId, inLayerShapes, outLayerShapes);
3085 3086 3087 3088 3089 3090 3091 3092 3093
    for(int i = 0; i < outLayerShapes.size(); i++)
    {
        blobs += total(outLayerShapes[i]) * sizeof(float);
    }
}

void Net::getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
                               size_t& weights, size_t& blobs) const
{
3094 3095
    CV_TRACE_FUNCTION();

3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
    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
{
3127 3128
    CV_TRACE_FUNCTION();

3129 3130 3131 3132
    layerIds.clear();
    weights.clear();
    blobs.clear();

3133
    std::vector<std::vector<MatShape> > inLayerShapes, outLayerShapes;
3134

3135
    getLayersShapes(netInputShapes, layerIds, inLayerShapes, outLayerShapes);
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165

    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++)
        {
            b += total(outLayerShapes[i][j]) * sizeof(float);
        }

        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);
}

3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
void Net::enableFusion(bool fusion)
{
    if( impl->fusion != fusion )
    {
        impl->fusion = fusion;
        impl->netWasAllocated = false;
        impl->clear();
    }
}

3176 3177
void Net::setHalideScheduler(const String& scheduler)
{
3178 3179 3180
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(scheduler, "scheduler", scheduler.c_str());

3181 3182 3183
    impl->halideConfigFile = scheduler;
}

3184 3185 3186 3187 3188 3189 3190
int64 Net::getPerfProfile(std::vector<double>& timings)
{
    timings = std::vector<double>(impl->layersTimings.begin() + 1, impl->layersTimings.end());
    int64 total = std::accumulate(timings.begin(), timings.end(), 0);
    return total;
}

3191 3192
//////////////////////////////////////////////////////////////////////////

3193
Layer::Layer() { preferableTarget = DNN_TARGET_CPU; }
3194 3195 3196 3197

Layer::Layer(const LayerParams &params)
    : blobs(params.blobs), name(params.name), type(params.type)
{
3198
    preferableTarget = DNN_TARGET_CPU;
3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
}

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

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

3213
int Layer::outputNameToIndex(const String&)
3214
{
3215
    return 0;
3216 3217 3218 3219
}

bool Layer::supportBackend(int backendId)
{
3220
    return backendId == DNN_BACKEND_OPENCV;
3221 3222
}

3223 3224 3225 3226 3227 3228 3229
Ptr<BackendNode> Layer::initVkCom(const std::vector<Ptr<BackendWrapper> > &)
{
    CV_Error(Error::StsNotImplemented, "VkCom pipeline of " + type +
                                       " layers is not defined.");
    return Ptr<BackendNode>();
}

3230 3231 3232 3233 3234 3235 3236
Ptr<BackendNode> Layer::initHalide(const std::vector<Ptr<BackendWrapper> > &)
{
    CV_Error(Error::StsNotImplemented, "Halide pipeline of " + type +
                                       " layers is not defined.");
    return Ptr<BackendNode>();
}

3237 3238 3239 3240 3241 3242 3243
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>();
}

3244 3245 3246 3247
void Layer::applyHalideScheduler(Ptr<BackendNode>& node, const std::vector<Mat*> &inputs,
                                 const std::vector<Mat> &outputs, int targetId) const
{
#ifdef  HAVE_HALIDE
3248 3249
    CV_TRACE_FUNCTION();

3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
    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)
        {
3290
            int c_split = outC > 8 ? (outC > 16 ? 8 : 4) : outC;
3291 3292 3293 3294 3295 3296 3297 3298 3299
            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;
3300 3301
            // Supported vectorization widths: 2, 3, 4, 8, 16
            int c_split = outC > 8 ? (outC > 16 ? 8 : 4) : std::min(4, outC);
3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319
            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>();
}

3320
bool Layer::setActivation(const Ptr<ActivationLayer>&) { return false; }
3321 3322 3323 3324 3325 3326 3327
bool Layer::tryFuse(Ptr<Layer>&) { return false; }
void Layer::getScaleShift(Mat& scale, Mat& shift) const
{
    scale = Mat();
    shift = Mat();
}

3328 3329 3330 3331
void Layer::unsetAttached()
{
    setActivation(Ptr<ActivationLayer>());
}
3332

3333 3334 3335 3336 3337 3338 3339 3340 3341 3342
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)
{
3343
    CV_TRACE_FUNCTION();
3344
    this->finalize((InputArrayOfArrays)inputs, (OutputArrayOfArrays)outputs);
3345 3346 3347 3348
}

void Layer::finalize(const std::vector<Mat*> &input, std::vector<Mat> &output)
{
3349
    CV_UNUSED(input);CV_UNUSED(output);
3350 3351
}

3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
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);
}

3364 3365
std::vector<Mat> Layer::finalize(const std::vector<Mat> &inputs)
{
3366 3367
    CV_TRACE_FUNCTION();

3368 3369 3370 3371 3372
    std::vector<Mat> outputs;
    this->finalize(inputs, outputs);
    return outputs;
}

3373 3374 3375 3376 3377 3378
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)
3379 3380 3381 3382
{
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(name, "name", name.c_str());

3383
    Layer::forward_fallback(inputs_arr, outputs_arr, internals_arr);
3384 3385
}

3386
void Layer::forward_fallback(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr)
3387
{
3388
    CV_TRACE_FUNCTION();
3389
    CV_TRACE_ARG_VALUE(name, "name", name.c_str());
3390

Li Peng's avatar
Li Peng committed
3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
    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;
    }
3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439
    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);
3440 3441 3442 3443

    // sync results back
    outputs_arr.assign(outputs);
    internals_arr.assign(internals);
3444 3445 3446 3447
}

void Layer::run(const std::vector<Mat> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals)
{
3448 3449
    CV_TRACE_FUNCTION();

3450 3451
    this->finalize(inputs, outputs);
    this->forward(inputs, outputs, internals);
3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467
}

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;
}

//////////////////////////////////////////////////////////////////////////

3468
static Mutex& getLayerFactoryMutex()
3469
{
3470 3471 3472 3473 3474 3475 3476 3477 3478 3479
    static Mutex* volatile instance = NULL;
    if (instance == NULL)
    {
        cv::AutoLock lock(getInitializationMutex());
        if (instance == NULL)
            instance = new Mutex();
    }
    return *instance;
}

3480
typedef std::map<String, std::vector<LayerFactory::Constructor> > LayerFactory_Impl;
3481 3482 3483 3484 3485 3486

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

3488
static LayerFactory_Impl& getLayerFactoryImpl()
3489
{
3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500
    static LayerFactory_Impl* volatile instance = NULL;
    if (instance == NULL)
    {
        cv::AutoLock lock(getLayerFactoryMutex());
        if (instance == NULL)
        {
            instance = &getLayerFactoryImpl_();
            initializeLayerFactory();
        }
    }
    return *instance;
3501 3502
}

3503
void LayerFactory::registerLayer(const String &type, Constructor constructor)
3504
{
3505 3506 3507
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

3508
    cv::AutoLock lock(getLayerFactoryMutex());
3509
    String type_ = toLowerCase(type);
3510
    LayerFactory_Impl::iterator it = getLayerFactoryImpl().find(type_);
3511

3512
    if (it != getLayerFactoryImpl().end())
3513
    {
3514 3515 3516
        if (it->second.back() == constructor)
            CV_Error(cv::Error::StsBadArg, "Layer \"" + type_ + "\" already was registered");
        it->second.push_back(constructor);
3517
    }
3518
    getLayerFactoryImpl().insert(std::make_pair(type_, std::vector<Constructor>(1, constructor)));
3519 3520
}

3521
void LayerFactory::unregisterLayer(const String &type)
3522
{
3523 3524 3525
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

3526
    cv::AutoLock lock(getLayerFactoryMutex());
3527
    String type_ = toLowerCase(type);
3528 3529 3530 3531 3532 3533 3534 3535 3536

    LayerFactory_Impl::iterator it = getLayerFactoryImpl().find(type_);
    if (it != getLayerFactoryImpl().end())
    {
        if (it->second.size() > 1)
            it->second.pop_back();
        else
            getLayerFactoryImpl().erase(it);
    }
3537 3538
}

3539
Ptr<Layer> LayerFactory::createLayerInstance(const String &type, LayerParams& params)
3540
{
3541 3542 3543
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

3544
    cv::AutoLock lock(getLayerFactoryMutex());
3545
    String type_ = toLowerCase(type);
3546
    LayerFactory_Impl::const_iterator it = getLayerFactoryImpl().find(type_);
3547

3548
    if (it != getLayerFactoryImpl().end())
3549
    {
3550 3551
        CV_Assert(!it->second.empty());
        return it->second.back()(params);
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
    }
    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() {}

3580
Net readNet(const String& _model, const String& _config, const String& _framework)
3581
{
3582
    String framework = toLowerCase(_framework);
3583 3584
    String model = _model;
    String config = _config;
3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612
    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);
    }
3613 3614 3615 3616 3617 3618 3619
    if (framework == "dldt" || modelExt == "bin" || configExt == "bin" ||
                               modelExt == "xml" || configExt == "xml")
    {
        if (modelExt == "xml" || configExt == "bin")
            std::swap(model, config);
        return readNetFromModelOptimizer(config, model);
    }
3620 3621 3622 3623
    if (framework == "onnx" || modelExt == "onnx")
    {
        return readNetFromONNX(model);
    }
3624
    CV_Error(Error::StsError, "Cannot determine an origin framework of files: " +
3625
                                      model + (config.empty() ? "" : ", " + config));
3626 3627
}

3628 3629
Net readNet(const String& _framework, const std::vector<uchar>& bufferModel,
            const std::vector<uchar>& bufferConfig)
3630
{
3631
    String framework = toLowerCase(_framework);
3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644
    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")
        CV_Error(Error::StsNotImplemented, "Reading Intel's Model Optimizer models from buffers");
    CV_Error(Error::StsError, "Cannot determine an origin framework with a name " + framework);
}

3645 3646 3647 3648 3649
Net readNetFromModelOptimizer(const String &xml, const String &bin)
{
    return Net::readFromModelOptimizer(xml, bin);
}

3650
CV__DNN_INLINE_NS_END
3651
}} // namespace