torch_importer.cpp 35.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/*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 <limits>
#include <set>
#include <map>
#include <algorithm>
#include <iostream>
arrybn's avatar
arrybn committed
48
#include <fstream>
49 50 51

namespace cv {
namespace dnn {
52
#if defined(ENABLE_TORCH_IMPORTER) && ENABLE_TORCH_IMPORTER
53 54
#include "THDiskFile.h"

55
//#ifdef NDEBUG
56
static bool dbgPrint = false;
57 58 59
//#else
//static bool dbgPrint = true;
//#endif
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 87 88 89 90 91 92 93
enum LuaType
{
    TYPE_NIL      = 0,
    TYPE_NUMBER   = 1,
    TYPE_STRING   = 2,
    TYPE_TABLE    = 3,
    TYPE_TORCH    = 4,
    TYPE_BOOLEAN  = 5,
    TYPE_FUNCTION = 6,
    TYPE_RECUR_FUNCTION = 8,
    LEGACY_TYPE_RECUR_FUNCTION = 7
};

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

static inline bool startsWith(const String &str, const char *substr)
{
    return str.find(substr) == 0;
}

static inline bool endsWith(const String &str, const char *substr)
{
    return str.rfind(substr) == str.length() - strlen(substr);
}

struct TorchImporter : public ::cv::dnn::Importer
{
94
    typedef std::map<String, std::pair<int, Mat> > TensorsMap;
95 96 97 98 99
    Net net;

    THFile *file;
    std::set<int> readedIndexes;
    std::map<int, Mat> storages;
100
    std::map<int, Mat> tensors;
101 102 103 104 105

    struct Module
    {
        String thName, apiType;
        dnn::LayerParams params;
arrybn's avatar
arrybn committed
106
        std::vector<cv::Ptr<Module> > modules;
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 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

        Module(const String &_thName, const String &_apiType = String())
            : thName(_thName), apiType(_apiType) {}
    };

    Module *rootModule;
    Module *curModule;
    int moduleCounter;

    TorchImporter(String filename, bool isBinary)
    {
        rootModule = curModule = NULL;
        moduleCounter = 0;

        file = THDiskFile_new(filename.c_str(), "r", 0);
        CV_Assert(file && THFile_isOpened(file));

        if (isBinary)
            THFile_binary(file);
        else
            THFile_ascii(file);
    }

    /* Simple readers */

    inline int readInt()
    {
        return THFile_readIntScalar(file);
    }

    inline long readLong()
    {
        return THFile_readLongScalar(file);
    }

    inline bool readBool()
    {
        return readInt() != 0;
    }

    inline double readDouble()
    {
        return THFile_readDoubleScalar(file);
    }

    inline String readString()
    {
        int size = THFile_readIntScalar(file);
        String str(size, '\0');
        THFile_readCharRaw(file, const_cast<char*>(str.c_str()), size);
        return str;
    }

    inline String readTorchClassName()
    {
        String version = readString();
        return startsWith(version, "V ") ? readString() : version;
    }

    inline void readFunction()
    {
        readString();
        readObject();
    }

    void readTable(int index = -1)
    {
        index = (index < 0) ? readInt() : index;

        if (readedIndexes.count(index))
            return;

        readedIndexes.insert(index);

        int size = readInt();
arrybn's avatar
arrybn committed
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        for (int i = 0; i < size; i++)
        {
            readObject(); //key
            readObject(); //value
        }
    }

    /* Special readers */

    static inline int parseTorchType(const String &str, const char *suffix, const char *prefix = "torch.")
    {
        if (startsWith(str, prefix) && endsWith(str, suffix))
        {
           String typeStr = str.substr(strlen(prefix), str.length() - strlen(prefix) - strlen(suffix));

           if (typeStr == "Double")
               return CV_64F;
200
           else if (typeStr == "Float" || typeStr == "Cuda")
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
               return CV_32F;
           else if (typeStr == "Byte")
               return CV_8U;
           else if (typeStr == "Char")
               return CV_8S;
           else if (typeStr == "Short")
               return CV_16S;
           else if (typeStr == "Int")
               return CV_32S;
           else if (typeStr == "Long") //Carefully! CV_64S type coded as CV_USRTYPE1
               return CV_USRTYPE1;
           else
               CV_Error(Error::StsNotImplemented, "Unknown type \"" + typeStr + "\" of torch class \"" + str + "\"");
        }

        return -1;
    }

    static int parseTensorType(const String &className)
    {
        return parseTorchType(className, "Tensor");
    }

    static int parseStorageType(const String &className)
    {
        return parseTorchType(className, "Storage");
    }

    void readTorchStorage(int index, int type = -1)
    {
        long size = readLong();
        Mat storageMat(1, size, (type != CV_USRTYPE1) ? type : CV_64F); //handle LongStorage as CV_64F Mat

        switch (type)
        {
        case CV_32F:
            THFile_readFloatRaw(file, (float*)storageMat.data, size);
            break;
        case CV_64F:
            THFile_readDoubleRaw(file, (double*)storageMat.data, size);
            break;
        case CV_8S:
        case CV_8U:
            THFile_readByteRaw(file, (uchar*)storageMat.data, size);
            break;
        case CV_16S:
        case CV_16U:
            THFile_readShortRaw(file, (short*)storageMat.data, size);
            break;
        case CV_32S:
            THFile_readIntRaw(file, (int*)storageMat.data, size);
            break;
        case CV_USRTYPE1:
        {
            double *buf = storageMat.ptr<double>();
256
            THFile_readLongRaw(file, (int64*)buf, size);
257 258

            for (size_t i = (size_t)size; i-- > 0; )
259
                buf[i] = ((int64*)buf)[i];
260 261 262 263 264 265 266 267 268 269
        }
            break;
        default:
            CV_Error(Error::StsInternal, "");
            break;
        }

        storages.insert(std::make_pair(index, storageMat));
    }

