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

54 55 56
namespace cv {
namespace dnn {
CV__DNN_EXPERIMENTAL_NS_BEGIN
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

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

template<typename T>
static String toString(const T &v)
{
    std::ostringstream ss;
    ss << v;
    return ss.str();
}

87
Mat blobFromImage(InputArray image, double scalefactor, const Size& size,
88
                  const Scalar& mean, bool swapRB, bool crop)
89
{
A
Alexander Alekhin 已提交
90
    CV_TRACE_FUNCTION();
91
    std::vector<Mat> images(1, image.getMat());
92
    return blobFromImages(images, scalefactor, size, mean, swapRB, crop);
93 94 95
}

Mat blobFromImages(const std::vector<Mat>& images_, double scalefactor, Size size,
96
                   const Scalar& mean_, bool swapRB, bool crop)
97
{
A
Alexander Alekhin 已提交
98
    CV_TRACE_FUNCTION();
99 100 101 102 103 104 105 106
    std::vector<Mat> images = images_;
    for (int i = 0; i < images.size(); i++)
    {
        Size imgSize = images[i].size();
        if (size == Size())
            size = imgSize;
        if (size != imgSize)
        {
107 108 109 110
            if(crop)
            {
              float resizeFactor = std::max(size.width / (float)imgSize.width,
                                            size.height / (float)imgSize.height);
111
              resize(images[i], images[i], Size(), resizeFactor, resizeFactor, INTER_LINEAR);
112 113 114 115 116 117
              Rect crop(Point(0.5 * (images[i].cols - size.width),
                              0.5 * (images[i].rows - size.height)),
                        size);
              images[i] = images[i](crop);
            }
            else
118
              resize(images[i], images[i], size, 0, 0, INTER_LINEAR);
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        }
        if(images[i].depth() == CV_8U)
            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();
    if(nimages == 0)
        return Mat();
    Mat image0 = images[0];
    int nch = image0.channels();
    CV_Assert(image0.dims == 2);
    Mat blob, image;
    if (nch == 3 || nch == 4)
    {
139
        int sz[] = { (int)nimages, nch, image0.rows, image0.cols };
140 141 142 143 144 145 146 147 148 149 150
        blob = Mat(4, sz, CV_32F);
        Mat ch[4];

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

151
            for( int j = 0; j < nch; j++ )
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
                ch[j] = Mat(image.rows, image.cols, CV_32F, blob.ptr((int)i, j));
            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 };
       blob = Mat(4, sz, CV_32F);

       for( i = 0; i < nimages; i++ )
       {
           Mat image = images[i];
           CV_Assert(image.depth() == CV_32F);
           nch = image.channels();
           CV_Assert(image.dims == 2 && (nch == 1));
           CV_Assert(image.size() == image0.size());

           image.copyTo(Mat(image.rows, image.cols, CV_32F, blob.ptr((int)i, 0)));
       }
    }
    return blob;
}

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
{
209
    LayerData() : id(-1), flag(0) {}
210
    LayerData(int _id, const String &_name, const String &_type, LayerParams &_params)
211
        : id(_id), name(_name), type(_type), params(_params), flag(0)
212
    {
A
Alexander Alekhin 已提交
213 214
        CV_TRACE_FUNCTION();

215 216 217 218 219 220 221 222 223 224 225 226 227 228
        //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;
229 230
    std::vector<Ptr<BackendWrapper> > outputBlobsWrappers;
    std::vector<Ptr<BackendWrapper> > inputBlobsWrappers;
231 232 233 234 235

    Ptr<Layer> layerInstance;
    std::vector<Mat> outputBlobs;
    std::vector<Mat*> inputBlobs;
    std::vector<Mat> internals;
L
Li Peng 已提交
236 237 238
    std::vector<UMat> umat_outputBlobs;
    std::vector<UMat> umat_inputBlobs;
    std::vector<UMat> umat_internals;
239 240 241 242 243 244 245 246 247
    // Computation nodes of implemented backends (except DEFAULT).
    std::map<int, Ptr<BackendNode> > backendNodes;
    // Flag for skip layer computation for specific backend.
    std::map<int, bool> skipFlags;

    int flag;

    Ptr<Layer> getLayerInstance()
    {
A
Alexander Alekhin 已提交
248 249 250
        CV_TRACE_FUNCTION();
        CV_TRACE_ARG_VALUE(type, "type", type.c_str());

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        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
{
    void finalize(const std::vector<Mat*>&, std::vector<Mat>&) {}
    void forward(std::vector<Mat*>&, std::vector<Mat>&, std::vector<Mat> &) {}
L
Li Peng 已提交
269
    void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals) {}
270 271 272 273 274 275 276 277 278 279 280 281

    int outputNameToIndex(String tgtName)
    {
        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());
    }

282 283 284 285 286 287 288 289 290 291
    bool getMemoryShapes(const std::vector<MatShape> &inputs,
                         const int requiredOutputs,
                         std::vector<MatShape> &outputs,
                         std::vector<MatShape> &internals) const
    {
        CV_Assert(inputs.size() == requiredOutputs);
        outputs.assign(inputs.begin(), inputs.end());
        return false;
    }

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 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 367 368 369
private:
    std::vector<String> outNames;
};

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

370
    void reuseOrCreate(const MatShape& shape, const LayerPin& lp, Mat& dst)
371
    {
372
#ifdef REUSE_DNN_MEMORY
373 374
        Mat bestBlob;
        LayerPin bestBlobPin;
375

376 377
        std::map<LayerPin, Mat>::iterator hostIt;
        std::map<LayerPin, int>::iterator refIt;
378

379 380
        const int targetTotal = total(shape);
        int bestBlobTotal = INT_MAX;
381

382 383 384 385 386 387
        for (hostIt = memHosts.begin(); hostIt != memHosts.end(); ++hostIt)
        {
            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)
388
            {
389 390 391
                Mat& unusedBlob = hostIt->second;
                if (unusedBlob.total() >= targetTotal &&
                    unusedBlob.total() < bestBlobTotal)
392
                {
393 394 395
                    bestBlobPin = hostIt->first;
                    bestBlob = unusedBlob;
                    bestBlobTotal = unusedBlob.total();
396 397 398 399 400 401
                }
            }
        }
        if (!bestBlob.empty())
        {
            reuse(bestBlobPin, lp);
402
            dst = bestBlob.reshape(1, 1).colRange(0, targetTotal).reshape(1, shape);
403 404
        }
        else
405
#endif  // REUSE_DNN_MEMORY
406 407 408 409 410 411 412 413
        {
            // if dst already has been allocated with total(shape) elements,
            // it won't be recrreated and pointer of dst.data remains the same.
            dst.create(shape, CV_32F);
            addHost(lp, dst);
        }
    }

414
    void reuseOrCreate(const MatShape& shape, const LayerPin& lp, UMat &umat_dst)
L
Li Peng 已提交
415
    {
416
#ifdef REUSE_DNN_MEMORY
L
Li Peng 已提交
417 418 419
        UMat bestBlob;
        LayerPin bestBlobPin;

420 421
        std::map<LayerPin, UMat>::iterator hostIt;
        std::map<LayerPin, int>::iterator refIt;
L
Li Peng 已提交
422

423 424
        const int targetTotal = total(shape);
        int bestBlobTotal = INT_MAX;
L
Li Peng 已提交
425

426 427 428 429 430 431
        for (hostIt = umat_memHosts.begin(); hostIt != umat_memHosts.end(); ++hostIt)
        {
            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)
L
Li Peng 已提交
432
            {
433 434 435
                UMat& unusedBlob = hostIt->second;
                if (unusedBlob.total() >= targetTotal &&
                    unusedBlob.total() < bestBlobTotal)
L
Li Peng 已提交
436
                {
437 438 439
                    bestBlobPin = hostIt->first;
                    bestBlob = unusedBlob;
                    bestBlobTotal = unusedBlob.total();
L
Li Peng 已提交
440 441 442 443 444 445 446 447 448
                }
            }
        }
        if (!bestBlob.empty())
        {
            reuse(bestBlobPin, lp);
            umat_dst.create(shape, CV_32F);
        }
        else
449
#endif  // REUSE_DNN_MEMORY
L
Li Peng 已提交
450 451 452 453 454 455 456 457
        {
            // if dst already has been allocated with total(shape) elements,
            // it won't be recrreated and pointer of dst.data remains the same.
            umat_dst.create(shape, CV_32F);
            addHost(lp, umat_dst);
        }
    }

458
    void allocateBlobsForLayer(LayerData &ld, const LayerShapes& layerShapes,
459
                               std::vector<LayerPin>& pinsForInternalBlobs)
460
    {
A
Alexander Alekhin 已提交
461
        CV_TRACE_FUNCTION();
L
Li Peng 已提交
462 463
        bool use_umat = (preferableBackend == DNN_BACKEND_DEFAULT &&
                         preferableTarget == DNN_TARGET_OPENCL);
A
Alexander Alekhin 已提交
464

465 466 467 468 469
        pinsForInternalBlobs.clear();

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

L
Li Peng 已提交
470 471 472
        std::vector<UMat>& umat_outputBlobs = ld.umat_outputBlobs,
                &umat_internalBlobs = ld.umat_internals;

473 474 475 476 477
        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());
L
Li Peng 已提交
478 479 480 481 482
        if (use_umat)
        {
            umat_outputBlobs.resize(std::max((size_t)1, outShapes.size()));
            umat_internalBlobs.resize(internalShapes.size());
        }
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

        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;
L
Li Peng 已提交
502
        std::vector<UMat*> umat_blobs;
503 504 505
        for(int i = 0; i < outputBlobs.size(); i++)
        {
            blobs.push_back(&outputBlobs[i]);
L
Li Peng 已提交
506 507
            if (use_umat)
                umat_blobs.push_back(&umat_outputBlobs[i]);
508 509 510 511 512
        }

