mxnet icon indicating copy to clipboard operation
mxnet copied to clipboard

Write CNN program with C++

Open zhubuntu opened this issue 10 years ago • 16 comments

I'm trying to write a CNN program with C++,according to mlp.cpp,It can compile ,but when I run my CNN program .there were always errors at

mxnet::Executor* exe =
            mxnet::Executor::Bind(sym_out, ctx_dev, g2c, in_args, arg_grad_store,
            grad_req_type,aux_states);

The error information is

0x00007FFC0EFD1F08 处(位于 MxnetTestApp.exe 中)有未经处理的异常: Microsoft C++ 异常: dmlc::Error,位于内存位置 0x000000F2EA8FDD18 处。

Here is my program

#include <iostream>
#include <utility>
#include <map>
#include <string>
#include <vector>

#include "mxnet/ndarray.h"
#include "mxnet/base.h"
#include "mxnet/operator.h"
#include "mxnet/symbolic.h"

using namespace std;

#if MSHADOW_USE_CUDA
#define DEV_CTX \
  (mxnet::Context::Create(mxnet::Context::kGPU, 0))  // use no.0 gpu
#else
#define DEV_CTX (mxnet::Context::Create(mxnet::Context::kCPU, 0))  // use cpu
#endif


class CNN {
public:
    mxnet::Symbol ConvolutionLayer(mxnet::Symbol input, std::string kernel = "(5,5)",
        std::string stride = "(1,1)", std::string num_filter = "4", std::string name = "conv") {
        mxnet::OperatorProperty* convolution_op =
            mxnet::OperatorProperty::Create("Convolution");
        std::vector<std::pair<std::string, std::string> > conv_config;
        conv_config.push_back(std::make_pair("kernel", kernel));
        conv_config.push_back(std::make_pair("stride", stride));
        conv_config.push_back(std::make_pair("num_filter", num_filter));
        convolution_op->Init(conv_config);

        std::vector<mxnet::Symbol> sym_vec;
        sym_vec.push_back(input);
        mxnet::Symbol conv = mxnet::Symbol::Create(convolution_op)(sym_vec, name);

        return conv;
    }

    mxnet::Symbol BatchNormLayer(mxnet::Symbol input, std::string name = "batch") {
        mxnet::OperatorProperty* batchnorm_op =
            mxnet::OperatorProperty::Create("BatchNorm");
        std::vector<std::pair<std::string, std::string> > config;
        batchnorm_op->Init(config);
        std::vector<mxnet::Symbol> sym_vec;
        sym_vec.push_back(input);
        mxnet::Symbol batch= mxnet::Symbol::Create(batchnorm_op)(sym_vec, name);

        return batch;
    }
    mxnet::Symbol ActivationLayer(mxnet::Symbol input, std::string act_type = "relu", 
std::string name = "act") {
        mxnet::OperatorProperty* activation_op =
            mxnet::OperatorProperty::Create("Activation");
        std::vector<std::pair<std::string, std::string> > act_config;
        act_config.push_back(std::make_pair("act_type", act_type));
        activation_op->Init(act_config);
        std::vector<mxnet::Symbol> sym_vec;
        sym_vec.push_back(input);
        mxnet::Symbol act = mxnet::Symbol::Create(activation_op)(sym_vec, name);

        return act;
    }
    mxnet::Symbol PoolingLayer(mxnet::Symbol input, std::string pool_type = "max",
        std::string kernel = "(2,2)",std::string stride = "(2,2)",
        std::string name = "pool_max") {
        mxnet::OperatorProperty* pooling_op =
            mxnet::OperatorProperty::Create("Pooling");

        std::vector<std::pair<std::string, std::string> > pool_config;
        pool_config.push_back(
            std::make_pair("pool_type", pool_type));  
        pool_config.push_back(std::make_pair("kernel", kernel));
        pool_config.push_back(std::make_pair("stride", stride));
        pool_config.push_back(std::make_pair("pad", "(1,1)"));
        pooling_op->Init(pool_config);
        std::vector<mxnet::Symbol> sym_vec;

        sym_vec.push_back(input);
        mxnet::Symbol pool_max =
            mxnet::Symbol::Create(pooling_op)(sym_vec, name);
        return pool_max;
    }

