I want to write a custom layer to get mean and var value of symbol layer, but backward function does not work


#1

The code is the following:
import logging
import mxnet as mx
import numpy as np
from distutils.util import strtobool

from …logger import logger
from rcnn.io.rcnn import sample_rois

class Debug(mx.operator.CustomOp):
def forward(self, is_train, req, in_data, out_data, aux):

    value = in_data[0].asnumpy()
    value = np.reshape(value, (1, -1))
    temp = np.zeros((2, ))
    temp[0] = np.mean(value, axis=1)
    temp[1] = np.var(value, axis=1)
    f = open('s.txt', 'a')
    f.write('mean\t')
    f.write('%1.4f\t' % temp[0])
    f.write('var\t')
    f.write('%1.4f\n' % temp[1])
    f.close()
    self.assign(out_data[0], req[0], mx.nd.array(in_data[0]))


def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
    self.assign(in_grad[0],req[0], out_grad[0])

@mx.operator.register(‘Debug’)
class DebugProp(mx.operator.CustomOpProp):
def init(self):
super(DebugProp, self).init(need_top_grad=False)

def list_arguments(self):
    return ['conv_feat']

def list_outputs(self):
    return ['conv_output']

def list_auxiliary_states(self):
    return []

def declare_backward_dependency(self, out_grad, in_data, out_data):
    return []

def create_operator(self, ctx, shapes, dtypes):
    return Debug()

error:
/home/travis/build/dmlc/mxnet-distro/mxnet-build/dmlc-core/include/dmlc/logging.h:308: [14:26:54] include/mxnet/./././ndarray.h:283: Check failed: !is_none()

/home/travis/build/dmlc/mxnet-distro/mxnet-build/dmlc-core/include/dmlc/logging.h:308: [14:26:54] src/operator/custom/custom.cc:348: Check failed: reinterpret_cast(params.info->callbacks[kCustomOpBackward])( ptrs.size(), ptrs.data(), tags.data(), reinterpret_cast<const int*>(req.data()), static_cast(ctx.is_train), params.info->contexts[kCustomOpBackward])

Any advice will be appreciated.