        for(int i = 0; i < internalBlobs.size(); i++)
        {
            blobs.push_back(&internalBlobs[i]);
L
Li Peng 已提交
513 514
            if (use_umat)
                umat_blobs.push_back(&umat_internalBlobs[i]);
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
            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);
538
                    if (index < outShapes.size() && inPlace)
539
                    {
L
Li Peng 已提交
540 541 542 543 544 545 546 547 548 549 550 551
                        if (use_umat)
                        {
                            CV_Assert(ld.umat_inputBlobs[0].total() == total(shapes[index]));
                            ld.umat_outputBlobs[index] =
                                ld.umat_inputBlobs[0].reshape(1, shapes[index].size(),
                                                              &shapes[index][0]);
                        }
                        else
                        {
                            CV_Assert(ld.inputBlobs[0]->total() == total(shapes[index]));
                            ld.outputBlobs[index] = ld.inputBlobs[0]->reshape(1, shapes[index]);
                        }
552 553 554 555
                        reuse(ld.inputBlobsId[0], blobPin);
                    }
                    else
                    {
L
Li Peng 已提交
556
                        if (use_umat)
557
                            reuseOrCreate(shapes[index], blobPin, *umat_blobs[index]);
L
Li Peng 已提交
558
                        else
559
                            reuseOrCreate(shapes[index], blobPin, *blobs[index]);
560 561 562 563 564 565 566 567 568
                    }
                }
            }
        }
    }

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

571 572 573
        refCounter.clear();
        reuseMap.clear();
        memHosts.clear();
L
Li Peng 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586
        umat_memHosts.clear();
        preferableTarget = DNN_TARGET_CPU;
        preferableBackend = DNN_BACKEND_DEFAULT;
    }

    void setPreferableTarget(int targetId)
    {
        preferableTarget = targetId;
    }

    void setPreferableBackend(int backendId)
    {
        preferableBackend = backendId;
587 588 589 590 591 592 593 594 595 596 597
    }

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

L
Li Peng 已提交
598 599 600 601 602 603 604
    void addHost(const LayerPin& lp, const UMat& umat)
    {
        CV_Assert(umat_memHosts.find(lp) == umat_memHosts.end());
        reuseMap[lp] = lp;
        umat_memHosts[lp] = umat;
    }

605 606 607 608 609
    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;
L
Li Peng 已提交
610 611 612
    std::map<LayerPin, UMat> umat_memHosts;
    int preferableTarget;
    int preferableBackend;
613 614
};

615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
static Ptr<BackendWrapper> wrapMat(int backendId, int targetId, const cv::Mat& m)
{
    if (backendId == DNN_BACKEND_DEFAULT)
    {
        return Ptr<BackendWrapper>();
    }
    else if (backendId == DNN_BACKEND_HALIDE)
    {
        CV_Assert(haveHalide());
#ifdef HAVE_HALIDE
        return Ptr<BackendWrapper>(new HalideBackendWrapper(targetId, m));
#endif  // HAVE_HALIDE
    }
    else
        CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
    return Ptr<BackendWrapper>();
}

633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
struct Net::Impl
{
    typedef std::map<int, LayerShapes> LayersShapesMap;
    typedef std::map<int, LayerData> MapIdToLayerData;

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

649
        lastLayerId = 0;
650
        netWasAllocated = false;
651
        fusion = true;
652 653
        preferableBackend = DNN_BACKEND_DEFAULT;
        preferableTarget = DNN_TARGET_CPU;
654 655
        blobManager.setPreferableBackend(DNN_BACKEND_DEFAULT);
        blobManager.setPreferableTarget(DNN_TARGET_CPU);
656 657 658 659 660 661 662 663 664 665 666
    }

    Ptr<DataLayer> netInputLayer;
    std::vector<int> netOutputs;
    std::vector<LayerPin> blobsToKeep;
    MapIdToLayerData layers;
    std::map<String, int> layerNameToId;
    BlobManager blobManager;
    int preferableBackend;
    int preferableTarget;
    String halideConfigFile;
667 668
    // Map host data to backend specific wrapper.
    std::map<void*, Ptr<BackendWrapper> > backendWrappers;
669 670 671 672

    int lastLayerId;

    bool netWasAllocated;
