使用python创建mxnet操作符(网络层)

时间:2024-09-21 14:36:20

对cuda了解不多,所以使用python创建新的操作层是个不错的选择,当然这个性能不如cuda编写的代码。

在MXNET源码的example/numpy-ops/下有官方提供的使用python编写新操作符的实例。分别跑ndarray_softmax.py、numpy_softmax.py和custom_softmax.py 发现ndarray_softmax.py中训练速度将近其他两种方法的3倍,分析发现ndarray_softmax.py中调用cuda核,而其他两种方法都是numpy在cpu上的运行。

这里总结一下我对ndarray_softmax.py的理解。

分析一下ndarray_softmax.py源码,重写了父类的一些基本方法,其中最重要的是前向和后向操作:

 def forward(self, in_data, out_data):
x = in_data[0]
y = out_data[0]
if self.fwd_kernel is None:
self.fwd_kernel = mx.rtc('softmax', [('x', x)], [('y', y)], """
int i = threadIdx.x + blockIdx.x*blockDim.x;
float max_x = x[i*x_dims[1]];
for (int j = 1; j < x_dims[1]; ++j) {
if (max_x < x[i*x_dims[1]+j]) {
max_x = x[i*x_dims[1]+j];
}
}
float sum = 0.0f;
for (int j = 0; j < x_dims[1]; ++j) {
sum += expf(x[i*x_dims[1]+j]-max_x);
}
for (int j = 0; j < x_dims[1]; ++j) {
y[i*x_dims[1]+j] = expf(x[i*x_dims[1]+j]-max_x)/sum;
}
""")
self.fwd_kernel.push([x], [y], (1, 1, 1), (x.shape[0], 1, 1))

def backward(self, out_grad, in_data, out_data, in_grad):
l = in_data[1]
y = out_data[0]
dx = in_grad[0]
if self.bwd_kernel is None:
self.bwd_kernel = mx.rtc('softmax_grad', [('y', y), ('l', l)], [('dx', dx)], """
int i = blockIdx.x;
int j = threadIdx.x;
int k = static_cast<int>(l[i]);
if (j == k) {
dx[i*dx_dims[1]+j] = y[i*dx_dims[1]+j] - 1.0f;
} else {
dx[i*dx_dims[1]+j] = y[i*dx_dims[1]+j];
}
""")
self.bwd_kernel.push([y,l], [dx], (y.shape[0],1,1), (y.shape[1], 1, 1))

使用mx.rtc(...)定义的就是cuda 编译相关内容了,查看/python/mxnet/rtc.py中Rtc类的定义,其参数部分描述如下:

 """MXRtc object in mxnet.
This class allow you to write CUDA kernels in Python
and call them with NDArray.

Parameters
----------
name : str
Name of the kernel.
inputs : tuple of (str, mxnet.ndarray)
List of input names and ndarray.
outputs : tuple of (str, mxnet.ndarray)
List of output names and ndarray.
kernel : str
The actual kernel code.
Note that this is only the body of the kernel, i.e.
after { and before }. Rtc will decorate the kernel.
For example, if ``name = "mykernel"`` and
inputs = [('x', mx.nd.zeros((10,)))]
outputs = [('y', mx.nd.zeros((10,)))]
kernel = "y[threadIdx.x] = x[threadIdx.x];",
then the compiled kernel will be:
extern "C" __global__ mykernel(float *x, float *y) {
const int x_ndim = 1;
const int x_dims = { 10 };
const int y_ndim = 1;
const int y_dims = { 10 };

y[threadIdx.x] = x[threadIdx.x];
}
"""

以ndarray_softmax.py为例, softmax层输入数据shape=(100,10),输出数据shape=(100,10),那么forward方法里的x_dim=(100,10), 第三个参数即cuda编译的要执行的语句。 在forward方法中看到最后一句push方法,gridDim={'x':1,'y':1,'z':1}, blockDim={'x':100,'y':1,'z':1} (cuda存储参见cudaMemcpy与kernel),于是每一个线程操作一个sample的10个elements,threadIdx.x表示线程在block块中的索引,那么threadIdx.x+blockIdx.x*blockDim.x就是对应线程总的索引,blockDim对应的是block中threads的个数,然后后面softmax前向计算就容易理解了。

再看backward方法,这个kernel将gradDim划分成(100,1,1), blockDim划分成(10,1,1),即每一个element对应着一个线程,然后在每一个线程中计算该element对应的梯度。

example:

实现一个reorganize层,也就是yolo中特征重组层,具体功能YOLO v2 reorg 当然,最清楚的方式是看darknet中源码如何实现。

这个例子只是想继承mx.operator.NDArrayOp实现新的操作层,该操作层中没有权重参数,对于有权重的层要在forward和backward中操作对应的值。

  # -*- coding: utf-8 -*-
import mxnet as mx
import numpy as np
import logging