    mxnet::Symbol FlattenLayer(mxnet::Symbol input, std::string name = "flatten") {
        mxnet::OperatorProperty* flatten_op =
            mxnet::OperatorProperty::Create("Flatten");
        std::vector<std::pair<std::string, std::string> > fla_config;
        flatten_op->Init(fla_config);

        std::vector<mxnet::Symbol> sym_vec;
        sym_vec.push_back(input);
        mxnet::Symbol fla = mxnet::Symbol::Create(flatten_op)(sym_vec, name);

        return fla;
    }
    mxnet::Symbol SoftmaxLayer(mxnet::Symbol input,
        std::string name = "softmax") {
        mxnet::OperatorProperty* softmax_output_op =
            mxnet::OperatorProperty::Create("SoftmaxOutput");

        std::vector<std::pair<std::string, std::string> > config;
        softmax_output_op->Init(config);

        std::vector<mxnet::Symbol> sym_vec;
        sym_vec.push_back(input);
        mxnet::Symbol softmax =
            mxnet::Symbol::Create(softmax_output_op)(sym_vec, name);

        return softmax;
    }
    mxnet::Symbol FullyConnectedLayer(mxnet::Symbol input,
        std::string num_hidden = "2",
        std::string name = "fc") {
        mxnet::OperatorProperty* fully_connected_op =
            mxnet::OperatorProperty::Create("FullyConnected");

        std::vector<std::pair<std::string, std::string> > fc_config;
        fc_config.push_back(std::make_pair("num_hidden", num_hidden));
        fc_config.push_back(std::make_pair("no_bias", "false"));
        fully_connected_op->Init(fc_config);

        std::vector<mxnet::Symbol> sym_vec;
        sym_vec.push_back(input);
        mxnet::Symbol fc = mxnet::Symbol::Create(fully_connected_op)(sym_vec, name);

        return fc;
    }