arrybn's avatar
arrybn committed
270
    void readTorchTable(Dict &scalarParams, TensorsMap &tensorParams)
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    {
        int luaType = readInt();
        int index = readInt();

        CV_Assert(luaType == TYPE_TABLE && readedIndexes.count(index) == 0);
        readedIndexes.insert(index);

        long fpos;
        int numPairs = readInt();

        for (int i = 0; i < numPairs; i++)
        {
            fpos = THFile_position(file);
            int ktype = readInt();

            if (ktype != TYPE_STRING) //skip non-string fileds
            {
                THFile_seek(file, fpos);
                readObject(); //key
                readObject(); //value
                continue;
            }

            String key = readString();
295 296
            if (dbgPrint)
                std::cout << i << "th key: " << key << "\n";
297 298 299 300 301 302 303 304 305 306 307

            fpos = THFile_position(file);
            int vtype = readInt();

            if (vtype == TYPE_TORCH)
            {
                int index = readInt();
                readTorchObject(index);

                if (tensors.count(index)) //tensor was readed
                {
arrybn's avatar
arrybn committed
308
                    tensorParams.insert(std::make_pair(key, std::make_pair(index, tensors[index])));
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
                }
                else if (storages.count(index)) //storage was readed
                {
                    Mat &matStorage = storages[index];
                    Mat matCasted;
                    matStorage.convertTo(matCasted, CV_64F);

                    DictValue scalar = DictValue::arrayReal(matCasted.ptr<double>(), matCasted.total());
                    scalarParams.set(key, scalar);
                }
            }
            else if (vtype == TYPE_NUMBER)
            {
                scalarParams.set(key, readDouble());
            }
            else if (vtype == TYPE_STRING)
            {
                scalarParams.set(key, readString());
            }
            else if (vtype == TYPE_BOOLEAN)
            {
                scalarParams.set(key, readBool());
            }
            else
            {
                THFile_seek(file, fpos);
                readObject();
            }
        }

        //Debug output
340 341 342 343
        if (dbgPrint)
        {
            std::cout << "scalarParams:\n";
            std::cout << scalarParams;
344

345
            std::cout << "#" << tensorParams.size() << " tensorParams:\n";
346
            std::map<String,std::pair<int, Mat> >::const_iterator it;
347
            for (it = tensorParams.begin(); it != tensorParams.end(); it++)
348
                std::cout << it->first << ": Tensor " << it->second.second.size << "\n";
349
        }
350 351 352 353 354
    }

    void readTorchTensor(int indexTensor, int typeTensor)
    {
        int ndims = readInt();
355 356
        AutoBuffer<int64, 4> sizes(ndims);
        AutoBuffer<int64, 4> steps(ndims);
357 358 359 360 361 362 363 364 365 366
        THFile_readLongRaw(file, sizes, ndims);
        THFile_readLongRaw(file, steps, ndims);
        long offset = readLong() - 1;

        //read Storage
        int typeidx = readInt();
        CV_Assert(typeidx == TYPE_TORCH || (typeidx == TYPE_NIL && ndims == 0));

        if (typeidx == TYPE_NIL)
        {
367
            tensors.insert(std::make_pair(indexTensor, Mat()));
368 369 370 371 372 373
            return;
        }

        int indexStorage = readInt();
        if (readedIndexes.count(indexStorage) == 0)
        {
arrybn's avatar
arrybn committed
374 375
            String className = readTorchClassName();
            int typeStorage = parseStorageType(className);
376 377
            CV_Assert(typeStorage >= 0 && typeTensor == typeStorage);
            readTorchStorage(indexStorage, typeStorage);
378
            typeTensor = storages[indexStorage].type();
arrybn's avatar
arrybn committed
379
            readedIndexes.insert(indexStorage);
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
        }

        //small check
        size_t requireElems = (size_t)offset + (size_t)steps[0] * (size_t)sizes[0];
        size_t storageElems = storages[indexStorage].total();
        if (requireElems > storageElems)
            CV_Error(Error::StsBadSize, "Storage has insufficent number of elemements for requested Tensor");

        //convert sizes
        AutoBuffer<int, 4> isizes(ndims);
        AutoBuffer<size_t, 4> ssteps(ndims);
        for (int i = ndims - 1; i >= 0; i--)
        {
            isizes[i] = (int)sizes[i];
            ssteps[i] = (size_t)steps[i] * CV_ELEM_SIZE(typeTensor);
        }

        //allocate Blob
arrybn's avatar
arrybn committed
398
        Mat srcMat(ndims, (int*)isizes, typeTensor , storages[indexStorage].ptr() + offset*CV_ELEM_SIZE(typeTensor), (size_t*)ssteps);
399 400
        int dstType = CV_32F;

401 402
        Mat blob;
        srcMat.convertTo(blob, dstType);
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

        tensors.insert(std::make_pair(indexTensor, blob));
    }

    static bool isNNClass(const String &className, String &nnName)
    {
        const char *prefixes[] = {"nn.", "cunn.", "cudnn.", "fbcunn.", NULL};

        for (int i = 0; prefixes[i]; i++)
        {
            if (startsWith(className, prefixes[i]))
            {
                nnName = className.substr(strlen(prefixes[i]));
                return true;
            }
        }

        return false;
    }

    static void convertTorchKernelsParams(const Dict &torchParams, cv::dnn::LayerParams &layerParams)
    {
        layerParams.set("kernel_h", torchParams.get<int>("kH"));
        layerParams.set("kernel_w", torchParams.get<int>("kW"));
        layerParams.set("stride_h", torchParams.get<int>("dH"));
        layerParams.set("stride_w", torchParams.get<int>("dW"));
        layerParams.set("pad_h", torchParams.get<int>("padH", 0));
        layerParams.set("pad_w", torchParams.get<int>("padW", 0));
    }

    void readTorchObject(int index)
    {
        if(readedIndexes.count(index))
arrybn's avatar
arrybn committed
436
            return;
437 438 439

        String className = readTorchClassName();
        String nnName;
440 441 442

        if (dbgPrint)
            std::cout << "Class: " << className << std::endl;
443 444 445 446 447 448 449 450 451 452 453 454 455

        int type;
        if ( (type = parseTensorType(className)) >= 0 ) //is Tensor
        {
            readTorchTensor(index, type);
        }
        else if ( (type = parseStorageType(className)) >= 0 ) //is Storage
        {
            readTorchStorage(index, type);
        }
        else if (isNNClass(className, nnName))
        {
            Dict scalarParams;
arrybn's avatar
arrybn committed
456
            TensorsMap tensorParams;
457

arrybn's avatar
arrybn committed
458
            cv::Ptr<Module> newModule(new Module(nnName));
459 460
            cv::dnn::LayerParams &layerParams = newModule->params;

arrybn's avatar
arrybn committed
461 462 463 464
            layerParams.set("torch_index", index);

            if (nnName == "Sequential" || nnName == "Parallel" ||
                    nnName == "Concat" || nnName == "ConcatTable" || nnName == "JoinTable")
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
            {
                Module *parentModule = curModule;
                curModule->modules.push_back(newModule);
                curModule = newModule;
                readTorchTable(scalarParams, tensorParams);
                curModule = parentModule;

                if (nnName == "Parallel")
                {
                    layerParams.set("inputDimension", scalarParams.get<int>("inputDimension"));
                    layerParams.set("outputDimension", scalarParams.get<int>("outputDimension"));
                }
                if (nnName == "Concat")
                {
                    layerParams.set("dimension", scalarParams.get<int>("dimension"));
                }
arrybn's avatar
arrybn committed
481 482 483 484
                if (nnName == "JoinTable")
                {
                    layerParams.set("dimension", scalarParams.get<int>("dimension"));
                }
485 486 487 488 489 490 491
            }
            else if (nnName == "SpatialConvolution")
            {
                newModule->apiType = "Convolution";
                readTorchTable(scalarParams, tensorParams);

                CV_Assert(tensorParams.count("weight"));
arrybn's avatar
arrybn committed
492
                layerParams.blobs.push_back(tensorParams["weight"].second);
493 494 495 496

                bool bias = tensorParams.count("bias") != 0;
                layerParams.set("bias_term", bias);
                if (bias)
arrybn's avatar
arrybn committed
497
                    layerParams.blobs.push_back(tensorParams["bias"].second);
498 499 500 501 502 503 504 505 506 507 508

                layerParams.set("num_output", scalarParams.get<int>("nOutputPlane"));
                convertTorchKernelsParams(scalarParams, layerParams);

                curModule->modules.push_back(newModule);
            }
            else if (nnName == "SpatialMaxPooling" || nnName == "SpatialAveragePooling")
            {
                newModule->apiType = "Pooling";
                readTorchTable(scalarParams, tensorParams);

arrybn's avatar
arrybn committed
509
                if (nnName == "SpatialMaxPooling") {
510
                    layerParams.set("pool", "MAX");
arrybn's avatar
arrybn committed
511 512
                    layerParams.set("indices_blob_id", tensorParams["indices"].first);
                }
513 514 515 516 517 518 519 520 521 522 523 524
                if (nnName == "SpatialAveragePooling")
                    layerParams.set("pool", "AVE");
                convertTorchKernelsParams(scalarParams, layerParams);

                curModule->modules.push_back(newModule);
            }
            else if (nnName == "Linear")
            {
                newModule->apiType = "InnerProduct";
                readTorchTable(scalarParams, tensorParams);

                CV_Assert(tensorParams.count("weight"));
525
                Mat weightBlob = tensorParams["weight"].second;
526 527 528 529
                layerParams.blobs.push_back(weightBlob);

                bool bias = tensorParams.count("bias") != 0;
                if (bias)
arrybn's avatar
arrybn committed
530
                    layerParams.blobs.push_back(tensorParams["bias"].second);
531 532
                layerParams.set("bias_term", bias);

533
                layerParams.set("num_output", weightBlob.size[0]);
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
                curModule->modules.push_back(newModule);
            }
            else if (nnName == "Reshape")
            {
                newModule->apiType = "Reshape";

                readTorchTable(scalarParams, tensorParams);
                CV_Assert(scalarParams.has("size"));

                DictValue dimParam = scalarParams.get("size");
                layerParams.set("dim", dimParam);

                if (scalarParams.has("batchMode") && scalarParams.get<bool>("batchMode"))
                    layerParams.set("axis", 1);

                curModule->modules.push_back(newModule);
            }
            else if (nnName == "ReLU")
            {
arrybn's avatar
arrybn committed
553
                curModule->modules.push_back(cv::Ptr<Module>(new Module(nnName, "ReLU")));
554 555 556 557
                readObject();
            }
            else if (nnName == "Tanh")
            {
arrybn's avatar
arrybn committed
558
                curModule->modules.push_back(cv::Ptr<Module>(new Module(nnName, "TanH")));
559 560 561 562
                readObject();
            }
            else if (nnName == "Sigmoid")
            {
arrybn's avatar
arrybn committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576
                curModule->modules.push_back(cv::Ptr<Module>(new Module(nnName, "Sigmoid")));
                readObject();
            }
            else if (nnName == "SpatialBatchNormalization")
            {
                newModule->apiType = "BatchNorm";
                readTorchTable(scalarParams, tensorParams);

                CV_Assert(tensorParams.count("running_var") &&
                          tensorParams.count("running_mean"));
                layerParams.blobs.push_back(tensorParams["running_mean"].second);
                layerParams.blobs.push_back(tensorParams["running_var"].second);

                CV_Assert(scalarParams.has("eps"));
577 578
                float eps = float(scalarParams.get<double>("eps"));
                layerParams.set("eps", eps);
arrybn's avatar
arrybn committed
579 580 581 582

                if (tensorParams.count("weight"))
                {
                    layerParams.set("has_weight", true);
583
                    layerParams.blobs.push_back(tensorParams["weight"].second);
arrybn's avatar
arrybn committed
584 585 586 587 588
                }

                if (tensorParams.count("bias"))
                {
                    layerParams.set("has_bias", true);
589
                    layerParams.blobs.push_back(tensorParams["bias"].second);
arrybn's avatar
arrybn committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
                }

                curModule->modules.push_back(newModule);
            }
            else if (nnName == "PReLU")
            {
                readTorchTable(scalarParams, tensorParams);

                CV_Assert(tensorParams.count("weight"));

                size_t outputChannels = static_cast<int>(scalarParams.get<double>("nOutputPlane"));
                if (outputChannels) {

                    CV_Assert(tensorParams["weight"].second.total() == outputChannels);
                    layerParams.blobs.push_back(tensorParams["weight"].second);

                    newModule->apiType = "ChannelsPReLU";
                }
                else {
                    CV_Assert(tensorParams["weight"].second.total() == 1);
610
                    float negative_slope = *tensorParams["weight"].second.ptr<float>();
arrybn's avatar
arrybn committed
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
                    layerParams.set("negative_slope", negative_slope);

                    newModule->apiType = "ReLU";
                }

                curModule->modules.push_back(newModule);
            }
            else if (nnName == "SpatialDropout")
            {
                readTorchTable(scalarParams, tensorParams);
                CV_Assert(scalarParams.has("p"));

                float scale = 1 -  scalarParams.get<double>("p");

                CV_Assert(scale > 0);

                newModule->apiType = "Power";
                layerParams.set("scale", scale);
                curModule->modules.push_back(newModule);
            }
            else if (nnName == "Identity")
            {
                readTorchTable(scalarParams, tensorParams);
                newModule->apiType = "Identity";
                curModule->modules.push_back(newModule);
            }
            else if (nnName == "Padding")
            {
                readTorchTable(scalarParams, tensorParams);
                newModule->apiType = "Padding";

                CV_Assert(scalarParams.has("pad") &&
                          scalarParams.has("dim"));

                layerParams.set("padding_dim",
                                static_cast<int>(scalarParams.get<double>("dim") - 1));
                layerParams.set("padding", static_cast<int>(scalarParams.get<double>("pad")));

                if (scalarParams.has("nInputDim"))
                    layerParams.set("input_dims",
                                    static_cast<int>(scalarParams.get<double>("nInputDim")));

                if (scalarParams.has("value"))
                    layerParams.set("value", scalarParams.get<double>("value"));

                if (scalarParams.has("index"))
                    layerParams.set("index",
                                    static_cast<int>(scalarParams.get<double>("index") - 1));

                curModule->modules.push_back(newModule);
            }
            else if (nnName == "CAddTable")
            {
                curModule->modules.push_back(newModule);
665 666
                readObject();
            }
arrybn's avatar
arrybn committed
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
            else if (nnName == "SpatialDilatedConvolution")
            {
                readTorchTable(scalarParams, tensorParams);
                newModule->apiType = "Convolution";
                CV_Assert(scalarParams.has("padW") &&
                          scalarParams.has("padH")&&
                          scalarParams.has("dW")&&
                          scalarParams.has("dH")&&
                          scalarParams.has("dilationW")&&
                          scalarParams.has("dilationH")&&
                          scalarParams.has("kW")&&
                          scalarParams.has("kH")&&
                          scalarParams.has("nOutputPlane"));

                layerParams.set("kernel_w", static_cast<int>(scalarParams.get<double>("kW")));
                layerParams.set("kernel_h", static_cast<int>(scalarParams.get<double>("kH")));
                layerParams.set("pad_w", static_cast<int>(scalarParams.get<double>("padW")));
                layerParams.set("pad_h", static_cast<int>(scalarParams.get<double>("padH")));
                layerParams.set("stride_w", static_cast<int>(scalarParams.get<double>("dW")));
                layerParams.set("stride_h", static_cast<int>(scalarParams.get<double>("dH")));
                layerParams.set("dilation_w", static_cast<int>(scalarParams.get<double>("dilationW")));
                layerParams.set("dilation_h", static_cast<int>(scalarParams.get<double>("dilationH")));
                layerParams.set("num_output", static_cast<int>(scalarParams.get<double>("nOutputPlane")));

                layerParams.blobs.push_back(tensorParams["weight"].second);

                bool bias = tensorParams.count("bias");
                layerParams.set("bias_term", bias);
                if (bias)
                    layerParams.blobs.push_back(tensorParams["bias"].second);

                curModule->modules.push_back(newModule);
            }
            else if (nnName == "SpatialFullConvolution")
            {
                readTorchTable(scalarParams, tensorParams);
                newModule->apiType = "Deconvolution";
                CV_Assert(scalarParams.has("padW") &&
                          scalarParams.has("padH")&&
                          scalarParams.has("dW")&&
                          scalarParams.has("dH")&&
                          scalarParams.has("adjW")&&
                          scalarParams.has("adjH")&&
                          scalarParams.has("kW")&&
                          scalarParams.has("kH")&&
                          scalarParams.has("nOutputPlane"));

                layerParams.set("kernel_w", static_cast<int>(scalarParams.get<double>("kW")));
                layerParams.set("kernel_h", static_cast<int>(scalarParams.get<double>("kH")));
                layerParams.set("pad_w", static_cast<int>(scalarParams.get<double>("padW")));
                layerParams.set("pad_h", static_cast<int>(scalarParams.get<double>("padH")));
                layerParams.set("stride_w", static_cast<int>(scalarParams.get<double>("dW")));
                layerParams.set("stride_h", static_cast<int>(scalarParams.get<double>("dH")));
                layerParams.set("adj_w", static_cast<int>(scalarParams.get<double>("adjW")));
                layerParams.set("adj_h", static_cast<int>(scalarParams.get<double>("adjH")));
                layerParams.set("num_output", static_cast<int>(scalarParams.get<double>("nOutputPlane")));

724 725 726 727
                Mat weights = tensorParams["weight"].second;
                CV_Assert(weights.dims == 4);
                int reorderedShape[] = { weights.size[1], weights.size[0], weights.size[2], weights.size[3] };
                layerParams.blobs.push_back(weights.reshape(1, 4, reorderedShape));
arrybn's avatar
arrybn committed
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

                bool bias = tensorParams.count("bias");
                layerParams.set("bias_term", bias);
                if (bias)
                    layerParams.blobs.push_back(tensorParams["bias"].second);

                curModule->modules.push_back(newModule);
            }
            else if (nnName == "SpatialMaxUnpooling")
            {
                readTorchTable(scalarParams, tensorParams);
                CV_Assert(tensorParams.count("indices"));

                layerParams.set("indices_blob_id", tensorParams["indices"].first);
                curModule->modules.push_back(newModule);
            }
744 745 746 747 748 749 750 751 752 753 754
            else if (nnName == "SoftMax")
            {
                newModule->apiType = "SoftMax";
                curModule->modules.push_back(newModule);
            }
            else if (nnName == "LogSoftMax")
            {
                newModule->apiType = "SoftMax";
                layerParams.set("log_softmax", true);
                curModule->modules.push_back(newModule);
            }
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
            else
            {
                CV_Error(Error::StsNotImplemented, "Unknown nn class \"" + className + "\"");
            }
        }
        else
        {
            CV_Error(Error::StsNotImplemented, "Unsupported Torch class \"" + className + "\"");
        }

        readedIndexes.insert(index);
    }

    void readObject()
    {
        int typeidx = readInt();

        if (typeidx == TYPE_TORCH)
        {
            int index = readInt();
            readTorchObject(index);
            readedIndexes.insert(index);
        }
        else if (typeidx == TYPE_NIL)
            return;
        else if (typeidx == TYPE_NUMBER)
            readDouble();
        else if (typeidx == TYPE_BOOLEAN)
            readBool();
        else if (typeidx == TYPE_STRING)
            readString();
        else if (typeidx == TYPE_TABLE)
            readTable();
        else
            CV_Error(Error::StsNotImplemented, "Unsupported Lua type");
    }

    inline String generateLayerName(const String &label = String())
    {
        return "l" + toString(++this->moduleCounter) + "_" + label;
    }

