mxnet (gluon): cpu 在选择 gpu(0) 上下文时使用

mxnet (gluon): cpu used when gpu(0) context selected

编辑 02/2018 在使用本地存储的数据和不那么笨重的准确性度量计算编写自己的代码后,我发现速度显着提高。 GPU 还会在我尝试在 mxnet 中构建的任何 CNN 中冲洗 CPU;即使只是使用 MNIST。我相信我的问题与教程代码有关,不再认为这是一个真正的问题。

我 运行 通过了 http://gluon.mxnet.io/chapter03_deep-neural-networks/mlp-gluon.html

上的 'Multilayer perceptrons in gluon' MNIST 教程

(相同的代码,除了将上下文设置为 gpu(0),使用顺序模型)

我在 Windows 10。使用 python 3 (anaconda),安装了 CUDA 9.0,以及用于 9.0 的 cuDNN v7.0.5,然后 mxnet_cu90 从 pip 安装。

我将数据和模型上下文设置为 gpu(0),但我的 gtx 1080 徘徊在 1-4% 的使用率(无论脚本是否为 运行),而我的 8 个 Xeon 核心在加速到 50-60% 左右。无论上下文如何,训练时间都没有差异。当我在训练后打印参数时,它说它们是 NDArray size gpu(0),所以它肯定认为它正在使用 gpu.

编辑:在我家里的笔记本电脑上复制(GPU:GTX980m,cpu:I7 4710HQ)。在这种情况下,使用了 gpu:980m 每个时期的使用率从 0% 增加到 12%。然而,cpu 也使用了 >40% 的负载,而且 gpu 上下文训练实际上比 cpu.

我开始认为,因为这是 MNIST/ANN 的一个简单问题,所以 gpu 没有受到挑战。也许我会在训练 CNN 时看到 gpu 使用的更多影响。

虽然我仍然有点困惑,因为我在使用 TensorFlow 时从未遇到过这些问题;使用 gpu 通常总是优于我的 cpu.

感谢任何帮助, 谢谢, T.

编辑:要求的代码:

#MULTILAYER PERCEPTRONS IN GLUON (MNIST)
#MODIFIED FROM: http://gluon.mxnet.io/chapter03_deep-neural-networks/mlp-gluon.html

#IMPORT REQUIRED PACKAGES
import numpy as np
import mxnet as mx
from mxnet import nd, autograd, gluon
import datetime #for comparing training times

#SET THE CONTEXTS (GPU/CPU)
ctx = mx.gpu(0) #note: original tutorial sets separate context variable for data/model. The data_ctx was never used so i submitted an issue on github and use a single ctx here
#ctx = mx.cpu()

#PREDEFINE SOME USEFUL NUMBERS
batch_size = 64
num_inputs = 784
num_outputs = 10 #ten hand written digits [0-9]
num_examples = 60000

#LOAD IN THE MNIST DATASET
def transform(data, label):
    return data.astype(np.float32)/255, label.astype(np.float32)
train_data = mx.gluon.data.DataLoader(mx.gluon.data.vision.MNIST(train = True, transform = transform), batch_size, shuffle = True)
test_data = mx.gluon.data.DataLoader(mx.gluon.data.vision.MNIST(train = False, transform = transform), batch_size, shuffle = False)

#MAKE SEQUENTIAL MODEL

num_hidden = 64
net = gluon.nn.Sequential()
with net.name_scope():
    net.add(gluon.nn.Dense(num_hidden, activation = "relu"))
    net.add(gluon.nn.Dense(num_hidden, activation = "relu"))
    net.add(gluon.nn.Dense(num_outputs))

net.collect_params().initialize(mx.init.Normal(sigma = 0.01), ctx = ctx)

#SETUP THE FUNCTIONS FOR TRAINING

softmax_cross_entropy = gluon.loss.SoftmaxCrossEntropyLoss() #LOSS
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.01}) #OPTIMIZER

#DEFINE A LOOP TO TEST THE ACCURACY OF THE MODEL ON A TEST SET
def evaluate_accuracy(data_iterator, net):
    acc = mx.metric.Accuracy()
    for i, (data, label) in enumerate(data_iterator):
        data = data.as_in_context(ctx).reshape((-1,784))
        label = label.as_in_context(ctx)
        output = net(data)
        predictions = nd.argmax(output, axis = 1)
        acc.update(preds = predictions, labels = label)
    return acc.get()[1] #get the accuracy value from the mxnet accuracy metric

#TRAINING LOOP
epochs  = 10
smoothing_constant = 0.01
start_time = datetime.datetime.now()

for e in range(epochs):
    cumulative_loss = 0
    for i, (data, label) in enumerate(train_data):
        data = data.as_in_context(ctx).reshape((-1, 784))
        label = label.as_in_context(ctx)
        with autograd.record():
            output = net(data)
            loss = softmax_cross_entropy(output, label)
        loss.backward()
        trainer.step(data.shape[0])
        cumulative_loss += nd.sum(loss).asscalar()
    test_accuracy = evaluate_accuracy(test_data, net)
    train_accuracy = evaluate_accuracy(train_data, net)
    print("Epoch %s. Loss: %s, Train_acc %s, Test_acc %s" % (e, cumulative_loss/num_examples, train_accuracy, test_accuracy))

#I ADDED THIS TO GET THE FINAL PARAMETERS / NDARRAY CONTEXTS    
params = net.collect_params()
for param in params.values():
    print(param.name,param.data())

#I ADDED THIS TO COMPARE THE TIMING I GET WHEN SETTING THE CTX AS GPU/CPU   
end_time = datetime.datetime.now()
training_time = end_time - start_time
print("In h/m/s, total training time was: %s" % training_time)

CPU 上下文的结果: cmd output for params and total training time (cpu)

GPU 上下文的结果(实际上花费了更长的时间): cmd output for params and total training time (gpu)

有几件事影响了您的表现。

  1. 您的训练受 DataLoader 限制。使用 num_workers 来增加获取数据并将数据预处理到 NDArray 中的进程数,以确保您的 GPU 不会挨饿。例如train_data = mx.gluon.data.DataLoader(mx.gluon.data.vision.MNIST(train=True, transform=transform), batch_size, shuffle=True, num_workers=4)

  2. MXNet 中的内置指标目前效率低下,尤其是在批量大小非常小时。在分析训练循环(使用简单的 time())时,您会注意到大部分时间都花在了准确性计算上,而不是训练上。但是,这在真正的 DL 训练会话中通常不是问题,因为训练数据的大小通常远大于验证数据的大小,并且您通常不会像本教程中所示那样同时计算训练和验证的准确性。

但总的来说,您不会在 GPU 利用率方面获得巨大提升,因为教程网络和数据集非常简单。

虽然需要 Windows 机器,但如果您在 Colab 上遇到这样的问题(使用 GluonTS 时), pip install mxnet-cu101 会解决。