【发布时间】:2018-07-19 09:59:53
【问题描述】:
EDIT 02/2018 在使用存储在本地的数据和不那么笨拙的准确度指标计算编写自己的代码后,我发现速度有了显着提高。 GPU 还会在我尝试在 mxnet 中构建的任何 CNN 中冲洗 CPU;即使只是使用 MNIST。我相信我的问题与教程代码有关,不再认为这是一个真正的问题。
我正在阅读 http://gluon.mxnet.io/chapter03_deep-neural-networks/mlp-gluon.html 上的“胶子中的多层感知器”MNIST 教程
(相同的代码,除了将上下文设置为 gpu(0),使用顺序模型)
我在 Windows 10 中。使用 python 3 (anaconda),安装 CUDA 9.0 和 cuDNN v7.0.5 for 9.0,然后从 pip 安装 mxnet_cu90。
我将数据和模型上下文设置为 gpu(0),但我的 gtx 1080 使用率徘徊在 1-4% 左右(无论脚本是否正在运行),而我的 8 个 Xeon 内核上升到大约 50-60%通过时代。无论上下文如何,训练时间都没有差异。当我在训练后打印参数时,它说它们是 NDArray size gpu(0),所以它肯定认为它正在使用 gpu。
编辑:在我家的笔记本电脑上复制(gpu:GTX980m,cpu:I7 4710HQ)。在这种情况下,使用了 gpu:每个 epoch 使用 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)
【问题讨论】:
-
请向我们提供Minimal, Complete and Verifiable example,而不是链接和更改说明。现在有点郁闷
-
对不起,我是新手。目前正在尝试这样做。下班回来会贴代码
-
不,问题,欢迎加入社区
标签: python python-3.x mxnet cudnn