arrybn's avatar
arrybn committed
797
    int fill(Module *module, std::vector<std::pair<int, Module*> >& addedModules, int prevLayerId = 0, int prevOutNum = 0)
798 799 800 801 802 803
    {
        if (module == NULL)
            return prevLayerId;

        if (module->apiType.length())
        {
arrybn's avatar
arrybn committed
804
            int newLayerId = net.addLayer(generateLayerName(module->apiType), module->apiType, module->params);
805
            net.connect(prevLayerId, prevOutNum, newLayerId, 0);
arrybn's avatar
arrybn committed
806
            addedModules.push_back(std::make_pair(newLayerId, module));
807 808 809 810 811 812 813 814
            return newLayerId;
        }
        else
        {
            if (module->thName == "Sequential")
            {
                for (size_t i = 0; i < module->modules.size(); i++)
                {
arrybn's avatar
arrybn committed
815
                    prevLayerId = fill(module->modules[i], addedModules, prevLayerId, prevOutNum);
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
                    prevOutNum = 0;
                }
                return prevLayerId;
            }
            else if (module->thName == "Concat")
            {
                int newId, splitId, mergeId;
                LayerParams mergeParams, splitParams;
                mergeParams.set("axis", module->params.get<int>("dimension") - 1);

                splitId = net.addLayer(generateLayerName("torchSplit"), "Split", splitParams);
                mergeId = net.addLayer(generateLayerName("torchMerge"), "Concat", mergeParams);
                net.connect(prevLayerId, prevOutNum, splitId, 0);

                for (int i = 0; i < (int)module->modules.size(); i++)
                {
arrybn's avatar
arrybn committed
832
                    newId = fill(module->modules[i], addedModules, splitId, i);
833 834 835
                    net.connect(newId, 0, mergeId, i);
                }

arrybn's avatar
arrybn committed
836
                addedModules.push_back(std::make_pair(mergeId, module));
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
                return mergeId;
            }
            else if (module->thName == "Parallel")
            {
                int newId, splitId, mergeId, reshapeId;

                LayerParams splitParams, mergeParams, reshapeParams;
                splitParams.set("axis", module->params.get<int>("inputDimension") - 1);
                mergeParams.set("axis", module->params.get<int>("outputDimension") - 1);
                reshapeParams.set("axis", splitParams.get<int>("axis"));
                reshapeParams.set("num_axes", 1);

                splitId = net.addLayer(generateLayerName("torchSplit"), "Slice", splitParams);
                mergeId = net.addLayer(generateLayerName("torchMerge"), "Concat", mergeParams);
                reshapeId = net.addLayer(generateLayerName("torchReshape"), "Reshape", reshapeParams);
                net.connect(prevLayerId, prevOutNum, splitId, 0);

                for (int i = 0; i < (int)module->modules.size(); i++)
                {
                    net.connect(splitId, i, reshapeId, i);
arrybn's avatar
arrybn committed
857
                    newId = fill(module->modules[i], addedModules, reshapeId, i);
858 859 860
                    net.connect(newId, 0, mergeId, i);
                }

arrybn's avatar
arrybn committed
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
                addedModules.push_back(std::make_pair(mergeId, module));
                return mergeId;
            }
            else if (module->thName == "ConcatTable") {
                int newId, splitId;
                LayerParams splitParams;

                splitId = net.addLayer(generateLayerName("torchSplit"), "Split", splitParams);
                net.connect(prevLayerId, prevOutNum, splitId, 0);

                addedModules.push_back(std::make_pair(splitId, module));

                for (int i = 0; i < (int)module->modules.size(); i++)
                {
                    newId = fill(module->modules[i], addedModules, splitId, i);
                }

                return newId;
            }
            else if (module->thName == "JoinTable") {
                std::vector<int> ids = net.getUnconnectedOutLayers();

                int mergeId;
                LayerParams mergeParams;
                mergeParams.set("axis", module->params.get<int>("dimension") - 1);

                mergeId = net.addLayer(generateLayerName("torchMerge"), "Concat", mergeParams);
                addedModules.push_back(std::make_pair(mergeId, module));

                for (int i = 0; i < ids.size(); i++)
                {
                    net.connect(ids[i], 0, mergeId, i);
                }

895 896
                return mergeId;
            }
arrybn's avatar
arrybn committed
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
            else if (module->thName == "CAddTable") {
                String name = generateLayerName("torchCAddTable");
                std::vector<int> ids = net.getUnconnectedOutLayers();
                LayerParams params;
                params.set("operation", "sum");


                int id = net.addLayer(name, "Eltwise", params);

                for (int i = 0; i < ids.size(); i++)
                {
                    net.connect(ids[i], 0, id, i);
                }

                addedModules.push_back(std::make_pair(id, module));
                return id;
            }
            else if (module->thName == "SpatialMaxUnpooling") {
                CV_Assert(module->params.has("indices_blob_id"));
                int indicesBlobId = module->params.get<int>("indices_blob_id");
917 918
                std::pair<int, Module*> poolingLayer;
                poolingLayer.first = -1;
arrybn's avatar
arrybn committed
919 920 921 922 923 924 925

                for(int i = 0; i < addedModules.size(); i++)
                {
                    if (addedModules[i].second->apiType == "Pooling" &&
                        addedModules[i].second->params.has("indices_blob_id") &&
                        addedModules[i].second->params.get<int>("indices_blob_id") == indicesBlobId)
                    {
926
                        poolingLayer = addedModules[i];
arrybn's avatar
arrybn committed
927 928 929 930
                        break;
                    }
                }

931 932 933 934 935 936 937 938 939 940 941 942 943 944
                module->params.set("pool_k_h", poolingLayer.second->params.get<int>("kernel_h"));
                module->params.set("pool_k_w", poolingLayer.second->params.get<int>("kernel_w"));
                module->params.set("pool_stride_h", poolingLayer.second->params.get<int>("stride_h"));
                module->params.set("pool_stride_w", poolingLayer.second->params.get<int>("stride_w"));
                module->params.set("pool_pad_h", poolingLayer.second->params.get<int>("pad_h"));
                module->params.set("pool_pad_w", poolingLayer.second->params.get<int>("pad_w"));

                String name = generateLayerName("torchMaxUnpooling");
                int id = net.addLayer(name, "MaxUnpool", module->params);
                net.connect(prevLayerId, 0, id, 0);

                CV_Assert(poolingLayer.first != -1);
                net.connect(poolingLayer.first, 1, id, 1);

arrybn's avatar
arrybn committed
945 946
                return id;
            }
947 948 949 950 951 952
        }

        CV_Error(Error::StsInternal, "Unexpected torch container: " + module->thName);
        return -1;
    }