673
    bool fusion;
674
    std::vector<int64> layersTimings;
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
    Ptr<BackendWrapper> wrap(const Mat& host)
    {
        if (preferableBackend == DNN_BACKEND_DEFAULT)
            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];
            if (preferableBackend == DNN_BACKEND_HALIDE)
            {
                CV_Assert(haveHalide());
  #ifdef HAVE_HALIDE
                return Ptr<BackendWrapper>(new HalideBackendWrapper(baseBuffer, shape));
  #endif  // HAVE_HALIDE
            }
            else
                CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
        }

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

705
#ifdef HAVE_HALIDE
706 707
    void compileHalide()
    {
A
Alexander Alekhin 已提交
708 709
        CV_TRACE_FUNCTION();

710 711 712
        CV_Assert(preferableBackend == DNN_BACKEND_HALIDE);

        HalideScheduler scheduler(halideConfigFile);
713 714
        std::vector< std::reference_wrapper<LayerData> > compileList; compileList.reserve(64);
        for (MapIdToLayerData::iterator it = layers.begin(); it != layers.end(); ++it)
715 716 717 718 719 720 721 722 723 724 725 726 727 728
        {
            LayerData &ld = it->second;
            Ptr<Layer> layer = ld.layerInstance;
            if (layer->supportBackend(DNN_BACKEND_HALIDE) && !ld.skipFlags[DNN_BACKEND_HALIDE])
            {
                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);
                }
729
                compileList.emplace_back(ld);
730 731
            }
        }
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
        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();
751
    }
752
#endif
753 754 755

    void clear()
    {
A
Alexander Alekhin 已提交
756 757
        CV_TRACE_FUNCTION();

758 759 760 761
        MapIdToLayerData::iterator it;
        for (it = layers.begin(); it != layers.end(); it++)
        {
            if (it->second.id != 0) {
A
Aleksandr Rybnikov 已提交
762
                it->second.inputBlobs.clear();
763 764
                it->second.outputBlobs.clear();
                it->second.internals.clear();
L
Li Peng 已提交
765 766 767
                it->second.umat_inputBlobs.clear();
                it->second.umat_outputBlobs.clear();
                it->second.umat_internals.clear();
768 769
            }
            it->second.skipFlags.clear();
770 771
            //it->second.consumers.clear();
            Ptr<Layer> currLayer = it->second.layerInstance;
772

773 774 775
            if( currLayer.empty() )
                continue;

776
            currLayer->unsetAttached();
777

778
            Ptr<PoolingLayer> poolingLayer = currLayer.dynamicCast<PoolingLayer>();
779 780 781 782 783
            if( !poolingLayer.empty() )
            {
                poolingLayer->computeMaxIdx = true;
            }
        }
784 785 786
        it = layers.find(0);
        CV_Assert(it != layers.end());
        it->second.skipFlags[DNN_BACKEND_DEFAULT] = true;
787 788

        layersTimings.clear();
789 790 791 792
    }

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

795 796 797 798 799 800 801 802 803 804
        if (!netWasAllocated || this->blobsToKeep != blobsToKeep_)
        {
            clear();

            allocateLayers(blobsToKeep_);
            computeNetOutputLayers();
            initBackend();

            if (!netWasAllocated )
            {
805
#ifdef HAVE_HALIDE
806 807
                if (preferableBackend == DNN_BACKEND_HALIDE)
                    compileHalide();
808 809 810
#else
                CV_Assert(preferableBackend != DNN_BACKEND_HALIDE);
#endif
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
            }

            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)
            CV_Error(Error::StsError, "Requsted layer \"" + layerName + "\" not found");

        return getLayerData(id);
    }

    LayerData& getLayerData(const DictValue &layerDesc)
    {
869
        CV_Assert(layerDesc.isInt() || layerDesc.isString());
870 871
        if (layerDesc.isInt())
            return getLayerData(layerDesc.get<int>());
872
        else /*if (layerDesc.isString())*/
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
            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))
                CV_Error(Error::StsError, "Input #" + toString(inNum) + "of layer \"" + ld.name + "\" already was connected");
        }

        ld.inputBlobsId[inNum] = from;
    }

    static void splitPin(const String &pinAlias, String &layerName, String &outName)
    {
        size_t delimPos = pinAlias.find('.');
        layerName = pinAlias.substr(0, delimPos);
        outName = (delimPos == String::npos) ? String() : pinAlias.substr(delimPos + 1);
    }

    int resolvePinOutputName(LayerData &ld, const String &outName)
    {
        if (outName.empty())
            return 0;

        if (std::isdigit(outName[0]))
        {
            char *lastChar;
            long inum = std::strtol(outName.c_str(), &lastChar, 10);

            if (*lastChar == 0)
            {
                CV_Assert(inum == (int)inum);
                return (int)inum;
            }
        }

        return ld.getLayerInstance()->outputNameToIndex(outName);
    }

    LayerPin getPinByAlias(const String &pinAlias)
    {
        LayerPin pin;
        String layerName, outName;
        splitPin(pinAlias, layerName, outName);

        pin.lid = (layerName.empty()) ? 0 : getLayerId(layerName);

        if (pin.lid >= 0)
            pin.oid = resolvePinOutputName(getLayerData(pin.lid), outName);

        return pin;
    }

    std::vector<LayerPin> getLayerOutPins(const String &pinAlias)
    {
        String layerName, outName;
        splitPin(pinAlias, layerName, outName);

        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 computeNetOutputLayers()
    {
A
Alexander Alekhin 已提交
963 964
        CV_TRACE_FUNCTION();

965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
        netOutputs.clear();

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

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

        #ifndef NDEBUG
        std::cout << "\nNet Outputs(" << netOutputs.size() << "):\n";
        for (size_t i = 0; i < netOutputs.size(); i++)
            std::cout << layers[netOutputs[i]].name << "\n";
        #endif
    }

    void initBackend()
    {
A
Alexander Alekhin 已提交
986 987
        CV_TRACE_FUNCTION();

988 989
        if (preferableBackend == DNN_BACKEND_DEFAULT)
        {
990
            CV_Assert(preferableTarget == DNN_TARGET_CPU || preferableTarget == DNN_TARGET_OPENCL);
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
            return;
        }

        // 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())
                    {
                        ldTop.skipFlags[preferableBackend] = true;
                        ldBot.backendNodes[preferableBackend] = fusedNode;
                        continue;
                    }
                }
            }
            // No layers fusion.
            ldTop.skipFlags[preferableBackend] = false;
            if (preferableBackend == DNN_BACKEND_HALIDE)
            {
1039 1040
                ldTop.backendNodes[DNN_BACKEND_HALIDE] =
                    layerTop->initHalide(ldTop.inputBlobsWrappers);
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
                baseIt = it;
            }
            else
            {
                CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
            }
        }
    }

    void allocateLayer(int lid, const LayersShapesMap& layersShapes)
    {
A
Alexander Alekhin 已提交
1052 1053
        CV_TRACE_FUNCTION();

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
        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
L
Li Peng 已提交
1088 1089
        bool use_umat = (preferableBackend == DNN_BACKEND_DEFAULT &&
                         preferableTarget == DNN_TARGET_OPENCL);
1090
        ld.inputBlobs.resize(ninputs);
L
Li Peng 已提交
1091 1092
        if (use_umat)
            ld.umat_inputBlobs.resize(ninputs);
1093
        ld.inputBlobsWrappers.resize(ninputs);
1094 1095 1096 1097 1098 1099
        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];