    void Train() {
        // setup sym network
        mxnet::Symbol sym_x = mxnet::Symbol::CreateVariable("X");
        mxnet::Symbol sym_conv1 = ConvolutionLayer(sym_x,"(5,5)","(1,1)","4","conv1");
        mxnet::Symbol sym_bn1 = BatchNormLayer(sym_conv1, "bn1");
        mxnet::Symbol sym_act1 = ActivationLayer(sym_bn1, "relu", "act1");
        mxnet::Symbol sym_mp1 = PoolingLayer(sym_act1,"max","(2,2)","(2,2)", "mp1");

        mxnet::Symbol sym_conv2 = ConvolutionLayer(sym_mp1, "(5,5)", "(1,1)", "4", "conv2");
        mxnet::Symbol sym_bn2 = BatchNormLayer(sym_conv2, "bn2");
        mxnet::Symbol sym_act2 = ActivationLayer(sym_bn2, "relu", "act2");
        mxnet::Symbol sym_mp2 = PoolingLayer(sym_act2, "max", "(2,2)", "(2,2)", "mp2");

        mxnet::Symbol sym_f1 = FlattenLayer(sym_mp2, "f1");
        mxnet::Symbol sym_fc1 = FullyConnectedLayer(sym_f1,"2", "fc1");
        mxnet::Symbol sym_out = SoftmaxLayer(sym_fc1, "softmax");

        // prepare train data
        mxnet::Context ctx_cpu = mxnet::Context::Create(mxnet::Context::kCPU, 1);
        mxnet::Context ctx_dev = DEV_CTX;  // use gpu if possible

        mxnet::NDArray array_x(mshadow::Shape4(1,1,128, 128), ctx_dev, false);
        mxnet::NDArray array_y(mshadow::Shape1(1), ctx_dev, false);

        mxnet::real_t* aptr_x = new mxnet::real_t[128 * 128];
        mxnet::real_t* aptr_y = new mxnet::real_t[1];

        // we make the data by hand, in 10 classes, with some pattern
        for (int i = 0; i < 128; i++) {
            for (int j = 0; j < 128; j++) {
                aptr_x[i * 128 + j] = i ;
            }
        }
        aptr_y[0] = 1;
        array_x.SyncCopyFromCPU(aptr_x, 128 * 128);
        array_x.WaitToRead();
        array_y.SyncCopyFromCPU(aptr_y, 1);
        array_y.WaitToRead();

        // init the parameters
        mxnet::NDArray conv1_1(mshadow::Shape4(4,1,5,5), ctx_dev, false);
        mxnet::NDArray conv1_2(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray bn1_1(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray bn1_2(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray conv2_1(mshadow::Shape4(4, 4, 5, 5), ctx_dev, false);
        mxnet::NDArray conv2_2(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray bn2_1(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray bn2_2(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray fc1_1(mshadow::Shape2(2,196), ctx_dev, false);
        mxnet::NDArray fc1_2(mshadow::Shape1(2), ctx_dev, false);

        // the parameters should be initialized in some kind of distribution,
        // so it learns fast
        // but here just give a const value by hand
        conv1_1 = 0.5f;
        conv1_2 = 0.0f;
        bn1_1 = 0.5f;
        bn1_2 = 0.5f;
        conv2_1 = 0.5f;
        conv2_2 = 0.0f;
        bn2_1 = 0.5f;
        bn2_2 = 0.5f;
        fc1_1 = 0.5f;
        fc1_2 = 0.0f;
        // the grads
        mxnet::NDArray conv1_1g(mshadow::Shape4(4, 1, 5, 5), ctx_dev, false);
        mxnet::NDArray conv1_2g(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray bn1_1g(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray bn1_2g(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray conv2_1g(mshadow::Shape4(4,4, 5, 5), ctx_dev, false);
        mxnet::NDArray conv2_2g(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray bn2_1g(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray bn2_2g(mshadow::Shape1(4), ctx_dev, false);
        mxnet::NDArray fc1_1g(mshadow::Shape2(2,196), ctx_dev, false);
        mxnet::NDArray fc1_2g(mshadow::Shape1(2), ctx_dev, false);

        // Bind the symolic network with the ndarray
        std::map<std::string, mxnet::Context> g2c;
        // all the input args
        std::vector<mxnet::NDArray> in_args;
        in_args.push_back(array_x);
        in_args.push_back(conv1_1);
        in_args.push_back(conv1_2);
        in_args.push_back(bn1_1);
        in_args.push_back(bn1_2);
        in_args.push_back(conv2_1);
        in_args.push_back(conv2_2);
        in_args.push_back(bn2_1);
        in_args.push_back(bn2_2);
        in_args.push_back(fc1_1);
        in_args.push_back(fc1_2);
        in_args.push_back(array_y);
        // all the grads
        std::vector<mxnet::NDArray> arg_grad_store;
        arg_grad_store.push_back(
            mxnet::NDArray());  // we don't need the grad of the input
        arg_grad_store.push_back(conv1_1g);
        arg_grad_store.push_back(conv1_2g);
        arg_grad_store.push_back(bn1_1g);
        arg_grad_store.push_back(bn1_2g);
        arg_grad_store.push_back(conv2_1g);
        arg_grad_store.push_back(conv2_2g);
        arg_grad_store.push_back(bn2_1g);
        arg_grad_store.push_back(bn2_2g);
        arg_grad_store.push_back(fc1_1g);
        arg_grad_store.push_back(fc1_2g);
        arg_grad_store.push_back(
            mxnet::NDArray());  // neither do we need the grad of the loss
        // how to handle the grad
        std::vector<mxnet::OpReqType> grad_req_type;
        grad_req_type.push_back(mxnet::kNullOp);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kWriteTo);
        grad_req_type.push_back(mxnet::kNullOp);
        std::vector<mxnet::NDArray> aux_states;
        cout << "make the Executor" << endl;
        mxnet::Executor* exe =
            mxnet::Executor::Bind(sym_out, ctx_dev, g2c, in_args, arg_grad_store,
            grad_req_type,aux_states);

        cout << "Training" << endl;
        exe->Forward(true);

        const std::vector<mxnet::NDArray>& out = exe->outputs();
        mxnet::NDArray c_cpu = out[0].Copy(ctx_cpu);
        c_cpu.WaitToRead();
        mxnet::real_t* cptr = static_cast<mxnet::real_t*>(c_cpu.data().dptr_);
        cout << cptr[0];

        delete[] aptr_x;
        delete[] aptr_y;
    }
};

int main(int argc, char** argv) {
    CNN cnn;
    cnn.Train();
    return 0;
}

The array_x is the input which shape is(1,1,128,128);This is the python program to detect shape inconsistency,so I think the in_args is right.

import mxnet as mx
data = mx.symbol.Variable('data')
net= mx.symbol.Convolution(data = data, name='conv1', num_filter=4, kernel=(5,5), stride=(2,2))
net = mx.symbol.BatchNorm(data = net, name="bn1")
net= mx.symbol.Activation(data =net, name='relu1', act_type="relu")
net = mx.symbol.Pooling(data = net, name = 'mp1', kernel=(2,2), stride=(2,2), pool_type='max')

net= mx.symbol.Convolution(data = net, name='conv2', num_filter=4, kernel=(5,5), stride=(2,2))
net= mx.symbol.BatchNorm(data = net, name="bn2")
net = mx.symbol.Activation(data =net, name='relu2', act_type="relu")
net = mx.symbol.Pooling(data = net, name = 'mp2', kernel=(2,2), stride=(2,2), pool_type='max')

net = mx.symbol.Flatten(data = net, name="flatten")
net = mx.symbol.FullyConnected(data = net, name='fc1', num_hidden=2)
net = mx.symbol.SoftmaxOutput(data = net, name = 'sm')
arg_shape, out_shape, aux_shape = net.infer_shape(data=(1, 1,128, 128))
dict(zip(net.list_arguments(), arg_shape))

I don't know what's wrong with my program,could sombody help me?

zhubuntu avatar Dec 20 '15 07:12 zhubuntu

Where exactly is the error? Could you compile with debug and trace the error?

piiswrong avatar Dec 20 '15 08:12 piiswrong

@piiswrong I'm sorry ,when I compile this with debug,there is another problem,which says

Program: D:\mxnet\win64\app\MxnetTestApp\x64\Debug\MxnetTestApp.exe
File: f:\dd\vctools\crt\crtw32\misc\dbgheap.c
Line: 1424

Expression: _pFirstBlock == pHead

I think this maybe caused when i build libmxnet.dll from the source. Can you run this program and help me to find where is wrong? I only know the error happened at the

mxnet::Executor* exe =
            mxnet::Executor::Bind(sym_out, ctx_dev, g2c, in_args, arg_grad_store,
            grad_req_type,aux_states);

zhubuntu avatar Dec 20 '15 08:12 zhubuntu

@zhubuntu Two problems here. First, the shape is wrong. Try using infer-shape. Second, when you use BatchNorm operator, you'll need the aux_states.

refer to new PR https://github.com/dmlc/mxnet/pull/980

For now, if you want to use cpp, you have to check the code carefully. I mean, you have to be familiar with the source codes in some degree, if you want to add something new.

zhangchen-qinyinghua avatar Dec 20 '15 09:12 zhangchen-qinyinghua

@zhangchen-qinyinghua Thanks, i'm not familiar with the source codes,I'll try to read it.But when i try to compile the mlp.cpp with debug ,It still show the error information

Program: D:\mxnet\win64\app\MxnetTestApp\x64\Debug\MxnetTestApp.exe
File: f:\dd\vctools\crt\crtw32\misc\dbgheap.c
Line: 1424
Expression: _pFirstBlock == pHead

And it happend at the

mxnet::Symbol sym_fc_1 = FullyConnectedLayer(sym_x, "512", "fc1");

when the FullyConnectedLayer function end. Was it because I use the windows version?I rebulid the libmxnet.dll with debug from the source ,it still has this problem.

zhubuntu avatar Dec 20 '15 10:12 zhubuntu

@zhubuntu As I said, the fc_1 NDArray shape you feed into the Net is not right. Try to fix it first. Try using infer-shape functon.

And if there's problem with you using the original mlp.cpp, I really cannot help. I've never used the Windows version. I'll try to make a mlp example with c_apis, maybe a little bit later.

zhangchen-qinyinghua avatar Dec 20 '15 11:12 zhangchen-qinyinghua

@zhangchen-qinyinghua I see, thanks for your help. Really appreciate about this.

zhubuntu avatar Dec 20 '15 11:12 zhubuntu

@zhubuntu Still, maybe you can try using PR #980 , and see if it can make the use of cpp a little easier. (And see if bugs there)

zhangchen-qinyinghua avatar Dec 20 '15 11:12 zhangchen-qinyinghua

@zhangchen-qinyinghua Ok,I'll see if I can run it tomorrow.It's time to prepare the exam.

zhubuntu avatar Dec 20 '15 11:12 zhubuntu

@zhangchen-qinyinghua I can run this ,and there is some change i made

  • I change the
class MXNET_API  CppNet {

in cpp_net.hpp to

class  CppNet {

because i found with MXNET_API ,when compile it will shows

error LNK2001:  unresolved   external   symbol "__declspec(dllimport) public: __cdecl mxnet::CppNet::~CppNet(void)" (__imp_??1CppNet@mxnet@@QEAA@XZ)
  • I change the
MnistCppNet mnist(true, 2);

in the main function to

MnistCppNet mnist(true, 0);

because I only have one GPU. Thanks for this,I learn very much from your program.And maybe you can upload the train.csv with this pull,so other people will not have to find the train.csv on the internet. This is the screenshot I run it 1

zhubuntu avatar Dec 21 '15 03:12 zhubuntu

This might have been caused by different layout of structures between the DLL and the EXE. With different compile options, the compiler might layout the struct/class in different ways, creating incompatible code. There are two ways to avoid this: 1) use only C api in the dll. 2) compile the exe directly, instead of generating DLL and then link into EXE

I would like to suggest we take 1, since we will then just offer binary distribution of the DLL, just as we did with Python and R.

On Mon, Dec 21, 2015 at 11:05 AM, zhubuntu [email protected] wrote:

@zhangchen-qinyinghua https://github.com/zhangchen-qinyinghua I can run this ,and there is some change i made 1, I change the

class MXNET_API CppNet {

in cpp_net.hpp to

class CppNet {

because i found with MXNET_API ,when compile it will shows

error LNK2001: unresolved external symbol "__declspec(dllimport) public: __cdecl mxnet::CppNet::~CppNet(void)" (_imp??1CppNet@mxnet@@QEAA@XZ)

2,I change the

MnistCppNet mnist(true, 2);

in the main function to

MnistCppNet mnist(true, 0);

because I only have one GPU. Thanks for this,I learn very much from your program. This is the screenshot I run it [image: 1] https://cloud.githubusercontent.com/assets/15666683/11922525/931e30f8-a7d2-11e5-8643-7964f5ccadc5.png

— Reply to this email directly or view it on GitHub https://github.com/dmlc/mxnet/issues/987#issuecomment-166185023.

HONG Chuntao System Research Group Microsoft Research Asia

hjk41 avatar Dec 21 '15 03:12 hjk41

@zhubuntu Thank you for you work.

@hjk41 Does this mean if I add a MXNET_API in front of the CppNet class, then it will be runnable for Windows, without changing the source codes of MXNET? And it is possible to use C api only. Just takes a few more work.

zhangchen-qinyinghua avatar Dec 21 '15 10:12 zhangchen-qinyinghua

@zhangchen-qinyinghua Any class or function not guarded by MXNET_API will not be exported in the DLL. So if you try to use it, you get undefined symbol. For example, Executor::Bind(), and xxx::Create() functions are not exported by default.

By using MXNET_API, we can fix the undefined symbol problem, but then we face the class layout problem. Different compiler/compiler options results in different class layout, thus calling C++ API from dynamic library is a bad idea. This is also a problem for Linux, if you use GCC -O2 to compile the .so file, and then use GCC -O0 to compile mlp.

The only safe way to use dynamic library is to use only C api, which is well defined and compatible across different compilers. I have just started writing a C++ wrapper on top of the C API(https://github.com/hjk41/mxnet/blob/cpp/example/cpp/MxNetCpp.h). Maybe we can work together on the wrapper. And we probably should setup a standalone project as we did for MxNet.jl.

hjk41 avatar Dec 21 '15 10:12 hjk41

@hjk41 I got your point. It sounds reasonable.

zhangchen-qinyinghua avatar Dec 21 '15 10:12 zhangchen-qinyinghua

@zhangchen-qinyinghua The latest code is here: https://github.com/hjk41/MxNet.cpp

hjk41 avatar Dec 22 '15 09:12 hjk41

@zhubuntu @zhangchen-qinyinghua Let's move to the #868 for discussing this issue.

hjk41 avatar Dec 22 '15 09:12 hjk41

@zhubuntu The cpp wrapper will soon be available. I will close this issue now.

hjk41 avatar Jan 13 '16 05:01 hjk41