arrybn's avatar
arrybn committed
953
    void populateNet(Net net_)
954 955 956 957 958 959 960 961 962 963
    {
        if (rootModule == NULL)
        {
            rootModule = new Module("Sequential");
            curModule = rootModule;

            THFile_seek(file, 0);
            readObject();
        }

arrybn's avatar
arrybn committed
964 965 966
        net = net_;
        std::vector<std::pair<int, Module*> > addedModules;
        fill(rootModule, addedModules);
967 968 969
    }
};

970
Ptr<Importer> createTorchImporter(const String &filename, bool isBinary)
971 972 973 974 975
{
    return Ptr<Importer>(new TorchImporter(filename, isBinary));
}


976
Mat readTorchBlob(const String &filename, bool isBinary)
977 978 979 980 981 982 983
{
    Ptr<TorchImporter> importer(new TorchImporter(filename, isBinary));
    importer->readObject();
    CV_Assert(importer->tensors.size() == 1);

    return importer->tensors.begin()->second;
}
984

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
#else

Ptr<Importer> createTorchImporter(const String&, bool)
{
    CV_Error(Error::StsNotImplemented, "Torch importer is disabled in current build");
    return Ptr<Importer>();
}

Mat readTorchBlob(const String&, bool)
{
    CV_Error(Error::StsNotImplemented, "Torch importer is disabled in current build");
    return Mat();
}

#endif //defined(ENABLE_TORCH_IMPORTER) && ENABLE_TORCH_IMPORTER

1001 1002
Net readNetFromTorch(const String &model, bool isBinary)
{
1003
    Ptr<Importer> importer = createTorchImporter(model, isBinary);
1004 1005 1006 1007 1008 1009
    Net net;
    if (importer)
        importer->populateNet(net);
    return net;
}

1010 1011
}
}