L
Li Peng 已提交
1100 1101
            if (use_umat)
                ld.umat_inputBlobs[i] = layers[from.lid].umat_outputBlobs[from.oid];
1102
            ld.inputBlobsWrappers[i] = layers[from.lid].outputBlobsWrappers[from.oid];
1103 1104 1105 1106 1107 1108 1109
        }

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

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

        std::vector<LayerPin> pinsForInternalBlobs;
1110
        blobManager.allocateBlobsForLayer(ld, layerShapesIt->second, pinsForInternalBlobs);
1111 1112 1113 1114 1115
        ld.outputBlobsWrappers.resize(ld.outputBlobs.size());
        for (int i = 0; i < ld.outputBlobs.size(); ++i)
        {
            ld.outputBlobsWrappers[i] = wrap(ld.outputBlobs[i]);
        }
1116 1117 1118

        Ptr<Layer> layerPtr = ld.getLayerInstance();
        {
L
Li Peng 已提交
1119 1120
            if (use_umat)
            {
L
Li Peng 已提交
1121
                std::vector<Mat> input_mats(ld.umat_inputBlobs.size());;
L
Li Peng 已提交
1122 1123 1124 1125
                std::vector<Mat*> inputs(ld.umat_inputBlobs.size());;
                std::vector<Mat> outputs(ld.umat_outputBlobs.size());
                for (int i = 0; i < inputs.size(); i++)
                {
L
Li Peng 已提交
1126 1127
                    input_mats[i] = ld.umat_inputBlobs[i].getMat(ACCESS_READ);
                    inputs[i] = &input_mats[i];
L
Li Peng 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
                }
                for (int i = 0; i < outputs.size(); i++)
                {
                    outputs[i] = ld.umat_outputBlobs[i].getMat(ACCESS_READ);
                }
                layerPtr->finalize(inputs, outputs);
            }
            else
            {
                layerPtr->finalize(ld.inputBlobs, ld.outputBlobs);
            }
1139
            layerPtr->preferableTarget = preferableTarget;
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
#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;
    }

1158 1159 1160 1161 1162 1163
#if 0
#define printf_(args) printf args
#else
#define printf_(args)
#endif

1164 1165
    void fuseLayers(const std::vector<LayerPin>& blobsToKeep_)
    {
W
Wu Zhiwen 已提交
1166
        if( !fusion || preferableBackend != DNN_BACKEND_DEFAULT)
1167 1168
            return;

A
Alexander Alekhin 已提交
1169 1170
        CV_TRACE_FUNCTION();

1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
        // 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::vector<String> outnames;
        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];
            if( ld.skipFlags[DNN_BACKEND_DEFAULT] )
            {
1183
                printf_(("skipped %s: %s\n", ld.layerInstance->name.c_str(), ld.layerInstance->type.c_str()));
1184 1185
                continue;
            }
1186
            printf_(("analyzing %s: %s\n", ld.layerInstance->name.c_str(), ld.layerInstance->type.c_str()));
1187 1188
            if( ld.consumers.size() == 0 )
                outnames.push_back(ld.layerInstance->name);
1189

1190 1191 1192 1193
            // 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.
W
Wu Zhiwen 已提交
1194 1195

            // TODO: OpenCL target support more fusion styles.
1196 1197
            if ( preferableTarget == DNN_TARGET_OPENCL &&
                 (!cv::ocl::useOpenCL() || ld.layerInstance->type.compare("Convolution")) )
W
Wu Zhiwen 已提交
1198 1199
                continue;

1200 1201
            Ptr<Layer>& currLayer = ld.layerInstance;
            if( ld.consumers.size() == 1 && pinsToKeep.count(LayerPin(lid, 0)) == 0 )