class NDArrayReorg(mx.operator.NDArrayOp):
def __init__(self, stride=2):
super(NDArrayReorg, self).__init__(True)
self.stride = stride
self.fwd_kernel = None
self.bwd_kernel = None def list_arguments(self):
return ['data'] def list_outputs(self):
return ['output'] def infer_shape(self, in_shape):
data_shape = in_shape[0]
output_shape = [in_shape[0][0], in_shape[0][1]*4
, in_shape[0][2]/self.stride, in_shape[0][3]/self.stride] return [data_shape], [output_shape] def forward(self, in_data, out_data):
x = in_data[0]
y = out_data[0]
if self.fwd_kernel is None:
self.fwd_kernel = mx.rtc('reorg',[('x',x)],[('y',y)],"""
int i = threadIdx.x + blockIdx.x*blockDim.x ;
int yw=y_dims[3];
int yh = y_dims[2];
int N = yw*yh;
int xw=x_dims[3];
int xh = x_dims[2];
int len_block = x_dims[2]*x_dims[3];
for(int j =0; j<xh; j+=2)
for(int k=0; k<xw; k+=2)
{ int t=j/2;
y[i*len_block+t*yw+k/2] = x[i*len_block+j*xw+k];
y[i*len_block+t*yw+k/2+N] = x[i*len_block + j*xw+k+1];
y[i*len_block+t*yw+k/2+2*N] = x[i*len_block +(j+1)*xw+k];
y[i*len_block+t*yw+k/2+3*N] = x[i*len_block +(j+1)*xw+k+1];
}
""")
self.fwd_kernel.push([x],[y],(x.shape[0]*x.shape[1],1,1),(1,1,1)) def backward(self, out_grad, in_data, out_data, in_grad):
y = out_grad[0]
dx = in_grad[0]
if self.bwd_kernel is None:
self.bwd_kernel = mx.rtc('reorg_grad',[('y',y)],[('dx', dx)],"""
int i = threadIdx.x + blockIdx.x * blockDim.x;
int yh = y_dims[2];
int yw = y_dims[3];
int N = yw*yh;
int old_block = dx_dims[2]*dx_dims[3];
for(int k=0;k<4;++k)
for(int j=0; j<yw; ++j)
for(int t=0; t<yh; ++t){
dx[i*old_block+2*j*yw+t*2+k]=y[i*old_block+k*N+j*yw+t];
}
""")
self.bwd_kernel.push([y],[dx],(y.shape[0]*y.shape[1]/4,1,1),(1,1,1)) mnist = mx.test_utils.get_mnist()
batch_size = 100
train_iter = mx.io.NDArrayIter(mnist['train_data'], mnist['train_label'], batch_size, shuffle=True)
val_iter = mx.io.NDArrayIter(mnist['test_data'], mnist['test_label'], batch_size)


data = mx.sym.var('data')
conv1 = mx.sym.Convolution(data=data, kernel=(5,5), num_filter=20)
tanh1 = mx.sym.Activation(data=conv1, act_type="tanh")
# pool1 = mx.sym.Pooling(data=tanh1, pool_type="max", kernel=(2,2), stride=(2,2))

reorg = NDArrayReorg(stride=2)
reg = reorg(data=tanh1, name='reorg')
conv2 = mx.sym.Convolution(data=reg, kernel=(5,5), num_filter=20)
tanh2 = mx.sym.Activation(data=conv2, act_type="tanh") # 80x8x8

conv2 = mx.sym.Convolution(data=tanh2, kernel=(5,5), num_filter=50)
tanh2 = mx.sym.Activation(data=conv2, act_type="tanh")
# pool2 = mx.sym.Pooling(data=tanh2, pool_type="max", kernel=(2,2), stride=(2,2))

flatten = mx.sym.flatten(data=tanh2)
fc1 = mx.sym.FullyConnected(data=flatten,num_hidden=500)
tanh3 = mx.sym.Activation(data=fc1, act_type="tanh")

fc2 = mx.sym.FullyConnected(data=tanh3, num_hidden=10)

mynet = mx.sym.SoftmaxOutput(data=fc2, name='softmax')

print(mynet.infer_shape(data=(100,1,28,28)))
mynet_model = mx.mod.Module(symbol=mynet, context=mx.gpu())

mynet_model.fit(train_iter,
eval_data=val_iter,
optimizer='sgd',
optimizer_params = {'learning_rate':0.1},
eval_metric='acc',
batch_end_callback=mx.callback.Speedometer(100,100),
num_epoch=10) test_iter = mx.io.NDArrayIter(mnist['test_data'], None, batch_size)
prob = mynet_model.predict(test_iter)
test_iter = mx.io.NDArrayIter(mnist['test_data'], mnist['test_label'], batch_size)
# predict accuracy for lenet
acc = mx.metric.Accuracy()
mynet_model.score(test_iter, acc)
print(acc) # 网络是随便构建的,参数也是随便选的,所以出来的值并没有什么参考价值,只是为了验证调用mx.rtc创建cuda的kernel

因此,对于定制的层,可是使用类似的方法定义,该方法显然比使用numpy要快的多。