1202 1203 1204 1205 1206 1207 1208 1209 1210
            {
                LayerData* nextData = &layers[ld.consumers[0].lid];
                Ptr<BatchNormLayer> nextBNormLayer =
                    nextData->layerInstance.dynamicCast<BatchNormLayer>();
                LayerPin lpNext(ld.consumers[0].lid, 0);
                if( !nextBNormLayer.empty() && pinsToKeep.count(lpNext) == 0 )
                {
                    LayerData* bnormData = nextData;
                    nextData = 0;
1211
                    if( currLayer->setBatchNorm(nextBNormLayer) )
1212
                    {
1213
                        printf_(("\tfused with %s\n", nextBNormLayer->name.c_str()));
1214
                        bnormData->skipFlags[DNN_BACKEND_DEFAULT] = true;
1215 1216 1217 1218
                        if ( preferableTarget == DNN_TARGET_OPENCL )
                            ld.umat_outputBlobs = layers[lpNext.lid].umat_outputBlobs;
                        else
                            ld.outputBlobs = layers[lpNext.lid].outputBlobs;
1219
                        if( bnormData->consumers.size() == 1 )
A
Aleksandr Rybnikov 已提交
1220
                        {
1221
                            nextData = &layers[bnormData->consumers[0].lid];
A
Aleksandr Rybnikov 已提交
1222 1223
                            lpNext = LayerPin(bnormData->consumers[0].lid, 0);
                        }
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
                    }
                }

                Ptr<ScaleLayer> nextScaleLayer;
                if( nextData )
                    nextScaleLayer = nextData->layerInstance.dynamicCast<ScaleLayer>();
                if( !nextScaleLayer.empty() && pinsToKeep.count(lpNext) == 0 )
                {
                    LayerData* scaleData = nextData;
                    nextData = 0;
                    if( currLayer->setScale(nextScaleLayer) )
                    {
                        printf_(("\tfused with %s\n", nextScaleLayer->name.c_str()));
                        scaleData->skipFlags[DNN_BACKEND_DEFAULT] = true;
1238 1239 1240 1241
                        if ( preferableTarget == DNN_TARGET_OPENCL )
                            ld.umat_outputBlobs = layers[lpNext.lid].umat_outputBlobs;
                        else
                            ld.outputBlobs = layers[lpNext.lid].outputBlobs;
1242
                        if( scaleData->consumers.size() == 1 )
A
Aleksandr Rybnikov 已提交
1243
                        {
1244
                            nextData = &layers[scaleData->consumers[0].lid];
A
Aleksandr Rybnikov 已提交
1245 1246
                            lpNext = LayerPin(scaleData->consumers[0].lid, 0);
                        }
1247 1248 1249
                    }
                }

1250
                // For now,  OpenCL target only support fusion with activation of ReLU/ChannelsPReLU/Power
W
Wu Zhiwen 已提交
1251 1252 1253 1254
                if ( preferableTarget != DNN_TARGET_OPENCL ||
                        (preferableTarget == DNN_TARGET_OPENCL &&
                         nextData &&
                        (!nextData->type.compare("ReLU") ||
1255 1256
                         !nextData->type.compare("ChannelsPReLU") ||
                         !nextData->type.compare("Power"))) )
1257
                {
W
Wu Zhiwen 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269

                    Ptr<ActivationLayer> nextActivLayer;

                    if( nextData )
                        nextActivLayer = nextData->layerInstance.dynamicCast<ActivationLayer>();

                    if( !nextActivLayer.empty() && pinsToKeep.count(lpNext) == 0
                            && currLayer->setActivation(nextActivLayer) )
                    {
                        LayerData *activData = nextData;
                        printf_(("\tfused with %s\n", nextActivLayer->name.c_str()));
                        activData->skipFlags[DNN_BACKEND_DEFAULT] = true;
1270 1271 1272 1273
                        if ( preferableTarget == DNN_TARGET_OPENCL )
                            ld.umat_outputBlobs = layers[lpNext.lid].umat_outputBlobs;
                        else
                            ld.outputBlobs = layers[lpNext.lid].outputBlobs;
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 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

                        if ( preferableTarget == DNN_TARGET_OPENCL )
                        {
                            nextData = &layers[activData->consumers[0].lid];
                            lpNext = LayerPin(activData->consumers[0].lid, 0);
                        }
                    }
                }

                // fuse convlution layer followed by eltwise + relu
                if ( preferableTarget == DNN_TARGET_OPENCL )
                {
                    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];
                        while (downLayerData->skipFlags[DNN_BACKEND_DEFAULT])
                        {
                            downLayerData = &layers[downLayerData->inputBlobsId[0].lid];
                        }

                        // 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];
                            while (downLayerData->skipFlags[DNN_BACKEND_DEFAULT])
                            {
                                if ( !downLayerData->type.compare("Eltwise") )
                                    downLayerData = &layers[downLayerData->inputBlobsId[1].lid];
                                else
                                    downLayerData = &layers[downLayerData->inputBlobsId[0].lid];
                            }

                            Ptr<ConvolutionLayer> convLayer;
                            if( downLayerData )
                                convLayer = downLayerData->layerInstance.dynamicCast<ConvolutionLayer>();

                            //  first input layer is convolution layer
                            if( !convLayer.empty() )
                            {
                                // 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) )
                                    {
1335 1336
                                        CV_Assert(firstConvLayerData->umat_outputBlobs.size() == 1 && ld.umat_inputBlobs.size() == 1);
                                        ld.umat_inputBlobs.push_back(firstConvLayerData->umat_outputBlobs[0]);
1337 1338 1339 1340
                                        printf_(("\tfused with %s\n", nextEltwiseLayer->name.c_str()));
                                        printf_(("\tfused with %s\n", nextActivLayer->name.c_str()));
                                        eltwiseData->skipFlags[DNN_BACKEND_DEFAULT] = true;
                                        nextData->skipFlags[DNN_BACKEND_DEFAULT] = true;
1341
                                        ld.umat_outputBlobs = layers[lpNext.lid].umat_outputBlobs;
1342 1343 1344 1345
                                    }
                                }
                            }
                        }
W
Wu Zhiwen 已提交
1346
                    }
1347 1348
                }
            }
1349 1350 1351 1352 1353

            // 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.
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
            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 )
1364
                {
1365
                    poolingLayer->computeMaxIdx = false;
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
                    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
            // the concat layer to write to the concatetion output buffer
            // (and so we eliminate the concatenation layer, because the channels
            // are concatenated implicitly).
            Ptr<ConcatLayer> concatLayer = ld.layerInstance.dynamicCast<ConcatLayer>();
1376
            if( !concatLayer.empty() && concatLayer->axis == 1 && !concatLayer->padding &&
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
                ld.outputBlobs.size() == 1 )
            {
                Mat& output = ld.outputBlobs[0];

                // 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];
                        while(inp_i_data->skipFlags[DNN_BACKEND_DEFAULT] &&
D
Dmitry Kurtaev 已提交
1396 1397
                              inp_i_data->inputBlobsId.size() == 1 &&
                              inp_i_data->consumers.size() == 1)
1398 1399 1400 1401 1402 1403 1404 1405
                        {
                            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()));

1406
                        if(inp_i_data->skipFlags[DNN_BACKEND_DEFAULT] || inp_i_data->consumers.size() != 1)
1407 1408 1409 1410 1411 1412
                            break;
                        realinputs[i] = pin;
                    }

                    if( i >= ninputs )
                    {
1413 1414 1415
                        // Allocate new memory to prevent collisions during memory
                        // reusing (see https://github.com/opencv/opencv/pull/10456).
                        output = output.clone();
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
                        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);
D
Dmitry Kurtaev 已提交
1430
                            Mat* oldPtr = &curr_output;
1431
                            curr_output = output_slice;
D
Dmitry Kurtaev 已提交
1432 1433 1434
                            // Layers that refer old input Mat will refer to the
                            // new data but the same Mat object.
                            CV_Assert(curr_output.data == output_slice.data, oldPtr == &curr_output);
1435 1436 1437 1438
                        }
                        ld.skipFlags[DNN_BACKEND_DEFAULT] = true;
                        printf_(("\toptimized out Concat layer %s\n", concatLayer->name.c_str()));
                    }
1439
                }
1440 1441 1442 1443 1444 1445
            }
        }
    }

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

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
        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++)
        {
            CV_Assert(layers[0].outputBlobs[i].total());
            inputShapes.push_back(shape(layers[0].outputBlobs[i]));
        }
        LayersShapesMap layersShapes;
        getLayersShapes(inputShapes, layersShapes);

        blobManager.reset();
L
Li Peng 已提交
1463 1464
        blobManager.setPreferableTarget(preferableTarget);
        blobManager.setPreferableBackend(preferableBackend);
1465
        backendWrappers.clear();
1466 1467 1468
        // Fake references to input blobs.
        for (int i = 0; i < layers[0].outputBlobs.size(); ++i)
            blobManager.addReference(LayerPin(0, i));
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
        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);
        }

1486
        layersTimings.resize(lastLayerId + 1, 0);
1487 1488 1489 1490 1491
        fuseLayers(blobsToKeep_);
    }

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

1494 1495
        Ptr<Layer> layer = ld.layerInstance;

1496 1497 1498
        TickMeter tm;
        tm.start();

1499 1500 1501 1502
        if (preferableBackend == DNN_BACKEND_DEFAULT ||
            !layer->supportBackend(preferableBackend))
        {
            if( !ld.skipFlags[DNN_BACKEND_DEFAULT] )
1503 1504 1505 1506 1507 1508
            {
                for (int i = 0, n = ld.inputBlobsWrappers.size(); i < n; ++i)
                {
                    if (!ld.inputBlobsWrappers[i].empty())
                        ld.inputBlobsWrappers[i]->copyToHost();
                }
L
Li Peng 已提交
1509 1510 1511 1512
                if (preferableBackend == DNN_BACKEND_DEFAULT && preferableTarget == DNN_TARGET_OPENCL)
                    layer->forward(ld.umat_inputBlobs, ld.umat_outputBlobs, ld.umat_internals);
                else
                    layer->forward(ld.inputBlobs, ld.outputBlobs, ld.internals);
1513 1514 1515 1516 1517 1518
                for (int i = 0, n = ld.outputBlobsWrappers.size(); i < n; ++i)
                {
                    if (!ld.outputBlobsWrappers[i].empty())
                        ld.outputBlobsWrappers[i]->setHostDirty();
                }
            }
1519 1520
            else
                tm.reset();
1521 1522 1523 1524 1525 1526
        }
        else if (!ld.skipFlags[preferableBackend])
        {
            Ptr<BackendNode> node = ld.backendNodes[preferableBackend];
            if (preferableBackend == DNN_BACKEND_HALIDE)
            {
1527
                forwardHalide(ld.outputBlobsWrappers, node);
1528 1529 1530 1531 1532 1533 1534
            }
            else
            {
                CV_Error(Error::StsNotImplemented, "Unknown backend identifier");
            }
        }

1535 1536 1537
        tm.stop();
        layersTimings[ld.id] = tm.getTimeTicks();

1538 1539 1540 1541 1542
        ld.flag = 1;
    }

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

1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
        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;
1558
        for (it = layers.begin(); it != layers.end() && (it->second.id < ld.id); ++it)
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
        {
            LayerData &ld = it->second;
            if (ld.flag)
                continue;
            forwardLayer(ld);
        }

        //forward itself
        forwardLayer(ld);
    }

    void forwardAll()
    {
A
Alexander Alekhin 已提交
1572 1573
        CV_TRACE_FUNCTION();

1574 1575 1576
        MapIdToLayerData::reverse_iterator last_layer = layers.rbegin();
        CV_Assert(last_layer != layers.rend());
        forwardToLayer(last_layer->second, true);
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
    }

    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)
    {
A
Alexander Alekhin 已提交
1637 1638
        CV_TRACE_FUNCTION();

1639 1640 1641 1642 1643 1644 1645 1646 1647
        if (!pin.valid())
            CV_Error(Error::StsObjectNotFound, "Requested blob not found");

        LayerData &ld = layers[pin.lid];
        if ((size_t)pin.oid >= ld.outputBlobs.size())
        {
            CV_Error(Error::StsOutOfRange, "Layer \"" + ld.name + "\" produce only " + toString(ld.outputBlobs.size()) +
                                           " outputs, the #" + toString(pin.oid) + " was requsted");
        }
1648
        if (preferableBackend != DNN_BACKEND_DEFAULT)
1649 1650
        {
            // Transfer data to CPU if it's require.
1651
            ld.outputBlobsWrappers[pin.oid]->copyToHost();
1652 1653 1654
        }
        else
        {
1655
            CV_Assert(preferableTarget == DNN_TARGET_CPU || preferableTarget == DNN_TARGET_OPENCL);
1656
        }
L
Li Peng 已提交
1657 1658 1659 1660

        if (ld.umat_outputBlobs.size() > 0 && !ld.umat_outputBlobs[pin.oid].empty())
            ld.umat_outputBlobs[pin.oid].copyTo(ld.outputBlobs[pin.oid]);

1661 1662 1663
        return ld.outputBlobs[pin.oid];
    }

1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
    void getBlob(UMat& umat, const LayerPin& pin)
    {
        CV_TRACE_FUNCTION();

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

        LayerData &ld = layers[pin.lid];
        if ((size_t)pin.oid >= ld.outputBlobs.size())
        {
            CV_Error(Error::StsOutOfRange, "Layer \"" + ld.name + "\" produce only " + toString(ld.outputBlobs.size()) +
                                           " outputs, the #" + toString(pin.oid) + " was requsted");
        }

        if (ld.umat_outputBlobs.size() > 0 && !ld.umat_outputBlobs[pin.oid].empty())
            umat = ld.umat_outputBlobs[pin.oid];
        else
            umat = UMat();
    }

1684 1685 1686 1687
    Mat getBlob(String outputName)
    {
        return getBlob(getPinByAlias(outputName));
    }
1688 1689 1690 1691 1692

    void getBlob(UMat& umat, String outputName)
    {
        getBlob(umat, getPinByAlias(outputName));
    }
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
};

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

Net::~Net()
{
}

int Net::addLayer(const String &name, const String &type, LayerParams &params)
{
A
Alexander Alekhin 已提交
1705 1706
    CV_TRACE_FUNCTION();

1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
    if (name.find('.') != String::npos)
    {
        CV_Error(Error::StsBadArg, "Added layer name \"" + name + "\" must not contain dot symbol");
        return -1;
    }

    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)
{
A
Alexander Alekhin 已提交
1728 1729
    CV_TRACE_FUNCTION();

1730 1731 1732 1733 1734 1735 1736 1737
    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)
{
A
Alexander Alekhin 已提交
1738 1739
    CV_TRACE_FUNCTION();

1740 1741 1742 1743 1744
    impl->connect(outLayerId, outNum, inpLayerId, inpNum);
}

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

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
    LayerPin outPin = impl->getPinByAlias(_outPin);
    LayerPin inpPin = impl->getPinByAlias(_inPin);

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

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

Mat Net::forward(const String& outputName)
{
A
Alexander Alekhin 已提交
1757 1758
    CV_TRACE_FUNCTION();

1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
    String layerName = outputName;

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

    impl->setUpNet();
    impl->forwardToLayer(impl->getLayerData(layerName));

    return impl->getBlob(layerName);
}

1770
void Net::forward(OutputArrayOfArrays outputBlobs, const String& outputName)
1771
{
A
Alexander Alekhin 已提交
1772 1773
    CV_TRACE_FUNCTION();

1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
    impl->setUpNet();

    String layerName = outputName;

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

    impl->forwardToLayer(impl->getLayerData(layerName));

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

1786
    if (outputBlobs.isUMat())
L
Li Peng 已提交
1787
    {
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
        if (ld.umat_outputBlobs.size() > 0)
        {
            UMat umat;
            impl->getBlob(umat, layerName);
            outputBlobs.assign(umat);
        }
    }
    else if (outputBlobs.isMat())
    {
        outputBlobs.assign(impl->getBlob(layerName));
    }
    else if (outputBlobs.isMatVector())
    {
        if (ld.umat_outputBlobs.size() > 0)
        {
            for (int i = 0; i < ld.umat_outputBlobs.size(); i++)
                ld.umat_outputBlobs[i].copyTo(ld.outputBlobs[i]);
        }
        std::vector<Mat> & outputvec = *(std::vector<Mat> *)outputBlobs.getObj();
        outputvec = ld.outputBlobs;
    }
    else if (outputBlobs.isUMatVector())
    {
        if (ld.umat_outputBlobs.size() > 0)
        {
            std::vector<UMat> & outputvec = *(std::vector<UMat> *)outputBlobs.getObj();
            outputvec = ld.umat_outputBlobs;
        }
L
Li Peng 已提交
1816
    }
1817 1818
}

1819
void Net::forward(OutputArrayOfArrays outputBlobs,
1820 1821
                  const std::vector<String>& outBlobNames)
{
A
Alexander Alekhin 已提交
1822 1823
    CV_TRACE_FUNCTION();

1824 1825 1826
    std::vector<LayerPin> pins;
    for (int i = 0; i < outBlobNames.size(); i++)
    {
1827
        pins.push_back(impl->getPinByAlias(outBlobNames[i]));
1828 1829 1830 1831 1832 1833 1834 1835
    }

    impl->setUpNet(pins);

    LayerPin out = impl->getLatestLayerPin(pins);

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

1836
    std::vector<Mat> matvec;
1837 1838
    for (int i = 0; i < pins.size(); i++)
    {
1839
        matvec.push_back(impl->getBlob(pins[i]));
1840
    }
1841 1842 1843

    std::vector<Mat> & outputvec = *(std::vector<Mat> *)outputBlobs.getObj();
    outputvec = matvec;
1844 1845 1846 1847 1848
}

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

1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
    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)
{
A
Alexander Alekhin 已提交
1877 1878 1879
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG(backendId);

1880 1881 1882
    if( impl->preferableBackend != backendId )
    {
        impl->preferableBackend = backendId;
L
Li Peng 已提交
1883
        impl->blobManager.setPreferableBackend(backendId);
1884 1885 1886
        impl->netWasAllocated = false;
        impl->clear();
    }
1887 1888 1889 1890
}

void Net::setPreferableTarget(int targetId)
{
A
Alexander Alekhin 已提交
1891 1892 1893
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG(targetId);

1894 1895 1896
    if( impl->preferableTarget != targetId )
    {
        impl->preferableTarget = targetId;
L
Li Peng 已提交
1897
        impl->blobManager.setPreferableTarget(targetId);
1898 1899 1900
        impl->netWasAllocated = false;
        impl->clear();
    }
1901 1902 1903 1904
}

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

1907 1908 1909
    impl->netInputLayer->setNames(inputBlobNames);
}

1910
void Net::setInput(InputArray blob, const String& name)
1911
{
A
Alexander Alekhin 已提交
1912 1913 1914
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(name, "name", name.c_str());

1915 1916 1917 1918 1919 1920 1921 1922 1923
    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];
    ld.outputBlobs.resize( std::max(pin.oid+1, (int)ld.requiredOutputs.size()) );
L
Li Peng 已提交
1924 1925 1926 1927
    bool use_umat = (impl->preferableBackend == DNN_BACKEND_DEFAULT &&
                     impl->preferableTarget == DNN_TARGET_OPENCL);
    if (use_umat)
        ld.umat_outputBlobs.resize( std::max(pin.oid+1, (int)ld.requiredOutputs.size()) );
1928
    ld.outputBlobsWrappers.resize(ld.outputBlobs.size());
1929
    MatShape prevShape = shape(ld.outputBlobs[pin.oid]);
1930
    Mat blob_ = blob.getMat();
1931 1932
    bool oldShape = prevShape == shape(blob_);
    if (oldShape)
L
Li Peng 已提交
1933
    {
1934
        blob_.copyTo(ld.outputBlobs[pin.oid]);
L
Li Peng 已提交
1935 1936 1937
        if (use_umat)
            blob_.copyTo(ld.umat_outputBlobs[pin.oid]);
    }
1938
    else
L
Li Peng 已提交
1939
    {
1940
        ld.outputBlobs[pin.oid] = blob_.clone();
L
Li Peng 已提交
1941 1942 1943
        if (use_umat)
            blob_.copyTo(ld.umat_outputBlobs[pin.oid]);
    }
1944

1945 1946 1947 1948
    if (!ld.outputBlobsWrappers[pin.oid].empty())
    {
        ld.outputBlobsWrappers[pin.oid]->setHostDirty();
    }
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
    impl->netWasAllocated = impl->netWasAllocated && oldShape;
}

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

    std::vector<Mat> &layerBlobs = ld.layerInstance->blobs;
    CV_Assert(numParam < (int)layerBlobs.size());
    return layerBlobs[numParam];
}

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

    std::vector<Mat> &layerBlobs = ld.layerInstance->blobs;
    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);
}

void Net::deleteLayer(LayerId)
{
    CV_Error(Error::StsNotImplemented, "");
}

Ptr<Layer> Net::getLayer(LayerId layerId)
{
    LayerData &ld = impl->getLayerData(layerId);
A
abratchik 已提交
1984
    return ld.getLayerInstance();
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
}

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

void Net::getLayersShapes(const ShapesVec& netInputShapes,
2040 2041 2042
                          std::vector<int>& layersIds,
                          std::vector<ShapesVec>& inLayersShapes,
                          std::vector<ShapesVec>& outLayersShapes) const
2043
{
2044 2045 2046
    layersIds.clear();
    inLayersShapes.clear();
    outLayersShapes.clear();
2047 2048 2049 2050 2051 2052 2053

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

    for(Impl::LayersShapesMap::const_iterator it = inOutShapes.begin();
        it != inOutShapes.end(); it++)
    {
2054 2055 2056
        layersIds.push_back(it->first);
        inLayersShapes.push_back(it->second.in);
        outLayersShapes.push_back(it->second.out);
2057 2058 2059 2060
    }
}

void Net::getLayersShapes(const MatShape& netInputShape,
2061 2062 2063
                          std::vector<int>& layerIds,
                          std::vector<ShapesVec>& inLayersShapes,
                          std::vector<ShapesVec>& outLayersShapes) const
2064 2065 2066 2067 2068 2069 2070
{
    getLayersShapes(ShapesVec(1, netInputShape),
                    layerIds, inLayersShapes, outLayersShapes);
}

void Net::getLayerShapes(const MatShape& netInputShape,
                         const int layerId,
2071 2072
                         ShapesVec& inLayerShapes,
                         ShapesVec& outLayerShapes) const
2073 2074 2075 2076 2077 2078 2079 2080
{
    getLayerShapes(ShapesVec(1, netInputShape),
                   layerId, inLayerShapes, outLayerShapes);

}

void Net::getLayerShapes(const ShapesVec& netInputShapes,
                    const int layerId,
2081 2082
                    ShapesVec& inLayerShapes,
                    ShapesVec& outLayerShapes) const
2083 2084 2085
{
    LayerShapes shapes;
    impl->getLayerShapes(netInputShapes, layerId, shapes);
2086 2087
    inLayerShapes = shapes.in;
    outLayerShapes = shapes.out;
2088 2089 2090 2091
}

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

2094 2095 2096
    int64 flops = 0;
    std::vector<int> ids;
    std::vector<std::vector<MatShape> > inShapes, outShapes;
2097
    getLayersShapes(netInputShapes, ids, inShapes, outShapes);
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
    CV_Assert(inShapes.size() == outShapes.size());
    CV_Assert(inShapes.size() == ids.size());

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

    return flops;
}

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

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

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

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

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

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

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

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

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

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

2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
    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();
    }

2182 2183
    ShapesVec inLayerShapes, outLayerShapes;
    getLayerShapes(netInputShapes, layerId, inLayerShapes, outLayerShapes);
2184 2185 2186 2187 2188 2189 2190 2191 2192
    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
{
A
Alexander Alekhin 已提交
2193 2194
    CV_TRACE_FUNCTION();

2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
    std::vector<int> layerIds;
    std::vector<size_t> w, b;
    getMemoryConsumption(netInputShapes, layerIds, w, b);

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

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

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

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

2228 2229 2230 2231
    layerIds.clear();
    weights.clear();
    blobs.clear();

2232
    std::vector<std::vector<MatShape> > inLayerShapes, outLayerShapes;
2233

2234
    getLayersShapes(netInputShapes, layerIds, inLayerShapes, outLayerShapes);
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

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

2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
void Net::enableFusion(bool fusion)
{
    if( impl->fusion != fusion )
    {
        impl->fusion = fusion;
        impl->netWasAllocated = false;
        impl->clear();
    }
}

2275 2276
void Net::setHalideScheduler(const String& scheduler)
{
A
Alexander Alekhin 已提交
2277 2278 2279
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(scheduler, "scheduler", scheduler.c_str());

2280 2281 2282
    impl->halideConfigFile = scheduler;
}

2283 2284 2285 2286 2287 2288 2289
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;
}

2290 2291
//////////////////////////////////////////////////////////////////////////

2292
Layer::Layer() { preferableTarget = DNN_TARGET_CPU; }
2293 2294 2295 2296

Layer::Layer(const LayerParams &params)
    : blobs(params.blobs), name(params.name), type(params.type)
{
2297
    preferableTarget = DNN_TARGET_CPU;
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
}

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

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

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

bool Layer::supportBackend(int backendId)
{
    return backendId == DNN_BACKEND_DEFAULT;
}

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

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

2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
    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)
    {
        int c_split = outC > 8 ? (outC > 16 ? 8 : 4) : outC;
        if (outW == 1 && outH == 1)
        {
            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;
            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>();
}

2403 2404
bool Layer::setActivation(const Ptr<ActivationLayer>&) { return false; }
bool Layer::setBatchNorm(const Ptr<BatchNormLayer>&) { return false; }
2405 2406 2407 2408 2409 2410 2411
bool Layer::setScale(const Ptr<ScaleLayer>&) { return false; }
void Layer::unsetAttached()
{
    setActivation(Ptr<ActivationLayer>());
    setBatchNorm(Ptr<BatchNormLayer>());
    setScale(Ptr<ScaleLayer>());
}
2412

2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
template <typename T>
static void vecToPVec(const std::vector<T> &v, std::vector<T*> &pv)
{
    pv.resize(v.size());
    for (size_t i = 0; i < v.size(); i++)
        pv[i] = const_cast<T*>(&v[i]);
}

void Layer::finalize(const std::vector<Mat> &inputs, std::vector<Mat> &outputs)
{
A
Alexander Alekhin 已提交
2423 2424
    CV_TRACE_FUNCTION();

2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
    std::vector<Mat*> inputsp;
    vecToPVec(inputs, inputsp);
    this->finalize(inputsp, outputs);
}

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

std::vector<Mat> Layer::finalize(const std::vector<Mat> &inputs)
{
A
Alexander Alekhin 已提交
2437 2438
    CV_TRACE_FUNCTION();

2439 2440 2441 2442 2443
    std::vector<Mat> outputs;
    this->finalize(inputs, outputs);
    return outputs;
}

L
Li Peng 已提交
2444
void Layer::forward_fallback(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr)
2445
{
A
Alexander Alekhin 已提交
2446
    CV_TRACE_FUNCTION();
L
Li Peng 已提交
2447
    CV_TRACE_ARG_VALUE(name, "name", name.c_str());
A
Alexander Alekhin 已提交
2448

L
Li Peng 已提交
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
    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);
2462 2463 2464 2465

    // sync results back
    outputs_arr.assign(outputs);
    internals_arr.assign(internals);
2466 2467 2468 2469
}

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

2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
    std::vector<Mat*> inputsp;
    vecToPVec(inputs, inputsp);
    this->finalize(inputsp, outputs);
    this->forward(inputsp, outputs, internals);
}

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

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

2492
static Mutex& getLayerFactoryMutex()
2493
{
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510
    static Mutex* volatile instance = NULL;
    if (instance == NULL)
    {
        cv::AutoLock lock(getInitializationMutex());
        if (instance == NULL)
            instance = new Mutex();
    }
    return *instance;
}

typedef std::map<String, LayerFactory::Constuctor> LayerFactory_Impl;

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

2512
static LayerFactory_Impl& getLayerFactoryImpl()
2513
{
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
    static LayerFactory_Impl* volatile instance = NULL;
    if (instance == NULL)
    {
        cv::AutoLock lock(getLayerFactoryMutex());
        if (instance == NULL)
        {
            instance = &getLayerFactoryImpl_();
            initializeLayerFactory();
        }
    }
    return *instance;
2525 2526
}

A
Alexander Alekhin 已提交
2527
void LayerFactory::registerLayer(const String &type, Constuctor constructor)
2528
{
A
Alexander Alekhin 已提交
2529 2530 2531
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

2532
    cv::AutoLock lock(getLayerFactoryMutex());
A
Alexander Alekhin 已提交
2533 2534
    String type_ = type.toLowerCase();
    LayerFactory_Impl::const_iterator it = getLayerFactoryImpl().find(type_);
2535

2536
    if (it != getLayerFactoryImpl().end() && it->second != constructor)
2537
    {
A
Alexander Alekhin 已提交
2538
        CV_Error(cv::Error::StsBadArg, "Layer \"" + type_ + "\" already was registered");
2539 2540
    }

A
Alexander Alekhin 已提交
2541
    getLayerFactoryImpl().insert(std::make_pair(type_, constructor));
2542 2543
}

A
Alexander Alekhin 已提交
2544
void LayerFactory::unregisterLayer(const String &type)
2545
{
A
Alexander Alekhin 已提交
2546 2547 2548
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

2549
    cv::AutoLock lock(getLayerFactoryMutex());
A
Alexander Alekhin 已提交
2550 2551
    String type_ = type.toLowerCase();
    getLayerFactoryImpl().erase(type_);
2552 2553
}

A
Alexander Alekhin 已提交
2554
Ptr<Layer> LayerFactory::createLayerInstance(const String &type, LayerParams& params)
2555
{
A
Alexander Alekhin 已提交
2556 2557 2558
    CV_TRACE_FUNCTION();
    CV_TRACE_ARG_VALUE(type, "type", type.c_str());

2559
    cv::AutoLock lock(getLayerFactoryMutex());
A
Alexander Alekhin 已提交
2560 2561
    String type_ = type.toLowerCase();
    LayerFactory_Impl::const_iterator it = getLayerFactoryImpl().find(type_);
2562

2563
    if (it != getLayerFactoryImpl().end())
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
    {
        return it->second(params);
    }
    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() {}

2594 2595
CV__DNN_EXPERIMENTAL_NS_END
}} // namespace