PowerAI 4.0에 포함된 DDL(Distributed Deep Learning)의 구체적인 사용법에 대해서 보시겠습니다.
일단 caffe는 IBM 버전 caffe (caffe-ibm)에 DDL 옵션이 통합되어 있으므로 별도 debian 패키지를 설치할 필요가 없습니다. 이 caffe-ibm도 내부적으로는 OpenMPI를 이용하는 것이므로 관련 library들이 설치되기는 해야 합니다만, 이는 caffe-ibm을 설치할 때 함께 자동으로 설치되므로 따로 신경쓰지 않으셔도 됩니다.
nimbix@JARVICENAE-0A0A1835:/data/mnist$ dpkg -l | grep openmpi
ii libopenmpi2-cuda:ppc64el 2.0.1-4ibm1 ppc64el high performance message passing library -- shared library
ii openmpi-bin-cuda 2.0.1-4ibm1 ppc64el high performance message passing library -- binaries
ii openmpi-common-cuda 2.0.1-4ibm1 all high performance message passing library -- common files
ii openmpi-doc-cuda 2.0.1-4ibm1 all high performance message passing library -- man pages
가령 위에서 보는 것과 같이 CUDA-aware OpenMPI를 설치하고나면, mpirun이라는 MPI utility가 설치됩니다. 이 mpirun이라는 것은 여러단계의 soft link가 걸린 orterun이라는 명령어이고, 결국 아래와 같이 openmpi-bin-cuda에서 제공됩니다.
nimbix@JARVICENAE-0A0A1835:/data/mnist$ dpkg -S /usr/bin/orterun
openmpi-bin-cuda: /usr/bin/orterun
IBM 버전 caffe에서의 DDL 사용법은 알고 보면 단순합니다. 다음 4가지만 아시면 됩니다.
1) caffe 명령을 수행할 때 -ddl 옵션을 준다
2) Train/Validation용 dataset은 모든 서버에서 동일한 위치(directory)에 존재해야 한다 (병렬파일시스템 또는 NFS가 편리)
3) 모든 서버는 암호 없이 ssh가 되도록 ssh-keygen과 ssh-copy-id가 되어 있어야 한다
4) 환경변수 등을 다른 서버 노드에도 전달하기 위해서는 mpirun 명령을 사용하는 것이 편하다
다른 것은 다 쉽습니다만 1)번 항목이 조금 어렵게 느껴질 수도 있습니다. 복잡한 부분은 다 빼고, 그냥 쉽게 보면 이렇습니다.
DDL 옵션을 쓴다고 해서 caffe가 여러분이 가진 GPU서버 및 network 환경을 스스로 이해하고 그에 맞게 자동으로 최적화할 수는 없습니다. 따라서 그런 환경, 즉 topology를 caffe에게 여러분이 직접 알려주셔야 합니다. 그게 -ddl 옵션의 mode입니다. 쉽게 예를 들어 설명하면 다음과 같습니다.
$ mpirun -x PATH -x LD_LIBRARY_PATH -n 12 -rf 4x3.rf caffe train -solver /data/mnist/lenet_solver.prototxt -gpu 0 -bvlc -ddl "-mode n:4x3x1 -dev_sync 1"
- mpirun은 여러대의 서버 노드에 동일한 명령을 동일한 환경변수 (-x 옵션)을 써서 수행해주는 병렬환경 명령어입니다.
- 4x3.rf라는 이름의 파일은 rank file입니다. 이 속에 병렬 서버 환경의 toplogy가 들어있습니다. 이걸 어떻게 만드는지는 아래에서 다루겠습니다.
- -n 12라는 것은 MPI client의 총 숫자이며, 쉽게 말해 training에 이용하려는 GPU의 갯수입니다.
- -gpu 0에서, 왜 12개가 아니라 gpu 0이라고 1개로 지정했는지 의아하실 수 있는데, MPI 환경에서는 각각의 GPU가 하나의 learner가 됩니다. 따라서 실제 물리적 서버 1대에 GPU가 몇 장 장착되어있든 상관없이 모두 -gpu 0, 즉 GPU는 1개로 지정한 것입니다.
- "-mode n:4x3x1"에서 n이라는 것은 NCCL (NVIDIA Collective Communications Library, 니클이라고 읽습니다)을 이용하라는 뜻입니다. 4x3x1은 4장의 GPU를 가진 서버 3대가 하나의 rack에 들어있다는 뜻입니다. 사실 어느 rack에 들어있느냐가 중요한 것은 아닌데, 보통 병렬수퍼컴 환경에서는 한대의 rack 안에 장착된 서버끼리는 좀더 고속의 low latency network으로 연결되어있기 때문에 이렇게 rack 표시까지 해주는 것입니다. 만약 4장의 GPU를 가진 서버가 6대씩 장착된 rack이 5대있다면 4x6x5로 표시됩니다.
- dev_sync에서 0은 GPU간 sync를 하지 말라는 것이고, 1은 통신 시작할 때 sync하라는 뜻, 2는 시작할 때와 끝낼 때 각각 sync하라는 뜻입니다.
잠깐, 데이터는 어디에 있는지 어떻게 지정하냐고요 ? 저 위에 지정된 solver 파일, 즉 lenet_solver.prototxt에 neural network이 지정되어 있고, 다시 그 neural network의 prototxt 파일 속에 데이터 위치가 지정되어 있습니다. 아래처럼요.
$ vi lenet_solver.prototxt
#net: "examples/mnist/lenet_train_test.prototxt"
net: "/data/mnist/lenet_train_test.prototxt"
$ vi lenet_train_test.prototxt
...
# source: "examples/mnist/mnist_train_lmdb"
source: "/data/mnist/mnist_train_lmdb"
...
# source: "examples/mnist/mnist_test_lmdb"
source: "/data/mnist/mnist_test_lmdb"
여러 서버 노드들의 GPU마다 수행될 learner들이 어떻게 data를 나누어 가져가느냐고요 ? 가급적이면 서버 노드마다 미리 파티셔닝되어 적절히 분배된 data들을 넣어두는 것이 좋습니다. Data를 N개의 learner들이 읽어갈 때, 각자 순차적으로 파일 이름들이 뒤섞여 들어간 목록으로부터 data를 읽어가는데, 만약 이 data가 물리적으로 미리 파티셔닝하여 노드 별로 분배해놓은 것이 아니라면 그냥 1번 training을 끝낼 때마다 전체 data를 N번 (N epochs) training한 것과 같은 효과를 냅니다. 저 data들의 저장소는 여러 노드에서 동시에 access할 수 있도록 IBM Spectrum Scale (구명칭 GPFS) 같은 병렬 파일시스템으로 하든가, 그게 없다면 성능이 떨어지더라도 NFS 같은 것으로 구성하는 것이 좋습니다.
이제 저 rf 파일, 즉 랭크 파일을 어떻게 만드는지 보시겠습니다. 그냥 손으로, 즉 vi 에디터 같은 것을 이용해서 만드셔도 됩니다만, PowerAI에서 기본 제공되는 rank_gen.py를 이용해서 다음과 같이 만드시는 것이 편합니다.
$ python /opt/DL/ddl/bin/rank_gen.py 4x2x3 sys-89074,sys-89075,sys-89076,sys-89077,sys-89078,sys-89079 > 4x2x3.rf
위에서 콤마(,)로 분리된 이름들이 서버 이름들입니다. 4x2x3이니 4장의 GPU를 가진 서버가 총 6대 있는 것이니, 서버 이름은 반드시 6대를 적으셔야 합니다. 이렇게 만들어진 4x2x3.rf 파일의 내용은 아래와 같습니다. rank_gen.py는 기본적으로 10-core POWER8 chip 2장을 장착한 Minsky 서버를 기준으로 만들기 때문에 아래와 같이 10개의 core를 가진 slot 2개가 있는 것으로 나옵니다. 그래서 rank, 즉 GPU 1개마다 slot이 5개 (0-4) 있는 것으로 나오는데, 만약 그게 아니라 8-core POWER8 chip이 장착된 서버라면 수작업으로 0-4가 아닌 0-3으로 수정해주셔야 합니다.
u0017649@sys-89075:~$ cat 4x2x3.rf
#2017-09-14 04:45:51 by rank_gen
#dims = 4x2x3
#host = sys-89074,sys-89075,sys-89076,sys-89077,sys-89078,sys-89079
#dimX = 4
#dimY = 2
#dimZ = 3
#sockets = 2
#cores = 10
rank 0=sys-89074 slot=0:0-4
rank 6=sys-89074 slot=0:5-9
rank 12=sys-89074 slot=1:0-4
rank 18=sys-89074 slot=1:5-9
rank 3=sys-89075 slot=0:0-4
rank 9=sys-89075 slot=0:5-9
rank 15=sys-89075 slot=1:0-4
rank 21=sys-89075 slot=1:5-9
rank 1=sys-89076 slot=0:0-4
rank 7=sys-89076 slot=0:5-9
rank 13=sys-89076 slot=1:0-4
rank 19=sys-89076 slot=1:5-9
rank 4=sys-89077 slot=0:0-4
rank 10=sys-89077 slot=0:5-9
rank 16=sys-89077 slot=1:0-4
rank 22=sys-89077 slot=1:5-9
rank 2=sys-89078 slot=0:0-4
rank 8=sys-89078 slot=0:5-9
rank 14=sys-89078 slot=1:0-4
rank 20=sys-89078 slot=1:5-9
rank 5=sys-89079 slot=0:0-4
rank 11=sys-89079 slot=0:5-9
rank 17=sys-89079 slot=1:0-4
rank 23=sys-89079 slot=1:5-9
Caffe는 그렇게 쉽게 됩니다만, tensorflow는 그보다 좀 어렵습니다. 일단 별도의 ddl-tensorflow라는 debian package가 PowerAI 4.0에 포함되어 있는데, 이는 사실 tensorflow DDL에 꼭 필요한 것이 아니라, tensorflow DDL을 좀더 쉽게 사용하실 수 있도록 해주는 Google Slim에 기반한 script들과 example 파일들을 제공해주는 것입니다. 정작 tensorflow는 별도로 설치하셔야 하는데, 물론 그건 PowerAI에서 제공되는 tensorflow를 apt-get install 명령으로 설치하시면 됩니다.
$ sudo apt-get install ddl-tensorflow tensorflow
$ dpkg -L ddl-tensorflow
/.
/opt
/opt/DL
/opt/DL/ddl-tensorflow
/opt/DL/ddl-tensorflow/examples
/opt/DL/ddl-tensorflow/examples/mnist
/opt/DL/ddl-tensorflow/examples/mnist/ddl_mnist.py
/opt/DL/ddl-tensorflow/examples/mnist/README.md
/opt/DL/ddl-tensorflow/examples/slim
/opt/DL/ddl-tensorflow/examples/slim/BUILD
/opt/DL/ddl-tensorflow/examples/slim/WORKSPACE
/opt/DL/ddl-tensorflow/examples/slim/scripts
/opt/DL/ddl-tensorflow/examples/slim/scripts/finetune_inception_resnet_v2_on_flowers.sh
/opt/DL/ddl-tensorflow/examples/slim/scripts/train_lenet_on_mnist.sh
/opt/DL/ddl-tensorflow/examples/slim/scripts/finetune_resnet_v1_50_on_flowers.sh
/opt/DL/ddl-tensorflow/examples/slim/scripts/finetune_inception_v3_on_flowers.sh
/opt/DL/ddl-tensorflow/examples/slim/scripts/train_cifarnet_on_cifar10.sh
/opt/DL/ddl-tensorflow/examples/slim/scripts/finetune_inception_v1_on_flowers.sh
/opt/DL/ddl-tensorflow/examples/slim/train-alexnet.sh
/opt/DL/ddl-tensorflow/examples/slim/deployment
/opt/DL/ddl-tensorflow/examples/slim/deployment/__init__.py
...
이 ddl-tensorflow를 사용하시기 위해서는 PYTHONPATH 등의 환경변수 설정을 위해 source 명령으로 아래와 같이 ddl-tensorflow-activate를 수행해주셔야 합니다.
$ source /opt/DL/ddl-tensorflow/bin/ddl-tensorflow-activate
이제 ddl-tensorflow-install-samples 명령을 사용하시어 지정하는 directory에 sample들을 설치하실 수 있습니다.
nimbix@JARVICENAE-0A0A1835:~$ ddl-tensorflow-install-samples /data
Write into existing directory /data? (yN)
y
Copying examples/ into /data...
Success
가장 간단한 것으로, 손글씨 숫자를 판독하는 MNIST가 들어 있습니다.
nimbix@JARVICENAE-0A0A1835:~$ cd /data/examples/mnist
nimbix@JARVICENAE-0A0A1835:/data/examples/mnist$ ls
ddl_mnist.py README.md
여기에 나온 것처럼, tensorflow는 명령어라기보다는 python에서 불러 사용하는 library로 되어 있기 때문에, 결국 multi-node 병렬처리를 하기 위해서는 python script를 위의 ddl_mnist.py에서처럼 작성해야 합니다.
일단 4-GPU 서버 2대(sys-89074와 sys-89075)로 수행하는 환경이라고 가정하고 아래와 같이 rank file을 먼저 만듭니다.
nimbix@JARVICENAE-0A0A1835:/data/examples/mnist$ python /opt/DL/ddl/bin/rank_gen.py 4x2x1 sys-89074,sys-89075 > 4x2.rf
nimbix@JARVICENAE-0A0A1835:/data/examples/mnist$ cat 4x2.rf
#2017-09-15 03:19:14 by rank_gen
#dims = 4x2x1
#host = sys-89074,sys-89075
#dimX = 4
#dimY = 2
#dimZ = 1
#sockets = 2
#cores = 10
rank 0=sys-89074 slot=0:0-4
rank 2=sys-89074 slot=0:5-9
rank 4=sys-89074 slot=1:0-4
rank 6=sys-89074 slot=1:5-9
rank 1=sys-89075 slot=0:0-4
rank 3=sys-89075 slot=0:5-9
rank 5=sys-89075 slot=1:0-4
rank 7=sys-89075 slot=1:5-9
이제 다음과 같이 수행하면 됩니다.
nimbix@JARVICENAE-0A0A1835:/data/examples/mnist$ mpirun -x PATH -x LD_LIBRARY_PATH -x PYTHONPATH -n 8 -rf 4x2.rf python ddl_mnist.py
(사실 mnist는 워낙 작은 dataset만 사용하므로, 병렬화의 의미가 없습니다. 그래서인지 ddl_mnist.py는 위에서 제가 예로 든 것처럼 4x2 구조는 애초에 불가능하고, 저 아래에 보시듯이 -mode r:2로 되어 있어 그냥 GPU 2장으로 병렬화하는 것만 가능합니다.)
결국 문제는 tensorflow를 병렬로 수행하기 위해서 python script를 어떻게 작성해야 하느냐인데, 이 부분에 대해서는 저도 개발자가 아닌 관계로 별 도움을 못 드리겠습니다. (사실 제겐 흰건 글씨요 검은건 공백이며, 깜빡이는 것은 커서 정도로만 보입니다.)
대신, 다소 깁니다만, 아래에 PowerAI에 포함된 ddl_mnist.py의 내용을 그대로 올려두겠습니다.
nimbix@JARVICENAE-0A0A1835:/data/examples/mnist$ vi ddl_mnist.py
import tensorflow as tf
import numpy as np
############################################################################
# IBM PowerAI Distributed Deep Learning (DDL) setup
############################################################################
# Disable GPU memory preallocation
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
############################################################################
# DDL Initialize BEGIN
############################################################################
# Load DDL operator
ddl = tf.load_op_library('/opt/DL/ddl-tensorflow/lib/ddl_MDR.so')
# DDL initializes MPI on CPU
# ddl.init takes two inputs
# 1) the number of GPUs to utilize on each host in training.
# this number is not the number of GPUs to use for each leaner. It simply tells DDL that there are X GPUs in each host to be used for training
# 2) DDL options (refer to README for details)
with tf.Session(config=config) as sess:
with tf.device('/cpu:0'):
rank, size, gpuid = sess.run(ddl.init(2, mode = '-mode r:2 -dump_iter 100'))
# MPI info and assigned GPU
print [rank, size, gpuid]
############################################################################
# DDL Initialize END
############################################################################
# Perform all TensorFlow computation within gpuid
with tf.device('/gpu:%d' %gpuid):
##############################################################################
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# Parameters
learning_rate = 0.001
training_iters = 200000
batch_size = 100
display_step = 1
# Network Parameters
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)
dropout = 0.75 # Dropout, probability to keep units
# tf Graph input
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)
# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
# MaxPool2D wrapper
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
padding='SAME')
# Create model
def conv_net(x, weights, biases, dropout):
# Reshape input picture
x = tf.reshape(x, shape=[-1, 28, 28, 1])
# Convolution Layer
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
# Max Pooling (down-sampling)
conv1 = maxpool2d(conv1, k=2)
# Convolution Layer
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
# Max Pooling (down-sampling)
conv2 = maxpool2d(conv2, k=2)
# Fully connected layer
# Reshape conv2 output to fit fully connected layer input
fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
# Apply Dropout
fc1 = tf.nn.dropout(fc1, dropout)
# Output, class prediction
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
return out
# Store layers weight & bias
weights = {
############################################################################
# DDL BROADCAST BEGIN
############################################################################
# This step ensures that all learners start with the same initial parameters
# 5x5 conv, 1 input, 32 outputs
'wc1': tf.Variable(ddl.bcast(tf.random_normal([5, 5, 1, 32]))),
# 5x5 conv, 32 inputs, 64 outputs
'wc2': tf.Variable(ddl.bcast(tf.random_normal([5, 5, 32, 64]))),
# fully connected, 7*7*64 inputs, 1024 outputs
'wd1': tf.Variable(ddl.bcast(tf.random_normal([7*7*64, 1024]))),
# 1024 inputs, 10 outputs (class prediction)
'out': tf.Variable(ddl.bcast(tf.random_normal([1024, n_classes])))
############################################################################
# DDL BROADCAST END
############################################################################
}
biases = {
'bc1': tf.Variable(ddl.bcast(tf.random_normal([32]))),
'bc2': tf.Variable(ddl.bcast(tf.random_normal([64]))),
'bd1': tf.Variable(ddl.bcast(tf.random_normal([1024]))),
'out': tf.Variable(ddl.bcast(tf.random_normal([n_classes])))
}
# Construct model
pred = conv_net(x, weights, biases, keep_prob)
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
############################################################################
# DDL ALLREDUCE BEGIN
############################################################################
# Collect the gradients and the corresponding parameters w.r.t the given cost
grads_and_vars = optimizer.compute_gradients(cost)
# Separate out the tuple
grads, vars = zip(*grads_and_vars)
# This step takes the average of the gradients on all the learners
grads_and_vars_ddl = zip(ddl.all_reduce_n(grads, op='avg'), vars)
# Update the parameters with the averaged gradient
objective = optimizer.apply_gradients(grads_and_vars_ddl)
############################################################################
# DDL ALLREDUCE END
############################################################################
# Evaluate model
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
##############################################################################
def split(a, n):
k, m = divmod(len(a), n)
return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(n))
# Launch the graph
with tf.Session(config=config) as sess:
sess.run(tf.global_variables_initializer())
step = 1
# Keep training until reach max iterations
while step * batch_size < training_iters:
# Each learner will read batch_size*size samples and
# use only the portion correspoding to the current learner (or rank)
batch_x, batch_y = mnist.train.next_batch(batch_size*size)
batch_x = np.split(batch_x,size)[rank]
batch_y = np.split(batch_y,size)[rank]
# Run optimization op (backprop)
sess.run(objective, feed_dict={x: batch_x, y: batch_y,
keep_prob: dropout})
if step % display_step == 0:
# Calculate batch loss and accuracy
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
y: batch_y,
keep_prob: 1.})
print("MPI "+str(rank)+"] Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
"{:.6f}".format(loss) + ", Training Accuracy= " + \
"{:.5f}".format(acc))
step += 1
print("MPI "+str(rank)+"] Optimization Finished!")
# Calculate accuracy for 256 mnist test images
print("MPI "+str(rank)+"] Testing Accuracy:", \
sess.run(accuracy, feed_dict={x: mnist.test.images[:256],
y: mnist.test.labels[:256],
keep_prob: 1.}))
2017년 9월 15일 금요일
Minsky 서버에 Anaconda installer의 full package 설치하기
올 3월까지만 해도 Continuum사의 Anaconda installer가 Minsky의 아키텍처인 ppc64le 환경에서는 full package로는 없었고, Miniconda installer만 있었습니다. 그런데 그 사이에 ppc64le용 Anaconda installer의 full package가 이미 나왔네요.
https://repo.continuum.io/archive/
Filename Size Last Modified MD5
Anaconda2-4.4.0.1-Linux-ppc64le.sh 271.4M 2017-07-26 16:10:02 ce166de6f116acd08cd313f9c55c04d6
Anaconda3-4.4.0.1-Linux-ppc64le.sh 285.6M 2017-07-26 16:08:42 fe7c87abd9fd70dc0cb4f83cc22d336f
설치는 아래와 같이 하시면 됩니다. Python2.7 환경에서는 아래와 같이 Anaconda2-4.4.0.1-Linux-ppc64le.sh를 받으시면 되고, Python3 환경에서는 Anaconda3-4.4.0.1-Linux-ppc64le.sh를 받으시면 됩니다. 일단 둘다 받아서 설치하시는 것이 좋습니다. 여기서는 Anaconda2에 대한 부분만 써놓습니다.
u0017649@sys-89075:~$ wget https://repo.continuum.io/archive/Anaconda2-4.4.0.1-Linux-ppc64le.sh
--2017-09-14 21:42:44-- https://repo.continuum.io/archive/Anaconda2-4.4.0.1-Linux-ppc64le.sh
Resolving repo.continuum.io (repo.continuum.io)... 104.16.18.10, 104.16.19.10, 2400:cb00:2048:1::6810:120a, ...
Connecting to repo.continuum.io (repo.continuum.io)|104.16.18.10|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 284629257 (271M) [application/x-sh]
Saving to: ‘Anaconda2-4.4.0.1-Linux-ppc64le.sh’
Anaconda2-4.4.0.1-L 100%[===================>] 271.44M 16.7MB/s in 17s
2017-09-14 21:43:01 (16.4 MB/s) - ‘Anaconda2-4.4.0.1-Linux-ppc64le.sh’ saved [284629257/284629257]
여러 user가 함께 쓰는 서버 환경에 Anaconda를 설치할 때는, 해당 user의 home directory에 설치하면 다른 user들이 쓸 수가 없지요. 따라서 일단은 /opt/anaconda2에 설치해놓고 user별로 clone을 해서 사용하시는 것이 좋습니다. 물론 /opt directory에 설치하려면 sudo 권한이 있어야 합니다.
u0017649@sys-89075:~$ chmod u+x Anaconda2-4.4.0.1-Linux-ppc64le.sh
u0017649@sys-89075:~$ sudo ./Anaconda2-4.4.0.1-Linux-ppc64le.sh
Do you approve the license terms? [yes|no]
>>> yes
Anaconda2 will now be installed into this location:
/home/u0017649/anaconda2
- Press ENTER to confirm the location
- Press CTRL-C to abort the installation
- Or specify a different location below
[/home/u0017649/anaconda2] >>> /opt/anaconda2
...
installing: zict-0.1.2-py27_0 ...
installing: zlib-1.2.8-3 ...
installing: anaconda-4.4.0-np112py27_0 ...
installing: conda-4.3.21-py27_0 ...
installing: conda-env-2.6.0-0 ...
Python 2.7.13 :: Continuum Analytics, Inc.
creating default environment...
installation finished.
Do you wish the installer to prepend the Anaconda2 install location
to PATH in your /home/u0017649/.bashrc ? [yes|no]
[no] >>> yes
Prepending PATH=/opt/anaconda2/bin to PATH in /home/u0017649/.bashrc
A backup will be made to: /home/u0017649/.bashrc-anaconda2.bak
For this change to become active, you have to open a new terminal.
Thank you for installing Anaconda2!
Share your notebooks and packages on Anaconda Cloud!
Sign up for free: https://anaconda.org
이제 환경변수를 적용하고, conda install을 해봅니다.
u0017649@sys-89075:~$ . ./.bashrc
u0017649@sys-89075:~$ env | grep PATH
PATH=/opt/anaconda2/bin:/home/u0017649/bin:/home/u0017649/.local/bin:/opt/ibm/xlC/current/bin:/opt/ibm/xlf/current/bin:/opt/at10.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
u0017649@sys-89075:~$ conda install scikit-learn
Fetching package metadata .........
Solving package specifications: .
Package plan for installation in environment /opt/anaconda2:
The following packages will be UPDATED:
scikit-learn: 0.18.1-np112py27_1 --> 0.19.0-np112py27_0
Proceed ([y]/n)? y
CondaIOError: Missing write permissions in: /opt/anaconda2
#
# You don't appear to have the necessary permissions to install packages
# into the install area '/opt/anaconda2'.
# However you can clone this environment into your home directory and
# then make changes to it.
# This may be done using the command:
#
# $ conda create -n my_root --clone="/opt/anaconda2"
보시다시피 /opt/anaconda2에 대해서 일반 user들은 write 권한이 없기 때문에 error가 납니다. 그래서 각 user별로 cloning을 해서 사용하는 것입니다. 아래와 같이 하시면 됩니다.
u0017649@sys-89075:~$ conda create -n anaconda2 --clone="/opt/anaconda2"
Source: /opt/anaconda2
Destination: /home/u0017649/.conda/envs/anaconda2
The following packages cannot be cloned out of the root environment:
- conda-4.3.21-py27_0
- conda-env-2.6.0-0
Packages: 186
Files: 11
#
# To activate this environment, use:
# > source activate anaconda2
#
# To deactivate this environment, use:
# > source deactivate anaconda2
#
이제 cloning 환경으로 들어가서 위에서 실패했던 scikit-learn 패키지의 설치를 다시 해보겠습니다.
u0017649@sys-89075:~$ source activate anaconda2
(anaconda2) u0017649@sys-89075:~$ conda install scikit-learn
이건 잘 됩니다. 이것이 잘 되는 이유는 다음과 같이 각 user의 home directory 밑인 ~/.conda/envs에 cloning을 해놓고 쓰기 때문입니다. 물론 이는 disk 저장공간을 사용하는 작업이므로, 많은 user들이 각자 모두 cloning을 할 경우 disk 공간의 낭비가 꽤 있게 되는 문제가 있긴 합니다. 가령 Anaconda2를 1번 clone할 때마다 약 1.1 GB의 공간이 소모됩니다. 따라서 모든 user가 일괄적으로 이렇게 cloning을 할 필요는 없고, 정말 꼭 자신만의 변경된 package 환경을 가져야 할 경우에만 하실 것을 권고합니다.
(anaconda2) u0017649@sys-89075:~/.conda/envs/anaconda2$ du -sm .
1135 .
https://repo.continuum.io/archive/
Filename Size Last Modified MD5
Anaconda2-4.4.0.1-Linux-ppc64le.sh 271.4M 2017-07-26 16:10:02 ce166de6f116acd08cd313f9c55c04d6
Anaconda3-4.4.0.1-Linux-ppc64le.sh 285.6M 2017-07-26 16:08:42 fe7c87abd9fd70dc0cb4f83cc22d336f
설치는 아래와 같이 하시면 됩니다. Python2.7 환경에서는 아래와 같이 Anaconda2-4.4.0.1-Linux-ppc64le.sh를 받으시면 되고, Python3 환경에서는 Anaconda3-4.4.0.1-Linux-ppc64le.sh를 받으시면 됩니다. 일단 둘다 받아서 설치하시는 것이 좋습니다. 여기서는 Anaconda2에 대한 부분만 써놓습니다.
u0017649@sys-89075:~$ wget https://repo.continuum.io/archive/Anaconda2-4.4.0.1-Linux-ppc64le.sh
--2017-09-14 21:42:44-- https://repo.continuum.io/archive/Anaconda2-4.4.0.1-Linux-ppc64le.sh
Resolving repo.continuum.io (repo.continuum.io)... 104.16.18.10, 104.16.19.10, 2400:cb00:2048:1::6810:120a, ...
Connecting to repo.continuum.io (repo.continuum.io)|104.16.18.10|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 284629257 (271M) [application/x-sh]
Saving to: ‘Anaconda2-4.4.0.1-Linux-ppc64le.sh’
Anaconda2-4.4.0.1-L 100%[===================>] 271.44M 16.7MB/s in 17s
2017-09-14 21:43:01 (16.4 MB/s) - ‘Anaconda2-4.4.0.1-Linux-ppc64le.sh’ saved [284629257/284629257]
여러 user가 함께 쓰는 서버 환경에 Anaconda를 설치할 때는, 해당 user의 home directory에 설치하면 다른 user들이 쓸 수가 없지요. 따라서 일단은 /opt/anaconda2에 설치해놓고 user별로 clone을 해서 사용하시는 것이 좋습니다. 물론 /opt directory에 설치하려면 sudo 권한이 있어야 합니다.
u0017649@sys-89075:~$ chmod u+x Anaconda2-4.4.0.1-Linux-ppc64le.sh
u0017649@sys-89075:~$ sudo ./Anaconda2-4.4.0.1-Linux-ppc64le.sh
Do you approve the license terms? [yes|no]
>>> yes
Anaconda2 will now be installed into this location:
/home/u0017649/anaconda2
- Press ENTER to confirm the location
- Press CTRL-C to abort the installation
- Or specify a different location below
[/home/u0017649/anaconda2] >>> /opt/anaconda2
...
installing: zict-0.1.2-py27_0 ...
installing: zlib-1.2.8-3 ...
installing: anaconda-4.4.0-np112py27_0 ...
installing: conda-4.3.21-py27_0 ...
installing: conda-env-2.6.0-0 ...
Python 2.7.13 :: Continuum Analytics, Inc.
creating default environment...
installation finished.
Do you wish the installer to prepend the Anaconda2 install location
to PATH in your /home/u0017649/.bashrc ? [yes|no]
[no] >>> yes
Prepending PATH=/opt/anaconda2/bin to PATH in /home/u0017649/.bashrc
A backup will be made to: /home/u0017649/.bashrc-anaconda2.bak
For this change to become active, you have to open a new terminal.
Thank you for installing Anaconda2!
Share your notebooks and packages on Anaconda Cloud!
Sign up for free: https://anaconda.org
이제 환경변수를 적용하고, conda install을 해봅니다.
u0017649@sys-89075:~$ . ./.bashrc
u0017649@sys-89075:~$ env | grep PATH
PATH=/opt/anaconda2/bin:/home/u0017649/bin:/home/u0017649/.local/bin:/opt/ibm/xlC/current/bin:/opt/ibm/xlf/current/bin:/opt/at10.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
u0017649@sys-89075:~$ conda install scikit-learn
Fetching package metadata .........
Solving package specifications: .
Package plan for installation in environment /opt/anaconda2:
The following packages will be UPDATED:
scikit-learn: 0.18.1-np112py27_1 --> 0.19.0-np112py27_0
Proceed ([y]/n)? y
CondaIOError: Missing write permissions in: /opt/anaconda2
#
# You don't appear to have the necessary permissions to install packages
# into the install area '/opt/anaconda2'.
# However you can clone this environment into your home directory and
# then make changes to it.
# This may be done using the command:
#
# $ conda create -n my_root --clone="/opt/anaconda2"
보시다시피 /opt/anaconda2에 대해서 일반 user들은 write 권한이 없기 때문에 error가 납니다. 그래서 각 user별로 cloning을 해서 사용하는 것입니다. 아래와 같이 하시면 됩니다.
u0017649@sys-89075:~$ conda create -n anaconda2 --clone="/opt/anaconda2"
Source: /opt/anaconda2
Destination: /home/u0017649/.conda/envs/anaconda2
The following packages cannot be cloned out of the root environment:
- conda-4.3.21-py27_0
- conda-env-2.6.0-0
Packages: 186
Files: 11
#
# To activate this environment, use:
# > source activate anaconda2
#
# To deactivate this environment, use:
# > source deactivate anaconda2
#
이제 cloning 환경으로 들어가서 위에서 실패했던 scikit-learn 패키지의 설치를 다시 해보겠습니다.
u0017649@sys-89075:~$ source activate anaconda2
(anaconda2) u0017649@sys-89075:~$ conda install scikit-learn
이건 잘 됩니다. 이것이 잘 되는 이유는 다음과 같이 각 user의 home directory 밑인 ~/.conda/envs에 cloning을 해놓고 쓰기 때문입니다. 물론 이는 disk 저장공간을 사용하는 작업이므로, 많은 user들이 각자 모두 cloning을 할 경우 disk 공간의 낭비가 꽤 있게 되는 문제가 있긴 합니다. 가령 Anaconda2를 1번 clone할 때마다 약 1.1 GB의 공간이 소모됩니다. 따라서 모든 user가 일괄적으로 이렇게 cloning을 할 필요는 없고, 정말 꼭 자신만의 변경된 package 환경을 가져야 할 경우에만 하실 것을 권고합니다.
(anaconda2) u0017649@sys-89075:~/.conda/envs/anaconda2$ du -sm .
1135 .
2017년 9월 13일 수요일
IBM PowerAI 4.0에 포함된 Caffe Distributed Deep Learning (DDL)
Tensorflow는 distributed tensorflow를 예전부터 지원하여, 여러대의 서버에 장착된 여러장의 GPU를 이용한 분산 training이 가능했습니다. IBM PowerAI toolkit에도 ddl-tensorflow가 포함되어 있습니다.
Caffe는 tensorflow와는 달리 분산 모델이 정식으로는 지원되지 않아 한대의 서버에서만 training이 가능했습니다. 물론 각 기업이나 연구소별로 open source로 공개되지 않은 자체적인 버전의 distributed caffe를 자체 개발하여 사용하고 있긴 했습니다.
최근 새로 나온 IBM PowerAI 4.0에 포함된 IBM 버전의 caffe에서는 Distributed Deep Learning (DDL) 옵션을 지원합니다. 이는 OpenMPI 기술에 기반하여 caffe가 하나의 큰 모델을 여러대의 서버에서 분산 처리할 수 있도록 만든 것입니다.
구체적으로는 caffe 명령어에 -ddl 옵션이 추가된 형태로 제공됩니다. 구체적인 내용은 아래 link에 설명되어 있습니다.
https://public.dhe.ibm.com/software/server/POWER/Linux/mldl/ubuntu/README.html
문제는 여기에 설명되는 option parameter들에 대해, 충분한 설명이 없다는 것입니다. 가령 -ddl "-mode b:4x3"이라고 쓸 때, b는 뭐고 4는 무엇이며 3은 무엇인지 위 link만 보고는 알기가 어렵습니다.
-ddl "-mode b:4x3"를 설명하자면 b는 enhanced NCCL library를 쓰되, 4장의 GPU를 장착한 서버 3대를 쓰라는 것입니다.
또 가령 -ddl "-mode r:2x8"이라는 것은 RING 구성만 써서 2장의 GPU를 장착한 서버 8대를 쓰라는 것이고요.
이에 대해서 설명이 없는 이유를 IBM 본사에 물어보니, "인터넷에는 없지만 PowerAI 4.0을 설치하면 민스키 서버 안에 생성되는 /opt/DL/ddl/doc/README.md 파일 속에 설명이 다 들어있다" 라고 합니다.
해서, 많은 분들이 쉽게 보실 수 있도록 제가 여기에 그 파일 내용을 올려둡니다.
# Overview
IBM PowerAI Distributed Deep Learning (or DDL) is a MPI-based
communication library, which is specifically optimized for Deep Learning
training. An application integrated with DDL becomes a MPI-application,
which will allow the use of the `mpirun` command to invoke the job in
parallel across a cluster of systems. DDL understands multi-tier network
environment and uses different libraries (e.g. NCCL) and algorithms to
get the best performance in multi-node, multi-GPU environments.
IBM PowerAI Distributed Deep Learning considers each GPU in a cluster as
an individual "learner". The overall set of learners is described to
IBM PowerAI Distributed Deep Learning in terms of 3 dimensions (X-Y-Z)
that correspond to a multi-tier network hierarchy. The recommended
mapping is:
- X for within-host (e.g. number of GPUs per host for multi-GPU hosts)
- Y for between nearby-hosts (e.g. number of hosts in a single rack)
- Z for between distant-hosts (e.g. number of racks)
For example, 256 learners can be configured as 4x8x8 or 4x16x4 and so on.
**Example: 2 racks of 8 S822LC for HPC systems with 4 GPUs each**
In this setup, there are 64 learners (4 GPUs in each of 8 hosts in each
of 2 racks) and a simple description would be 4x8x2.
If this configuration includes a truly hierarchical network setup--for
example a high-speed, low-latency network within each rack, and a
slower, higher-latency network between the racks--then 4x8x2 might be
the optimal description.
But if the network configuration is not actually hierarchical--if all
the hosts are connected to a "flat" network regardless of the physical
racking--then a 4x4x4 description may perform better than 4x8x2. Some
experimentation may be needed to find the optimal description.
# Required Libraries
Pre-requisite packages required for IBM PowerAI Distributed Deep
Learning are provided with PowerAI:
1. OpenMPI with CUDA Support
2. NVIDIA NCCL
# Integration with Caffe and TensorFlow
IBM PowerAI Distributed Deep Learning has been integrated with the
PowerAI IBM Caffe and TensorFlow packages. `mpirun` must be used to
launch training using the IBM PowerAI Distributed Deep Learning
integration. General information about `mpirun` is available on the
OpenMPI website
[https://www.open-mpi.org/doc/v2.0/man1/mpirun.1.php](https://www.open-mpi.org/doc/v2.0/man1/mpirun.1.php).
1. Caffe
IBM PowerAI Distributed Deep Learning is directly integrated into
Caffe, and can be exercised by adding the following to the command line.
-ddl ?쏡DL_OPTIONS HERE??
2. TensorFlow
DDL is indirectly integrated into TensorFlow in the form of custom
operator. The custom operator is provided as a shared library, which is
loaded and invoked in the python training script.
The PowerAI ddl-tensorflow package provides an example training
setup based on the TensorFlow-Slim model library from the TensorFlow
models repository. Those can be found on your system in:
/opt/DL/ddl-tensorflow/examples/
More details on IBM PowerAI Distributed Deep Learning integration
into TensorFlow, can be found in
/opt/DL/ddl-tensorflow/doc/README.md
# Using IBM PowerAI Distributed Deep Learning
IBM PowerAI Distributed Deep Learning takes advantage of the network
topology to perform communication quickly. Network topology is described
to IBM PowerAI Distributed Deep Learning in two ways, through an MPI
rank file and via DDL options.
## MPI rank file
A rank file is a standard file that maps MPI clients (IBM PowerAI
Distributed Deep Learning learners) to specific hosts, sockets, and
cores. To get the best performance from IBM PowerAI Distributed Deep
Learning , it is crucial to generate an optimally mapped rank file. To
help with this effort, a script (`rank_gen.py`) is provided to
automatically generate rank files that are appropriate for most S822LC
systems. The script takes two inputs: the network decomposition and a
list of comma-separated hostnames.
**How to use rank file generator script**
$ python rank_gen.py XxYxZ host_list > rank_file
Here, `XxYxZ` specifies the topology of the GPU and multi-tier network
hierarchy.
For example, for 64 learners (e.g. 16 hosts each with 4 GPUs), any of
4x16x1, 4x8x2, or 4x4x4 might be reasonable choices, depending on the
network topology. All 3 dimensions must be specificed (use 1 to fill any
spaces).
`host_list` is a comma separated list of host names (e.g.
host1,host2,host3,...). It must contain `Y` times `Z` hostnames,
ordered "by Z". For example, a 4x2x2 configuration with 2 racks of 2
hosts each might have a host list of: `r1h1,r1h2,r2h1,r2h2`.The
hostnames provided in the rankfile should match the system hostnames.
It is possible in a distributed environment to have more than one
interface for each host. In such a scenario, OpenMPI by default, uses
any and all interfaces that are "up" to communicate with a host. To
avoid problems in such cases you can tell OpenMPI to use given
interface. E.g.:
$ mpirun --mca btl_tcp_if_include ib0 ...
$ mpirun --mca btl_tcp_if_exclude lo,enp1s0f2 ...
More details available on OpenMPI FAQ page:
[https://www.open-mpi.org/faq/?category=tcp#tcp-selection]([https://www.open-mpi.org/faq/?category=tcp#tcp-selection)
**Parameters for optimal rankfile**
An optimal rank file will depend on the number of sockets or nodes in
the system and the number of cores per socket/node. The `numactl` and
`ppc64_cpu` commands can help determine this information.
1. Number of sockets and thread slots for each socket.
`numactl -H` shows the number of sockets ("nodes") in a system,
and also lists the CPUs (thread slots) for each. For example:
$ numactl -H
available: 2 nodes (0-1)
node 0 cpus: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
node 0 size: 261788 MB
node 0 free: 6042 MB
node 1 cpus: 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
node 1 size: 261334 MB
node 1 free: 158805 MB
node distances:
node 0 1
0: 10 40
1: 40 10
Here the system has two sockets with 80 thread slots each.
2. Mapping between physical cores and CPUs/thread slots.
$ ppc64_cpu --info
Core 0: 0* 1* 2* 3* 4* 5* 6* 7*
Core 1: 8* 9* 10* 11* 12* 13* 14* 15*
Core 2: 16* 17* 18* 19* 20* 21* 22* 23*
Core 3: 24* 25* 26* 27* 28* 29* 30* 31*
Core 4: 32* 33* 34* 35* 36* 37* 38* 39*
Core 5: 40* 41* 42* 43* 44* 45* 46* 47*
Core 6: 48* 49* 50* 51* 52* 53* 54* 55*
Core 7: 56* 57* 58* 59* 60* 61* 62* 63*
Core 8: 64* 65* 66* 67* 68* 69* 70* 71*
Core 9: 72* 73* 74* 75* 76* 77* 78* 79*
Core 10: 80* 81* 82* 83* 84* 85* 86* 87*
Core 11: 88* 89* 90* 91* 92* 93* 94* 95*
Core 12: 96* 97* 98* 99* 100* 101* 102* 103*
Core 13: 104* 105* 106* 107* 108* 109* 110* 111*
Core 14: 112* 113* 114* 115* 116* 117* 118* 119*
Core 15: 120* 121* 122* 123* 124* 125* 126* 127*
Core 16: 128* 129* 130* 131* 132* 133* 134* 135*
Core 17: 136* 137* 138* 139* 140* 141* 142* 143*
Core 18: 144* 145* 146* 147* 148* 149* 150* 151*
Core 19: 152* 153* 154* 155* 156* 157* 158* 159*
Here the system has 20 physical cores with 8 thread slots/CPUs each. The
thread slot numbers match with the numbers in the `numactl` output. The
asterisks indicate which thread slots are enabled.
The rankfile only cares about cores (not CPUs/thread slots), and the
core numbering is relative to the to the node/socket (which is named
"slot" in the rankfile). So in rank file terms, this system has socket 0
cores 0-9 and socket 1 cores 0-9.
**Note:** If the number of cores specified in the rankfile exceeds the
actual number of cores, `mpirun` will fail with a non-obvious message.
For example, on a machine with 8-cores per socket:
$ cat 2x10core.rf
rank 0=host1 slot=0:0-9
rank 1=host1 slot=1:0-9
$ mpirun -n 2 -rf 2x10core.rf /bin/true
[host1:46256] [[20503,0],0] ORTE_ERROR_LOG: Not found in file rmaps_rank_file.c at line 320
[host1:46256] [[20503,0],0] ORTE_ERROR_LOG: Not found in file base/rmaps_base_map_job.c at line 351
$
Versus the working:
$ cat 2x8core.rf
rank 0=host1 slot=0:0-7
rank 1=host1 slot=1:0-7
$ mpirun -n 2 -rf 2x8core.rf /bin/true
$
The `-report-bindings` flag may be useful for diagnosing problems:
$ mpirun -report-bindings ......
## DDL options
There are a number of runtime options for the DDL engine. The options are:
`-mode`: This optionally indicates the algorithm and topology. The topology
should match to the rank assignment (e.g. via rankfile) to get the best
performance. If a mode is not provided, it will work as a single ring
configuration (e.g., r:N). Therefore, the total number of MPI clients
(specified as -n N to mpirun) must match with the number of learners in the
topology (specified as -mode in DDL): otherwise, it will show an error like
`invalid dim size=A usr_size=B dim[0]=...`
b:4x2 => use enhanced NCCL whenever possible (otherwise use ring) for 4x2 configuration
n:4x2 => use NCCL whenever possible (otherwise use ring) for 4x2 configuration
r:4x4 => use only RING for 4x4 configuration
m:4x6 => use only MPI reduce_scatter and all_gatherV for 4x6 configuration (currently disabled)
c:4x8 => use only RCS for 4x8 configuration
p:4x16x4 => first activate ex"p"location mode to get the best algorithms for each dimension of 4x16x4
`-dump_iter <N>`: This optionally makes DDL dump network performance on
every N iterations
`-dev_sync <0, 1, or 2>` : This optionally calls cudaDeviceSynchronize
to minimize jitter, default is 0 (which means off). With 1, it
invokes sync once in the beginning of communication. With 2, it invokes
sync twice in the beginning AND end of communication
`-rebind_iter <N>`: This optionally monitors variation every N
iterations, and performs rebind if a leaner has been slow for the last 3
checks. Too small number will incur variation-check overhead, but too
big number will make training suffer from variation for long time
`-dbg_level <0,1,2>`: 0 for no, 1 for mild, and 2 for detailed debug
messages
When `dump_iter` is given, you can see the following periodically where
you can find which learner has the maximum jitter and end to end DDL
elapsed time. Also, per dimension, it shows runtime breakdown along with
the selected algorithm for that particular dimension.

**Example of 2 racks of 8 S822LC HPC systems with 4 GPUs on each host**
Generate an appropriate rank file:
$ python rank_gen.py 4x8x2 host0,host1,host2,??,host15 > 4x8x2.rf
To start IBM Caffe with `mpirun`, specifying rank file and DDL options:
$ source /opt/DL/caffe/bin/caffe-activate
$ mpirun -x PATH -x LD_LIBRARY_PATH -n 16 -rf 4x8x2.rf caffe train -solver solver.prototxt -gpu 0 -bvlc -ddl "-mode b:4x8x2 -dump_iter 100"
To start TensorFlow with `mpirun` using custom operator for DDL:
- Update `train_image_classifier.py` to specify DDL options during
initialization:
ddl.Init(4, mode =??mode b:4x8x2 -dump_iter 100??
- Execute with `mpirun`:
$ source /opt/DL/ddl-tensorflow/bin/ddl-tensorflow-activate
$ mpirun -x PATH -x LD_LIBRARY_PATH -x PYTHONPATH -n 16 -rf 4x8.2.rf python train_image_classifier.py ...
Inference 시스템을 위한 GPU 용량 sizing, 그리고 IBM caffe의 Large Model Support (LMS) 옵션
오늘은 inference, 그 중에서도 inference를 위한 GPU 시스템의 sizing을 어떻게 해야 하는지에 대해서 보겠습니다. 여기서는 특정적으로, caffe를 이용하여 image data를 inference할 때 어떻게 하는지를 보겠습니다. 그리고 덧붙여, IBM Minsky 서버에서만 가능한 옵션, -lms (Large Model Support)가 어떤 혜택을 주는지도 보시겠습니다.
이에 대해서는 아래 site에 기본적인 방법이 소개됩니다. IBM China의 Deep Learning 개발팀의 박사님들에게 물어보니, 이 방법이 맞다고 합니다.
https://stackoverflow.com/questions/36867591/how-to-estimate-inference-time-from-average-forward-pass-time-in-caffe
여기서 핵심적인 부분은 바로 아래 부분입니다.
For instance, if I run the default command that comes with Caffe:
build/tools/caffe time --model=models/bvlc_alexnet/deploy.prototxt --gpu=0
I get the following output
...
I0426 13:07:32.701490 30417 layer_factory.hpp:77] Creating layer data
I0426 13:07:32.701513 30417 net.cpp:91] Creating Layer data
I0426 13:07:32.701529 30417 net.cpp:399] data -> data
I0426 13:07:32.709048 30417 net.cpp:141] Setting up data
I0426 13:07:32.709079 30417 net.cpp:148] Top shape: 10 3 227 227 (1545870)
I0426 13:07:32.709084 30417 net.cpp:156] Memory required for data: 6183480
...
I0426 13:07:34.390281 30417 caffe.cpp:377] Average Forward pass: 16.7818 ms.
I0426 13:07:34.390290 30417 caffe.cpp:379] Average Backward pass: 12.923 ms.
I0426 13:07:34.390296 30417 caffe.cpp:381] Average Forward-Backward: 29.7969 ms.
The following line:
I0426 13:07:32.709079 30417 net.cpp:148] Top shape: 10 3 227 227 (1545870)
is super important. It says that your input layer is 10x3x227x227-dimensional. In this case, the batch size is 10 images, each of size 3x227x227 (the 3 refers to each of the rgb channels in an image).
So effectively, it took 1.67818 ms/image to do a forward pass or inference time per image.
즉, caffe 명령어의 sub-comand 중 time 명령, 즉 caffe를 이용한 성능 benchmark 결과에서 평균 forward pass에 걸린 시간이 해당 model과 해당 이미지에 대해서 걸릴 inference time이라는 것입니다. 당연한 이야기지만 해당 model에 지정하는 data layer의 Top shape 10 3 227 227, 즉 batch size 10 x channel (RGB) 3 x height 227 x width 227이 클 수록 더 많은 시간이 걸립니다.
HPC cloud 서비스 업체인 Nimbix (nimbix.net/powerai)에서 제공하는 Minsky 서버의 P100 1장짜리 가상머신을 사용할 기회가 있어, 거기에서 이 test를 해봤습니다. 참고로 Nimbix는 docker 기반의 NVLink P100 GPU 가상 머신을 제공하는데, 이에 대해서도 나중에 다룰 기회가 있을 것입니다.
먼저, 1200x1200 크기의 이미지 1장에 대해서 GoogleNet으로 inference하는데 NVLink P100으로는 시간이 얼마나 걸리는지 보시겠습니다. 이를 위해서 먼저 GoogleNet에 포함된 deploy.prototxt를 아래와 같이 편집합니다. 원본 line은 아래에 #으로 comment-out 처리했습니다.
nimbix@JARVICENAE-0A0A1844:/data$ vi bvlc_googlenet/deploy.prototxt
name: "GoogleNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 1 dim: 3 dim: 1200 dim: 1200 } }
# input_param { shape: { dim: 10 dim: 3 dim: 224 dim: 224 } }
}
이제 이렇게 수정된 model로 caffe time을 수행합니다.
nimbix@JARVICENAE-0A0A1844:/data$ caffe time -gpu 0 -model=/data/bvlc_googlenet/deploy.prototxt --iterations=1
그 과정을 다 보실 필요는 없고, 사실 맨 끝의 benchmark 결과에서 Average Forward pass 시간만 보시면 됩니다.
I0908 05:39:36.830621 567 caffe.cpp:513] prob forward: 0.020864 ms.
I0908 05:39:36.830627 567 caffe.cpp:516] prob backward: 0.00368 ms.
I0908 05:39:36.830641 567 caffe.cpp:521] Average Forward pass: 45.3671 ms.
I0908 05:39:36.830649 567 caffe.cpp:523] Average Backward pass: 102.551 ms.
I0908 05:39:36.830657 567 caffe.cpp:525] Average Forward-Backward: 150.178 ms.
I0908 05:39:36.830673 567 caffe.cpp:527] Total Time: 150.178 ms.
I0908 05:39:36.830689 567 caffe.cpp:528] *** Benchmark ends ***
여기서 만약 우리가 batch size(맨 앞의 dim)를 10으로 했다면 저 Average Forward pass 시간을 10으로 나눠야 합니다. 그러나 우리는 dim을 1로 주었으므로 그럴 필요없이 저것을 그대로 쓰면 됩니다. 즉, RGB 3 채널의 1200x1200 이미지 1장을 P100 GPU를 이용하여 GoogleNet으로 inference하는데 0.045초가 걸린다고 보시면 됩니다.
위의 테스트에서 display되는 benchmark 과정을 보면 Deep Learning의 얼개를 대충 보실 수 있습니다. 아래처럼 먼저 Top shape를 1 x 3 x 1200 x 1200으로 시작했다가, 다음 단계에서는 1 x 64 x 600 x 600으로, 그 다음에는 다시 300 x 300으로 계속 절반으로 줄여나가다가 결국 31 x 31에서 마무리 됩니다. 마지막 단계에서의 channel 수는 무려 1024로 늘어나게 되는데, 그 의미를 (저 같은 무식한 HW 엔지니어는) 잘 모르겠군요. 사실 HW 엔지니어에게 중요한 것은 거기에 필요로 하는 메모리 사이즈입니다. 각 단계별 top shape마다 필요로 하는 메모리 사이즈가 'Memory required for data'라는 항목으로 display되는데, 처음 단계에서는 17MB 정도로 시작했다가 맨 마지막 단계에서는 거의 1.6GB 가까이 갑니다.
...
I0908 05:39:25.035709 567 net.cpp:135] Top shape: 1 3 1200 1200 (4320000)
I0908 05:39:25.035733 567 net.cpp:143] Memory required for data: 17280000
I0908 05:39:25.035754 567 layer_factory.hpp:77] Creating layer conv1/7x7_s2
I0908 05:39:25.035786 567 net.cpp:90] Creating Layer conv1/7x7_s2
I0908 05:39:25.035799 567 net.cpp:635] conv1/7x7_s2 <- data
I0908 05:39:25.035816 567 net.cpp:609] conv1/7x7_s2 -> conv1/7x7_s2
I0908 05:39:29.695616 567 net.cpp:128] Setting up conv1/7x7_s2
I0908 05:39:29.695672 567 net.cpp:135] Top shape: 1 64 600 600 (23040000)
I0908 05:39:29.695695 567 net.cpp:143] Memory required for data: 109440000
...
I0908 05:39:29.862272 567 net.cpp:128] Setting up pool5/drop_7x7_s1
I0908 05:39:29.862279 567 net.cpp:135] Top shape: 1 1024 31 31 (984064)
I0908 05:39:29.862287 567 net.cpp:143] Memory required for data: 1587930496
I0908 05:39:29.862294 567 layer_factory.hpp:77] Creating layer loss3/classifier
I0908 05:39:29.862305 567 net.cpp:90] Creating Layer loss3/classifier
I0908 05:39:29.862311 567 net.cpp:635] loss3/classifier <- pool5/7x7_s1
I0908 05:39:29.862320 567 net.cpp:609] loss3/classifier -> loss3/classifier
I0908 05:39:36.385628 567 net.cpp:128] Setting up loss3/classifier
I0908 05:39:36.385684 567 net.cpp:135] Top shape: 1 1000 (1000)
I0908 05:39:36.385696 567 net.cpp:143] Memory required for data: 1587934496
I0908 05:39:36.385712 567 layer_factory.hpp:77] Creating layer prob
I0908 05:39:36.385728 567 net.cpp:90] Creating Layer prob
I0908 05:39:36.385737 567 net.cpp:635] prob <- loss3/classifier
I0908 05:39:36.385749 567 net.cpp:609] prob -> prob
I0908 05:39:36.386745 567 net.cpp:128] Setting up prob
I0908 05:39:36.386756 567 net.cpp:135] Top shape: 1 1000 (1000)
I0908 05:39:36.386765 567 net.cpp:143] Memory required for data: 1587938496
I0908 05:39:36.386771 567 net.cpp:206] prob does not need backward computation.
...
잠깐만요, 1.6GB라고요 ? P100의 GPU 메모리 크기가 16GB 밖에 안되는데, 저런 image를 10장을 한꺼번에 inference하면 어떻게 된다는 것일까요 ? 설마 error가 날까요 ? 한번 해보겠습니다. 위와 동일한 모델을 사용하되, 단지 맨 앞의 dim, 즉 batch size를 1에서 10으로 바꾸겠습니다.
nimbix@JARVICENAE-0A0A1844:/data$ vi bvlc_googlenet/deploy.prototxt
name: "GoogleNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 10 dim: 3 dim: 1200 dim: 1200 } }
# input_param { shape: { dim: 1 dim: 3 dim: 1200 dim: 1200 } }
# input_param { shape: { dim: 10 dim: 3 dim: 224 dim: 224 } }
}
이제 동일하게 caffe time을 수행합니다.
nimbix@JARVICENAE-0A0A1844:/data$ caffe time -gpu 0 -model=/data/bvlc_googlenet/deploy.prototxt --iterations=1
I0908 05:43:44.249899 646 net.cpp:135] Top shape: 10 3 1200 1200 (43200000)
I0908 05:43:44.249914 646 net.cpp:143] Memory required for data: 172800000
I0908 05:43:44.249928 646 layer_factory.hpp:77] Creating layer conv1/7x7_s2
I0908 05:43:44.249949 646 net.cpp:90] Creating Layer conv1/7x7_s2
I0908 05:43:44.249956 646 net.cpp:635] conv1/7x7_s2 <- data
I0908 05:43:44.249967 646 net.cpp:609] conv1/7x7_s2 -> conv1/7x7_s2
I0908 05:43:44.614331 646 net.cpp:128] Setting up conv1/7x7_s2
I0908 05:43:44.614367 646 net.cpp:135] Top shape: 10 64 600 600 (230400000)
I0908 05:43:44.614382 646 net.cpp:143] Memory required for data: 1094400000
...
I0908 05:43:44.763245 646 net.cpp:135] Top shape: 10 1024 31 31 (9840640)
I0908 05:43:44.763254 646 net.cpp:143] Memory required for data: 15839942400
I0908 05:43:44.763260 646 layer_factory.hpp:77] Creating layer pool5/drop_7x7_s1
I0908 05:43:44.763272 646 net.cpp:90] Creating Layer pool5/drop_7x7_s1
I0908 05:43:44.763278 646 net.cpp:635] pool5/drop_7x7_s1 <- pool5/7x7_s1
I0908 05:43:44.763285 646 net.cpp:596] pool5/drop_7x7_s1 -> pool5/7x7_s1 (in-place)
I0908 05:43:44.763319 646 net.cpp:128] Setting up pool5/drop_7x7_s1
I0908 05:43:44.763325 646 net.cpp:135] Top shape: 10 1024 31 31 (9840640)
I0908 05:43:44.763334 646 net.cpp:143] Memory required for data: 15879304960
I0908 05:43:44.763340 646 layer_factory.hpp:77] Creating layer loss3/classifier
I0908 05:43:44.763352 646 net.cpp:90] Creating Layer loss3/classifier
I0908 05:43:44.763358 646 net.cpp:635] loss3/classifier <- pool5/7x7_s1
I0908 05:43:44.763367 646 net.cpp:609] loss3/classifier -> loss3/classifier
I0908 05:43:51.338423 646 net.cpp:128] Setting up loss3/classifier
I0908 05:43:51.345638 646 net.cpp:135] Top shape: 10 1000 (10000)
I0908 05:43:51.345651 646 net.cpp:143] Memory required for data: 15879344960
I0908 05:43:51.345667 646 layer_factory.hpp:77] Creating layer prob
I0908 05:43:51.345683 646 net.cpp:90] Creating Layer prob
I0908 05:43:51.345693 646 net.cpp:635] prob <- loss3/classifier
I0908 05:43:51.345705 646 net.cpp:609] prob -> prob
I0908 05:43:51.346666 646 net.cpp:128] Setting up prob
I0908 05:43:51.346678 646 net.cpp:135] Top shape: 10 1000 (10000)
I0908 05:43:51.346685 646 net.cpp:143] Memory required for data: 15879384960
...
I0908 05:43:51.724148 646 caffe.cpp:465] Initial loss: 0
I0908 05:43:51.724202 646 caffe.cpp:466] Performing Backward
I0908 05:43:51.724215 646 caffe.cpp:474] *** Benchmark begins ***
I0908 05:43:51.724222 646 caffe.cpp:475] Testing for 1 iterations.
F0908 05:43:51.915272 646 syncedmem.cpp:651] Check failed: error == cudaSuccess (2 vs. 0) out of memory
*** Check failure stack trace: ***
@ 0x100000f5ce0c google::LogMessage::Fail()
@ 0x100000f5f284 google::LogMessage::SendToLog()
@ 0x100000f5c768 google::LogMessage::Flush()
@ 0x100000f611c4 google::LogMessageFatal::~LogMessageFatal()
@ 0x10000026e3a0 caffe::SyncedMemory::mutable_gpu_data()
@ 0x1000002736c4 caffe::Blob<>::mutable_gpu_diff()
@ 0x1000004e774c caffe::InnerProductLayer<>::Backward_gpu()
@ 0x10018ca8 (unknown)
@ 0x10012974 (unknown)
@ 0x100001c2309c (unknown)
@ 0x100001c23298 __libc_start_main
@ (nil) (unknown)
아 ! 정말 error가 납니다. 정말 data에만 무려 15.8GB의 메모리가 필요하다고 나오더니, 실제 벤치마크에 들어가자마자 out of memory 에러가 나면서 중단됩니다. 정말 GPU의 발목을 잡는 것은 GPU 메모리 크기의 한계라는 것을 절실히 깨닫는 순간입니다.
하지만 IBM과 NVIDIA는 여기서 포기하지 않습니다. 원래 NVIDIA의 CUDA에서는 Unified Memory라고 해서, GPU가 CPU 메모리를 마치 GPU 메모리처럼 쓸 수 있는 기능을 내놓았지요. 그러나 실제로는 그렇게 GPU가 CPU memory에 접근하는 통로가 느려터진 PCIe이다보니, Unified Memory를 쓰면 편리하기는 해도 성능은 거의 1/10 수준으로 떨어져 버리는 것이 상식이었습니다. 이는 NVLink P100을 장착한 DGX-1 서버에서도 마찬가지였습니다. DGX-1도 GPU끼리만 NVLink로 연결될 뿐, 정작 CPU와 GPU를 연결하는 것은 PCIe거든요. 그래서 결국 아무도 caffe에서 unified memory를 쓸 생각을 하지 않았습니다.
그러나 IBM Minsky는 다릅니다. POWER8 processor에는 NVLink port가 박혀있으므로, CPU와 GPU가 NVLink로 직접 연결되며, 그것도 NVLink 2개를 뭉쳐서 무려 80GB/sec로 연결됩니다. PCIe의 2.5배나 되는 대역폭입니다. 이를 활용하여 caffe에서 CPU-GPU 간에 data를 직접 주고받을 수 있습니다 ! 실제로 IBM은 최근 발표한 PowerAI 4.0에 포함된 IBM caffe (caffe-ibm)에 이를 적용했습니다. 그 결과, IBM caffe에서는 일반 bvlc caffe나 NV caffe에는 없는 새로운 옵션, -lms (LMS, Large Model Support)를 사용할 수 있습니다.
이에 대해서는 아래 문서를 참조하시면 됩니다.
https://public.dhe.ibm.com/software/server/POWER/Linux/mldl/ubuntu/README.html
역시 귀찮으신 분들을 위해 간략히 요약해드리면 이렇습니다.
-lms 8000000 : 이는 8000000 (kbyte 단위, 즉 8GB) 이상의 메모리 덩어리는 그냥 CPU 메모리 상에 두라는 뜻입니다.
즉, -lms 뒤에 큰 수를 적을 수록 가급적 GPU 메모리를 많이 쓰고 CPU 메모리는 정말 필요한 경우에만 쓰라는 이야기입니다. 당연히 최대치는 16000000 정도가 될 것이고, 이보다 더 큰 수를 적는 것은 사실상 LMS 옵션을 disable하는 효과를 냅니다. 반면에 -lms를 매우 작게, 가령 100으로 주는 것은 사실상 GPU 메모리를 쓰지 말고 다 CPU 메모리를 쓰라는 이야기가 됩니다.
또 -lms_frac <0~1.0> 이라는 옵션을 줄 수도 있습니다. 가령 -lms_frac 0.4로 주면, GPU 메모리 사용률이 40%가 되기 전에는 LMS 기능을 쓰지 말라는 것이 됩니다. 작은 크기의 model을 수행할 때는 굳이 느린 CPU 메모리를 쓸 필요가 없으므로, -lms_frac 0.9 정도로 주는 것이 좋습니다.
이제 위에서 out of memory를 낸 model에 대해 실제로 -lms 옵션을 적용해 보시지요. 먼저 -lms 8192, 즉 8MB 이상의 메모리 덩어리는 모두 CPU 메모리에 두라고 지시했습니다.
nimbix@JARVICENAE-0A0A1844:/data$ caffe time -gpu 0 -lms 8192 -model=/data/bvlc_googlenet/deploy.prototxt --iterations=1
I0908 05:47:44.949090 676 net.cpp:135] Top shape: 10 3 1200 1200 (43200000)
I0908 05:47:44.949105 676 net.cpp:143] Memory required for data: 172800000
I0908 05:47:44.949124 676 layer_factory.hpp:77] Creating layer conv1/7x7_s2
I0908 05:47:44.949146 676 net.cpp:90] Creating Layer conv1/7x7_s2
I0908 05:47:44.949153 676 net.cpp:635] conv1/7x7_s2 <- data
I0908 05:47:44.949167 676 net.cpp:609] conv1/7x7_s2 -> conv1/7x7_s2
I0908 05:47:45.580006 676 net.cpp:128] Setting up conv1/7x7_s2
I0908 05:47:45.580046 676 net.cpp:135] Top shape: 10 64 600 600 (230400000)
I0908 05:47:45.580060 676 net.cpp:143] Memory required for data: 1094400000
...
I0908 05:47:57.704324 676 caffe.cpp:465] Initial loss: 0
I0908 05:47:57.704356 676 caffe.cpp:466] Performing Backward
I0908 05:47:57.704371 676 caffe.cpp:474] *** Benchmark begins ***
I0908 05:47:57.704377 676 caffe.cpp:475] Testing for 1 iterations.
I0908 05:47:57.711424 676 syncedmem.cpp:355] [LMS] memory[0x110024232400] device_=0 size_ = 921600000 allocation=7349057792 fragmented size = 655558000 gpu_ptr_=1155371368464
I0908 05:47:57.769644 676 syncedmem.cpp:355] [LMS] memory[0x110024258aa0] device_=0 size_ = 230400000 allocation=7579458048 fragmented size = 425158224 gpu_ptr_=1122381070352
I0908 05:47:57.778683 676 syncedmem.cpp:355] [LMS] memory[0x110024286d30] device_=0 size_ = 230400000 allocation=7809858304 fragmented size = 425158464 gpu_ptr_=1122842444032
I0908 05:47:57.790587 676 syncedmem.cpp:355] [LMS] memory[0x1100242c0be0] device_=0 size_ = 691200000 allocation=8731458560 fragmented size = 655558704 gpu_ptr_=1156294115344
I0908 05:47:57.838747 676 syncedmem.cpp:355] [LMS] memory[0x1100242df300] device_=0 size_ = 691200000 allocation=9653058816 fragmented size = 885958944 gpu_ptr_=1157447262464
...
I0908 05:47:58.203995 676 caffe.cpp:513] pool5/7x7_s1 forward: 4.48429 ms.
I0908 05:47:58.204002 676 caffe.cpp:516] pool5/7x7_s1 backward: 0.002144 ms.
I0908 05:47:58.204010 676 caffe.cpp:513] pool5/drop_7x7_s1 forward: 0.367552 ms.
I0908 05:47:58.204015 676 caffe.cpp:516] pool5/drop_7x7_s1 backward: 0.002112 ms.
I0908 05:47:58.204022 676 caffe.cpp:513] loss3/classifier forward: 18.1078 ms.
I0908 05:47:58.204033 676 caffe.cpp:516] loss3/classifier backward: 0.002112 ms.
I0908 05:47:58.204041 676 caffe.cpp:513] prob forward: 0.022848 ms.
I0908 05:47:58.204047 676 caffe.cpp:516] prob backward: 0.011328 ms.
I0908 05:47:58.204061 676 caffe.cpp:521] Average Forward pass: 495.206 ms.
I0908 05:47:58.204067 676 caffe.cpp:523] Average Backward pass: 2.21437 ms.
I0908 05:47:58.204074 676 caffe.cpp:525] Average Forward-Backward: 499.65 ms.
I0908 05:47:58.204092 676 caffe.cpp:527] Total Time: 499.65 ms.
I0908 05:47:58.204107 676 caffe.cpp:528] *** Benchmark ends ***
예 ! 도중에 LMS가 사용된다는 메시지가 display되면서 성공적으로 완료되었습니다 ! 아무래도 느린 CPU 메모리를 사용하니까 당연히 성능은 떨어졌을 것입니다. 얼마나 떨어졌을까요 ? 여기서의 결과는 Average Forward pass: 495.206 ms 인데, batch size가 10이므로 이미지 1장당 0.0495초 걸린 것입니다. 위에서 1장씩 테스트했을 때의 결과 0.045초보다 10% 정도 느려졌습니다. 10장씩 batch로 돌리면 사실 1장씩 돌린 것보다는 빨리 나와야 하는데 오히려 10% 느려진 것은 많이 느려진 것이지요.
결국 LMS를 사용하면 심각한 성능 저하는 어쩔 수 없이 발생하는 것일까요 ? 꼭 그렇지는 않습니다. 방금 제가 수행한 것은 극단적으로 거의 모든 메모리 덩어리를 CPU 메모리에 두라고 지시한 것입니다. GPU 메모리를 적극적으로 활용하되, GPU 메모리 크기보다 큰 것들만 어쩔 수 없이 CPU 메모리를 사용하라고 지시하면 성능이 훨씬 더 좋을 것입니다.
이번에는 그렇게 -lms 160000000 옵션으로 돌려 보겠습니다.
nimbix@JARVICENAE-0A0A1844:/data$ caffe time -gpu 0 -lms 160000000 -model=/data/bvlc_googlenet/deploy.prototxt --iterations=1
I0908 06:32:20.006875 1126 net.cpp:135] Top shape: 10 3 1200 1200 (43200000)
I0908 06:32:20.006891 1126 net.cpp:143] Memory required for data: 172800000
I0908 06:32:20.006904 1126 layer_factory.hpp:77] Creating layer conv1/7x7_s2
I0908 06:32:20.006927 1126 net.cpp:90] Creating Layer conv1/7x7_s2
I0908 06:32:20.006933 1126 net.cpp:635] conv1/7x7_s2 <- data
I0908 06:32:20.006944 1126 net.cpp:609] conv1/7x7_s2 -> conv1/7x7_s2
I0908 06:32:20.591289 1126 net.cpp:128] Setting up conv1/7x7_s2
I0908 06:32:20.591329 1126 net.cpp:135] Top shape: 10 64 600 600 (230400000)
I0908 06:32:20.591343 1126 net.cpp:143] Memory required for data: 1094400000
...
I0908 06:32:28.272960 1126 net.cpp:296] [LMS] BuildLargeModelSupport
W0908 06:32:28.273018 1126 net.cpp:348] [LMS] ######################################################
W0908 06:32:28.273172 1126 net.cpp:349] [LMS] uncovered layer type: Softmax
W0908 06:32:28.273182 1126 net.cpp:350] [LMS] ######################################################
W0908 06:32:28.273310 1126 net.cpp:348] [LMS] ######################################################
W0908 06:32:28.273320 1126 net.cpp:349] [LMS] uncovered layer type: Input
W0908 06:32:28.273329 1126 net.cpp:350] [LMS] ######################################################
I0908 06:32:28.273347 1126 net.cpp:425] [LMS] data_forward [0] data: -> data: 0x110009bfa4f0(172800000) ### flag=0 data:
I0908 06:32:28.273361 1126 net.cpp:425] [LMS] conv1/7x7_s2_forward [1] data: 0x110009bfa4f0(172800000) -> data: 0x1100233f7520(921600000) ### flag=0 data: 0x110009bfa4f0(1,1)
...
I0908 06:32:29.055697 1126 caffe.cpp:513] prob forward: 0.022016 ms.
I0908 06:32:29.055704 1126 caffe.cpp:516] prob backward: 0.006848 ms.
I0908 06:32:29.055716 1126 caffe.cpp:521] Average Forward pass: 263.516 ms.
I0908 06:32:29.055724 1126 caffe.cpp:523] Average Backward pass: 2.21066 ms.
I0908 06:32:29.055730 1126 caffe.cpp:525] Average Forward-Backward: 267.967 ms.
I0908 06:32:29.055748 1126 caffe.cpp:527] Total Time: 267.967 ms.
I0908 06:32:29.055764 1126 caffe.cpp:528] *** Benchmark ends ***
이번에는 10장에 대해 263.516 ms, 즉 1장에 대해서는 0.0263초가 걸렸습니다. 이는 1장씩 테스트했을 때의 결과 0.045초보다 무려 71% 빠른 결과입니다 ! LMS 덕분에 10장씩 batch로 돌리니까 더 빨라진 것이지요. 결국 LMS를 사용하면 오히려 더 빠른 성능을 낼 수도 있는 것입니다.
이에 대해서는 아래 site에 기본적인 방법이 소개됩니다. IBM China의 Deep Learning 개발팀의 박사님들에게 물어보니, 이 방법이 맞다고 합니다.
https://stackoverflow.com/questions/36867591/how-to-estimate-inference-time-from-average-forward-pass-time-in-caffe
여기서 핵심적인 부분은 바로 아래 부분입니다.
For instance, if I run the default command that comes with Caffe:
build/tools/caffe time --model=models/bvlc_alexnet/deploy.prototxt --gpu=0
I get the following output
...
I0426 13:07:32.701490 30417 layer_factory.hpp:77] Creating layer data
I0426 13:07:32.701513 30417 net.cpp:91] Creating Layer data
I0426 13:07:32.701529 30417 net.cpp:399] data -> data
I0426 13:07:32.709048 30417 net.cpp:141] Setting up data
I0426 13:07:32.709079 30417 net.cpp:148] Top shape: 10 3 227 227 (1545870)
I0426 13:07:32.709084 30417 net.cpp:156] Memory required for data: 6183480
...
I0426 13:07:34.390281 30417 caffe.cpp:377] Average Forward pass: 16.7818 ms.
I0426 13:07:34.390290 30417 caffe.cpp:379] Average Backward pass: 12.923 ms.
I0426 13:07:34.390296 30417 caffe.cpp:381] Average Forward-Backward: 29.7969 ms.
The following line:
I0426 13:07:32.709079 30417 net.cpp:148] Top shape: 10 3 227 227 (1545870)
is super important. It says that your input layer is 10x3x227x227-dimensional. In this case, the batch size is 10 images, each of size 3x227x227 (the 3 refers to each of the rgb channels in an image).
So effectively, it took 1.67818 ms/image to do a forward pass or inference time per image.
즉, caffe 명령어의 sub-comand 중 time 명령, 즉 caffe를 이용한 성능 benchmark 결과에서 평균 forward pass에 걸린 시간이 해당 model과 해당 이미지에 대해서 걸릴 inference time이라는 것입니다. 당연한 이야기지만 해당 model에 지정하는 data layer의 Top shape 10 3 227 227, 즉 batch size 10 x channel (RGB) 3 x height 227 x width 227이 클 수록 더 많은 시간이 걸립니다.
HPC cloud 서비스 업체인 Nimbix (nimbix.net/powerai)에서 제공하는 Minsky 서버의 P100 1장짜리 가상머신을 사용할 기회가 있어, 거기에서 이 test를 해봤습니다. 참고로 Nimbix는 docker 기반의 NVLink P100 GPU 가상 머신을 제공하는데, 이에 대해서도 나중에 다룰 기회가 있을 것입니다.
먼저, 1200x1200 크기의 이미지 1장에 대해서 GoogleNet으로 inference하는데 NVLink P100으로는 시간이 얼마나 걸리는지 보시겠습니다. 이를 위해서 먼저 GoogleNet에 포함된 deploy.prototxt를 아래와 같이 편집합니다. 원본 line은 아래에 #으로 comment-out 처리했습니다.
nimbix@JARVICENAE-0A0A1844:/data$ vi bvlc_googlenet/deploy.prototxt
name: "GoogleNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 1 dim: 3 dim: 1200 dim: 1200 } }
# input_param { shape: { dim: 10 dim: 3 dim: 224 dim: 224 } }
}
이제 이렇게 수정된 model로 caffe time을 수행합니다.
nimbix@JARVICENAE-0A0A1844:/data$ caffe time -gpu 0 -model=/data/bvlc_googlenet/deploy.prototxt --iterations=1
그 과정을 다 보실 필요는 없고, 사실 맨 끝의 benchmark 결과에서 Average Forward pass 시간만 보시면 됩니다.
I0908 05:39:36.830621 567 caffe.cpp:513] prob forward: 0.020864 ms.
I0908 05:39:36.830627 567 caffe.cpp:516] prob backward: 0.00368 ms.
I0908 05:39:36.830641 567 caffe.cpp:521] Average Forward pass: 45.3671 ms.
I0908 05:39:36.830649 567 caffe.cpp:523] Average Backward pass: 102.551 ms.
I0908 05:39:36.830657 567 caffe.cpp:525] Average Forward-Backward: 150.178 ms.
I0908 05:39:36.830673 567 caffe.cpp:527] Total Time: 150.178 ms.
I0908 05:39:36.830689 567 caffe.cpp:528] *** Benchmark ends ***
여기서 만약 우리가 batch size(맨 앞의 dim)를 10으로 했다면 저 Average Forward pass 시간을 10으로 나눠야 합니다. 그러나 우리는 dim을 1로 주었으므로 그럴 필요없이 저것을 그대로 쓰면 됩니다. 즉, RGB 3 채널의 1200x1200 이미지 1장을 P100 GPU를 이용하여 GoogleNet으로 inference하는데 0.045초가 걸린다고 보시면 됩니다.
위의 테스트에서 display되는 benchmark 과정을 보면 Deep Learning의 얼개를 대충 보실 수 있습니다. 아래처럼 먼저 Top shape를 1 x 3 x 1200 x 1200으로 시작했다가, 다음 단계에서는 1 x 64 x 600 x 600으로, 그 다음에는 다시 300 x 300으로 계속 절반으로 줄여나가다가 결국 31 x 31에서 마무리 됩니다. 마지막 단계에서의 channel 수는 무려 1024로 늘어나게 되는데, 그 의미를 (저 같은 무식한 HW 엔지니어는) 잘 모르겠군요. 사실 HW 엔지니어에게 중요한 것은 거기에 필요로 하는 메모리 사이즈입니다. 각 단계별 top shape마다 필요로 하는 메모리 사이즈가 'Memory required for data'라는 항목으로 display되는데, 처음 단계에서는 17MB 정도로 시작했다가 맨 마지막 단계에서는 거의 1.6GB 가까이 갑니다.
...
I0908 05:39:25.035709 567 net.cpp:135] Top shape: 1 3 1200 1200 (4320000)
I0908 05:39:25.035733 567 net.cpp:143] Memory required for data: 17280000
I0908 05:39:25.035754 567 layer_factory.hpp:77] Creating layer conv1/7x7_s2
I0908 05:39:25.035786 567 net.cpp:90] Creating Layer conv1/7x7_s2
I0908 05:39:25.035799 567 net.cpp:635] conv1/7x7_s2 <- data
I0908 05:39:25.035816 567 net.cpp:609] conv1/7x7_s2 -> conv1/7x7_s2
I0908 05:39:29.695616 567 net.cpp:128] Setting up conv1/7x7_s2
I0908 05:39:29.695672 567 net.cpp:135] Top shape: 1 64 600 600 (23040000)
I0908 05:39:29.695695 567 net.cpp:143] Memory required for data: 109440000
...
I0908 05:39:29.862272 567 net.cpp:128] Setting up pool5/drop_7x7_s1
I0908 05:39:29.862279 567 net.cpp:135] Top shape: 1 1024 31 31 (984064)
I0908 05:39:29.862287 567 net.cpp:143] Memory required for data: 1587930496
I0908 05:39:29.862294 567 layer_factory.hpp:77] Creating layer loss3/classifier
I0908 05:39:29.862305 567 net.cpp:90] Creating Layer loss3/classifier
I0908 05:39:29.862311 567 net.cpp:635] loss3/classifier <- pool5/7x7_s1
I0908 05:39:29.862320 567 net.cpp:609] loss3/classifier -> loss3/classifier
I0908 05:39:36.385628 567 net.cpp:128] Setting up loss3/classifier
I0908 05:39:36.385684 567 net.cpp:135] Top shape: 1 1000 (1000)
I0908 05:39:36.385696 567 net.cpp:143] Memory required for data: 1587934496
I0908 05:39:36.385712 567 layer_factory.hpp:77] Creating layer prob
I0908 05:39:36.385728 567 net.cpp:90] Creating Layer prob
I0908 05:39:36.385737 567 net.cpp:635] prob <- loss3/classifier
I0908 05:39:36.385749 567 net.cpp:609] prob -> prob
I0908 05:39:36.386745 567 net.cpp:128] Setting up prob
I0908 05:39:36.386756 567 net.cpp:135] Top shape: 1 1000 (1000)
I0908 05:39:36.386765 567 net.cpp:143] Memory required for data: 1587938496
I0908 05:39:36.386771 567 net.cpp:206] prob does not need backward computation.
...
잠깐만요, 1.6GB라고요 ? P100의 GPU 메모리 크기가 16GB 밖에 안되는데, 저런 image를 10장을 한꺼번에 inference하면 어떻게 된다는 것일까요 ? 설마 error가 날까요 ? 한번 해보겠습니다. 위와 동일한 모델을 사용하되, 단지 맨 앞의 dim, 즉 batch size를 1에서 10으로 바꾸겠습니다.
nimbix@JARVICENAE-0A0A1844:/data$ vi bvlc_googlenet/deploy.prototxt
name: "GoogleNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 10 dim: 3 dim: 1200 dim: 1200 } }
# input_param { shape: { dim: 1 dim: 3 dim: 1200 dim: 1200 } }
# input_param { shape: { dim: 10 dim: 3 dim: 224 dim: 224 } }
}
이제 동일하게 caffe time을 수행합니다.
nimbix@JARVICENAE-0A0A1844:/data$ caffe time -gpu 0 -model=/data/bvlc_googlenet/deploy.prototxt --iterations=1
I0908 05:43:44.249899 646 net.cpp:135] Top shape: 10 3 1200 1200 (43200000)
I0908 05:43:44.249914 646 net.cpp:143] Memory required for data: 172800000
I0908 05:43:44.249928 646 layer_factory.hpp:77] Creating layer conv1/7x7_s2
I0908 05:43:44.249949 646 net.cpp:90] Creating Layer conv1/7x7_s2
I0908 05:43:44.249956 646 net.cpp:635] conv1/7x7_s2 <- data
I0908 05:43:44.249967 646 net.cpp:609] conv1/7x7_s2 -> conv1/7x7_s2
I0908 05:43:44.614331 646 net.cpp:128] Setting up conv1/7x7_s2
I0908 05:43:44.614367 646 net.cpp:135] Top shape: 10 64 600 600 (230400000)
I0908 05:43:44.614382 646 net.cpp:143] Memory required for data: 1094400000
...
I0908 05:43:44.763245 646 net.cpp:135] Top shape: 10 1024 31 31 (9840640)
I0908 05:43:44.763254 646 net.cpp:143] Memory required for data: 15839942400
I0908 05:43:44.763260 646 layer_factory.hpp:77] Creating layer pool5/drop_7x7_s1
I0908 05:43:44.763272 646 net.cpp:90] Creating Layer pool5/drop_7x7_s1
I0908 05:43:44.763278 646 net.cpp:635] pool5/drop_7x7_s1 <- pool5/7x7_s1
I0908 05:43:44.763285 646 net.cpp:596] pool5/drop_7x7_s1 -> pool5/7x7_s1 (in-place)
I0908 05:43:44.763319 646 net.cpp:128] Setting up pool5/drop_7x7_s1
I0908 05:43:44.763325 646 net.cpp:135] Top shape: 10 1024 31 31 (9840640)
I0908 05:43:44.763334 646 net.cpp:143] Memory required for data: 15879304960
I0908 05:43:44.763340 646 layer_factory.hpp:77] Creating layer loss3/classifier
I0908 05:43:44.763352 646 net.cpp:90] Creating Layer loss3/classifier
I0908 05:43:44.763358 646 net.cpp:635] loss3/classifier <- pool5/7x7_s1
I0908 05:43:44.763367 646 net.cpp:609] loss3/classifier -> loss3/classifier
I0908 05:43:51.338423 646 net.cpp:128] Setting up loss3/classifier
I0908 05:43:51.345638 646 net.cpp:135] Top shape: 10 1000 (10000)
I0908 05:43:51.345651 646 net.cpp:143] Memory required for data: 15879344960
I0908 05:43:51.345667 646 layer_factory.hpp:77] Creating layer prob
I0908 05:43:51.345683 646 net.cpp:90] Creating Layer prob
I0908 05:43:51.345693 646 net.cpp:635] prob <- loss3/classifier
I0908 05:43:51.345705 646 net.cpp:609] prob -> prob
I0908 05:43:51.346666 646 net.cpp:128] Setting up prob
I0908 05:43:51.346678 646 net.cpp:135] Top shape: 10 1000 (10000)
I0908 05:43:51.346685 646 net.cpp:143] Memory required for data: 15879384960
...
I0908 05:43:51.724148 646 caffe.cpp:465] Initial loss: 0
I0908 05:43:51.724202 646 caffe.cpp:466] Performing Backward
I0908 05:43:51.724215 646 caffe.cpp:474] *** Benchmark begins ***
I0908 05:43:51.724222 646 caffe.cpp:475] Testing for 1 iterations.
F0908 05:43:51.915272 646 syncedmem.cpp:651] Check failed: error == cudaSuccess (2 vs. 0) out of memory
*** Check failure stack trace: ***
@ 0x100000f5ce0c google::LogMessage::Fail()
@ 0x100000f5f284 google::LogMessage::SendToLog()
@ 0x100000f5c768 google::LogMessage::Flush()
@ 0x100000f611c4 google::LogMessageFatal::~LogMessageFatal()
@ 0x10000026e3a0 caffe::SyncedMemory::mutable_gpu_data()
@ 0x1000002736c4 caffe::Blob<>::mutable_gpu_diff()
@ 0x1000004e774c caffe::InnerProductLayer<>::Backward_gpu()
@ 0x10018ca8 (unknown)
@ 0x10012974 (unknown)
@ 0x100001c2309c (unknown)
@ 0x100001c23298 __libc_start_main
@ (nil) (unknown)
아 ! 정말 error가 납니다. 정말 data에만 무려 15.8GB의 메모리가 필요하다고 나오더니, 실제 벤치마크에 들어가자마자 out of memory 에러가 나면서 중단됩니다. 정말 GPU의 발목을 잡는 것은 GPU 메모리 크기의 한계라는 것을 절실히 깨닫는 순간입니다.
하지만 IBM과 NVIDIA는 여기서 포기하지 않습니다. 원래 NVIDIA의 CUDA에서는 Unified Memory라고 해서, GPU가 CPU 메모리를 마치 GPU 메모리처럼 쓸 수 있는 기능을 내놓았지요. 그러나 실제로는 그렇게 GPU가 CPU memory에 접근하는 통로가 느려터진 PCIe이다보니, Unified Memory를 쓰면 편리하기는 해도 성능은 거의 1/10 수준으로 떨어져 버리는 것이 상식이었습니다. 이는 NVLink P100을 장착한 DGX-1 서버에서도 마찬가지였습니다. DGX-1도 GPU끼리만 NVLink로 연결될 뿐, 정작 CPU와 GPU를 연결하는 것은 PCIe거든요. 그래서 결국 아무도 caffe에서 unified memory를 쓸 생각을 하지 않았습니다.
그러나 IBM Minsky는 다릅니다. POWER8 processor에는 NVLink port가 박혀있으므로, CPU와 GPU가 NVLink로 직접 연결되며, 그것도 NVLink 2개를 뭉쳐서 무려 80GB/sec로 연결됩니다. PCIe의 2.5배나 되는 대역폭입니다. 이를 활용하여 caffe에서 CPU-GPU 간에 data를 직접 주고받을 수 있습니다 ! 실제로 IBM은 최근 발표한 PowerAI 4.0에 포함된 IBM caffe (caffe-ibm)에 이를 적용했습니다. 그 결과, IBM caffe에서는 일반 bvlc caffe나 NV caffe에는 없는 새로운 옵션, -lms (LMS, Large Model Support)를 사용할 수 있습니다.
이에 대해서는 아래 문서를 참조하시면 됩니다.
https://public.dhe.ibm.com/software/server/POWER/Linux/mldl/ubuntu/README.html
역시 귀찮으신 분들을 위해 간략히 요약해드리면 이렇습니다.
-lms 8000000 : 이는 8000000 (kbyte 단위, 즉 8GB) 이상의 메모리 덩어리는 그냥 CPU 메모리 상에 두라는 뜻입니다.
즉, -lms 뒤에 큰 수를 적을 수록 가급적 GPU 메모리를 많이 쓰고 CPU 메모리는 정말 필요한 경우에만 쓰라는 이야기입니다. 당연히 최대치는 16000000 정도가 될 것이고, 이보다 더 큰 수를 적는 것은 사실상 LMS 옵션을 disable하는 효과를 냅니다. 반면에 -lms를 매우 작게, 가령 100으로 주는 것은 사실상 GPU 메모리를 쓰지 말고 다 CPU 메모리를 쓰라는 이야기가 됩니다.
또 -lms_frac <0~1.0> 이라는 옵션을 줄 수도 있습니다. 가령 -lms_frac 0.4로 주면, GPU 메모리 사용률이 40%가 되기 전에는 LMS 기능을 쓰지 말라는 것이 됩니다. 작은 크기의 model을 수행할 때는 굳이 느린 CPU 메모리를 쓸 필요가 없으므로, -lms_frac 0.9 정도로 주는 것이 좋습니다.
이제 위에서 out of memory를 낸 model에 대해 실제로 -lms 옵션을 적용해 보시지요. 먼저 -lms 8192, 즉 8MB 이상의 메모리 덩어리는 모두 CPU 메모리에 두라고 지시했습니다.
nimbix@JARVICENAE-0A0A1844:/data$ caffe time -gpu 0 -lms 8192 -model=/data/bvlc_googlenet/deploy.prototxt --iterations=1
I0908 05:47:44.949090 676 net.cpp:135] Top shape: 10 3 1200 1200 (43200000)
I0908 05:47:44.949105 676 net.cpp:143] Memory required for data: 172800000
I0908 05:47:44.949124 676 layer_factory.hpp:77] Creating layer conv1/7x7_s2
I0908 05:47:44.949146 676 net.cpp:90] Creating Layer conv1/7x7_s2
I0908 05:47:44.949153 676 net.cpp:635] conv1/7x7_s2 <- data
I0908 05:47:44.949167 676 net.cpp:609] conv1/7x7_s2 -> conv1/7x7_s2
I0908 05:47:45.580006 676 net.cpp:128] Setting up conv1/7x7_s2
I0908 05:47:45.580046 676 net.cpp:135] Top shape: 10 64 600 600 (230400000)
I0908 05:47:45.580060 676 net.cpp:143] Memory required for data: 1094400000
...
I0908 05:47:57.704324 676 caffe.cpp:465] Initial loss: 0
I0908 05:47:57.704356 676 caffe.cpp:466] Performing Backward
I0908 05:47:57.704371 676 caffe.cpp:474] *** Benchmark begins ***
I0908 05:47:57.704377 676 caffe.cpp:475] Testing for 1 iterations.
I0908 05:47:57.711424 676 syncedmem.cpp:355] [LMS] memory[0x110024232400] device_=0 size_ = 921600000 allocation=7349057792 fragmented size = 655558000 gpu_ptr_=1155371368464
I0908 05:47:57.769644 676 syncedmem.cpp:355] [LMS] memory[0x110024258aa0] device_=0 size_ = 230400000 allocation=7579458048 fragmented size = 425158224 gpu_ptr_=1122381070352
I0908 05:47:57.778683 676 syncedmem.cpp:355] [LMS] memory[0x110024286d30] device_=0 size_ = 230400000 allocation=7809858304 fragmented size = 425158464 gpu_ptr_=1122842444032
I0908 05:47:57.790587 676 syncedmem.cpp:355] [LMS] memory[0x1100242c0be0] device_=0 size_ = 691200000 allocation=8731458560 fragmented size = 655558704 gpu_ptr_=1156294115344
I0908 05:47:57.838747 676 syncedmem.cpp:355] [LMS] memory[0x1100242df300] device_=0 size_ = 691200000 allocation=9653058816 fragmented size = 885958944 gpu_ptr_=1157447262464
...
I0908 05:47:58.203995 676 caffe.cpp:513] pool5/7x7_s1 forward: 4.48429 ms.
I0908 05:47:58.204002 676 caffe.cpp:516] pool5/7x7_s1 backward: 0.002144 ms.
I0908 05:47:58.204010 676 caffe.cpp:513] pool5/drop_7x7_s1 forward: 0.367552 ms.
I0908 05:47:58.204015 676 caffe.cpp:516] pool5/drop_7x7_s1 backward: 0.002112 ms.
I0908 05:47:58.204022 676 caffe.cpp:513] loss3/classifier forward: 18.1078 ms.
I0908 05:47:58.204033 676 caffe.cpp:516] loss3/classifier backward: 0.002112 ms.
I0908 05:47:58.204041 676 caffe.cpp:513] prob forward: 0.022848 ms.
I0908 05:47:58.204047 676 caffe.cpp:516] prob backward: 0.011328 ms.
I0908 05:47:58.204061 676 caffe.cpp:521] Average Forward pass: 495.206 ms.
I0908 05:47:58.204067 676 caffe.cpp:523] Average Backward pass: 2.21437 ms.
I0908 05:47:58.204074 676 caffe.cpp:525] Average Forward-Backward: 499.65 ms.
I0908 05:47:58.204092 676 caffe.cpp:527] Total Time: 499.65 ms.
I0908 05:47:58.204107 676 caffe.cpp:528] *** Benchmark ends ***
예 ! 도중에 LMS가 사용된다는 메시지가 display되면서 성공적으로 완료되었습니다 ! 아무래도 느린 CPU 메모리를 사용하니까 당연히 성능은 떨어졌을 것입니다. 얼마나 떨어졌을까요 ? 여기서의 결과는 Average Forward pass: 495.206 ms 인데, batch size가 10이므로 이미지 1장당 0.0495초 걸린 것입니다. 위에서 1장씩 테스트했을 때의 결과 0.045초보다 10% 정도 느려졌습니다. 10장씩 batch로 돌리면 사실 1장씩 돌린 것보다는 빨리 나와야 하는데 오히려 10% 느려진 것은 많이 느려진 것이지요.
결국 LMS를 사용하면 심각한 성능 저하는 어쩔 수 없이 발생하는 것일까요 ? 꼭 그렇지는 않습니다. 방금 제가 수행한 것은 극단적으로 거의 모든 메모리 덩어리를 CPU 메모리에 두라고 지시한 것입니다. GPU 메모리를 적극적으로 활용하되, GPU 메모리 크기보다 큰 것들만 어쩔 수 없이 CPU 메모리를 사용하라고 지시하면 성능이 훨씬 더 좋을 것입니다.
이번에는 그렇게 -lms 160000000 옵션으로 돌려 보겠습니다.
nimbix@JARVICENAE-0A0A1844:/data$ caffe time -gpu 0 -lms 160000000 -model=/data/bvlc_googlenet/deploy.prototxt --iterations=1
I0908 06:32:20.006875 1126 net.cpp:135] Top shape: 10 3 1200 1200 (43200000)
I0908 06:32:20.006891 1126 net.cpp:143] Memory required for data: 172800000
I0908 06:32:20.006904 1126 layer_factory.hpp:77] Creating layer conv1/7x7_s2
I0908 06:32:20.006927 1126 net.cpp:90] Creating Layer conv1/7x7_s2
I0908 06:32:20.006933 1126 net.cpp:635] conv1/7x7_s2 <- data
I0908 06:32:20.006944 1126 net.cpp:609] conv1/7x7_s2 -> conv1/7x7_s2
I0908 06:32:20.591289 1126 net.cpp:128] Setting up conv1/7x7_s2
I0908 06:32:20.591329 1126 net.cpp:135] Top shape: 10 64 600 600 (230400000)
I0908 06:32:20.591343 1126 net.cpp:143] Memory required for data: 1094400000
...
I0908 06:32:28.272960 1126 net.cpp:296] [LMS] BuildLargeModelSupport
W0908 06:32:28.273018 1126 net.cpp:348] [LMS] ######################################################
W0908 06:32:28.273172 1126 net.cpp:349] [LMS] uncovered layer type: Softmax
W0908 06:32:28.273182 1126 net.cpp:350] [LMS] ######################################################
W0908 06:32:28.273310 1126 net.cpp:348] [LMS] ######################################################
W0908 06:32:28.273320 1126 net.cpp:349] [LMS] uncovered layer type: Input
W0908 06:32:28.273329 1126 net.cpp:350] [LMS] ######################################################
I0908 06:32:28.273347 1126 net.cpp:425] [LMS] data_forward [0] data: -> data: 0x110009bfa4f0(172800000) ### flag=0 data:
I0908 06:32:28.273361 1126 net.cpp:425] [LMS] conv1/7x7_s2_forward [1] data: 0x110009bfa4f0(172800000) -> data: 0x1100233f7520(921600000) ### flag=0 data: 0x110009bfa4f0(1,1)
...
I0908 06:32:29.055697 1126 caffe.cpp:513] prob forward: 0.022016 ms.
I0908 06:32:29.055704 1126 caffe.cpp:516] prob backward: 0.006848 ms.
I0908 06:32:29.055716 1126 caffe.cpp:521] Average Forward pass: 263.516 ms.
I0908 06:32:29.055724 1126 caffe.cpp:523] Average Backward pass: 2.21066 ms.
I0908 06:32:29.055730 1126 caffe.cpp:525] Average Forward-Backward: 267.967 ms.
I0908 06:32:29.055748 1126 caffe.cpp:527] Total Time: 267.967 ms.
I0908 06:32:29.055764 1126 caffe.cpp:528] *** Benchmark ends ***
이번에는 10장에 대해 263.516 ms, 즉 1장에 대해서는 0.0263초가 걸렸습니다. 이는 1장씩 테스트했을 때의 결과 0.045초보다 무려 71% 빠른 결과입니다 ! LMS 덕분에 10장씩 batch로 돌리니까 더 빨라진 것이지요. 결국 LMS를 사용하면 오히려 더 빠른 성능을 낼 수도 있는 것입니다.
2017년 8월 16일 수요일
Minsky 서버를 위한 IBM KVM switch 옵션 소개
Minsky 서버에는 일반 범용 KVM switch를 연결해서 사용하시면 됩니다. 그래서 흔히 IBM의 정품 KVM switch 제품은 없다고 생각하실 수 있으나, 실은 있습니다. 다음의 것들을 주문하시면 됩니다.
7316-TF4 Rack-Mounted Flat Panel Console Kit 1:7316 Model TF4 1 4269 Cable, USB Conversion Option -- 1.5 meters 4
4283 IBM 1x8 Rack Console Switch 1
8896 USB Travel Keyboard with Cable, Korean 1
9911 Power Cord (4M) Specify -- All (Standard rack power cord) 1
저 위에 명기된 feature code (FC) 4283의 1x8 Rack Console Switch라는 것은 현재 Lenovo OEM으로 판매되는 LCM2 콘솔 스위치와 크게 다르지 않습니다. 모양은 아래와 같습니다.
(출처 : http://www-01.ibm.com/support/docview.wss?uid=tss1fq120703 )
다만 보시다시피 이 KVM 스위치에는 ARI port가 8개 밖에 없어서 언듯 보면 서버 8대까지만 연결된다고 생각하실 수도 있습니다만, 그렇지는 않습니다. Daisy-chain 방식으로 연결하면 최대 128대의 서버를 연결할 수 있습니다.
그렇게 daisy-chain 방식으로 연결하기 위해서 필요한 것이 fc 4269 USB Conversion Option cable입니다. 이것은 이렇게 생겼습니다.
(출처 : http://www-01.ibm.com/support/docview.wss?uid=tss1fq120703 )
이건 굳이 daisy-chain 방식으로 하지 않는다고 해도 잘 쓸 수 있는 cable입니다. 위의 그림에서 파란색 RGB port는 당연히 Minsky 서버의 video port에 연결되는 것이고, USB는 Minsky 서버의 USB에 연결되어 keyboard/mouse를 연결하는 것입니다. 그림 오른쪽에 보이는 뭔가 두껍고 port가 2개 나와 있는 것이 KVM switch에 연결되는 port입니다. Port가 2개 있는 이유는 간단합니다. 1개는 KVM switch와 연결되고, 나머지 하나는 다른 서버와 연결되는 fc 4269 USB Conversion Option cable의 port에 연결되는 것입니다. 아래 그림처럼요.
(출처 : https://lenovopress.com/tips0730 )
보시다시피 이 연결을 위해서는 CAT 5 cable이 필요합니다. 이게 별거 아니고, 그냥 UTP로 된 ethernet cable입니다. 이 CAT 5 cable은 IBM fc 4269에 포함되어 있지 않으므로 일반 UTP cable로 따로 준비해두셔야 합니다.
IBM fc 4269에는 저 USB Conversion Option cable이 4개씩 포함되어 있습니다. 따라서 위의 예처럼 fc 4269의 수량을 4개로 하면 USB Conversion Option cable을 16개 받으시게 됩니다. 그러면 최대 16대의 서버를 저 KVM switch에 연결하실 수 있는 것이지요. 다시 말씀드리지만 그렇게 16대의 서버 연결을 위해서는 fc 4269 외에도 CAT 5 cable (UTP cable)을 32개 별도로 준비하셔야 합니다.
7316-TF4 Rack-Mounted Flat Panel Console Kit 1:7316 Model TF4 1 4269 Cable, USB Conversion Option -- 1.5 meters 4
4283 IBM 1x8 Rack Console Switch 1
8896 USB Travel Keyboard with Cable, Korean 1
9911 Power Cord (4M) Specify -- All (Standard rack power cord) 1
저 위에 명기된 feature code (FC) 4283의 1x8 Rack Console Switch라는 것은 현재 Lenovo OEM으로 판매되는 LCM2 콘솔 스위치와 크게 다르지 않습니다. 모양은 아래와 같습니다.
(출처 : http://www-01.ibm.com/support/docview.wss?uid=tss1fq120703 )
다만 보시다시피 이 KVM 스위치에는 ARI port가 8개 밖에 없어서 언듯 보면 서버 8대까지만 연결된다고 생각하실 수도 있습니다만, 그렇지는 않습니다. Daisy-chain 방식으로 연결하면 최대 128대의 서버를 연결할 수 있습니다.
그렇게 daisy-chain 방식으로 연결하기 위해서 필요한 것이 fc 4269 USB Conversion Option cable입니다. 이것은 이렇게 생겼습니다.
(출처 : http://www-01.ibm.com/support/docview.wss?uid=tss1fq120703 )
이건 굳이 daisy-chain 방식으로 하지 않는다고 해도 잘 쓸 수 있는 cable입니다. 위의 그림에서 파란색 RGB port는 당연히 Minsky 서버의 video port에 연결되는 것이고, USB는 Minsky 서버의 USB에 연결되어 keyboard/mouse를 연결하는 것입니다. 그림 오른쪽에 보이는 뭔가 두껍고 port가 2개 나와 있는 것이 KVM switch에 연결되는 port입니다. Port가 2개 있는 이유는 간단합니다. 1개는 KVM switch와 연결되고, 나머지 하나는 다른 서버와 연결되는 fc 4269 USB Conversion Option cable의 port에 연결되는 것입니다. 아래 그림처럼요.
(출처 : https://lenovopress.com/tips0730 )
보시다시피 이 연결을 위해서는 CAT 5 cable이 필요합니다. 이게 별거 아니고, 그냥 UTP로 된 ethernet cable입니다. 이 CAT 5 cable은 IBM fc 4269에 포함되어 있지 않으므로 일반 UTP cable로 따로 준비해두셔야 합니다.
IBM fc 4269에는 저 USB Conversion Option cable이 4개씩 포함되어 있습니다. 따라서 위의 예처럼 fc 4269의 수량을 4개로 하면 USB Conversion Option cable을 16개 받으시게 됩니다. 그러면 최대 16대의 서버를 저 KVM switch에 연결하실 수 있는 것이지요. 다시 말씀드리지만 그렇게 16대의 서버 연결을 위해서는 fc 4269 외에도 CAT 5 cable (UTP cable)을 32개 별도로 준비하셔야 합니다.
2017년 8월 7일 월요일
POWER9 + Volta의 Cache Coherence : preview
아래 URL은 주로 엔터프라이즈 컴퓨팅 및 수퍼컴 이슈를 다루는 Nextplatform이라는 매체에서 IBM의 Vice President이자 수퍼컴 전문가인 David Turek과 인터뷰한 기사입니다. David Turek은 저도 실무 차원에서 두어번 teleconference를 한 적이 있는 분인데, 높은 곳에서 호령만 하는 임원이 아니라 진짜 실무 engineer입니다. 이 분은 현재 세계에서 가장 뛰어난 수퍼컴이 될 Sierra와 Summit을 구축하는 CORAL (Collaboration of Oak Ridge, Argonne, and Livermore) 프로젝트를 수행하고 있습니다.
https://www.nextplatform.com/2017/06/21/thinking-cognitive-hpc-nexus-big-blue/
여기서 눈에 띄는 부분은 아래 내용입니다.
TPM: No one else is going to have this coherence between the CPU and the GPU, although AMD might be able to do it now that it is delivering both Epyc processors and Radeon Instinct GPU accelerators. It certain has done some work on coherency in the past with its APUs and that technology could be applied to CPUs and discrete GPUs not on a single die or in a single package. But for now, only Power9 has NVLink and Intel is not offering something that looks like NVLink between its Xeons or Xeon Phis and other types of accelerators. The point is, no one has this yet except IBM and Nvidia.
Dave Turek: Correct. I was down in an exascale conference a couple of weeks ago in Princeton, and Jack Wells, one of the people at Oak Ridge National Laboratories, got up and was talking about progress on the CORAL systems and said that one of the biggest things is going to be this coherency. Forget flops and all of that, the big deal is the coherency. This is a bit under the radar because people are only talking about the technical features of Summit and Sierra machines and they have not realized the impact of this coherence.
이 대화 부분을 요약하면 이렇습니다.
"CORAL 수퍼컴에서는 세계 수퍼컴 최초로 CPU와 GPU간에 coherence가 구현되는데, 진짜 주목할 부분은 (흔히 수퍼컴 성능을 이야기할 때 사용되는) 테라플롭스(TFLOPS) 따위가 아니라 바로 coherence다. 업계 사람들조차도 아직 이 기술의 중요성에 대해 잘 모른다."
이렇게 중요한 기술이라는 coherence라는 것이 대체 무엇일까요 ? 일반적인 cache coherence라는 것은 여러 곳의 메모리/캐쉬에 저장된 data를 일관성있게 유지하는 것을 말합니다. 이는 여러개의 processor를 이용하는 경우 데이터 정합성을 위해 반드시 필요한 기능이며, 대형 SMP 서버의 성능은 CPU와 메모리 등의 성능 외에도, 이 cache coherence를 어떻게 유지하느냐에 달려 있습니다. 아래 그림을 보시면 아마 cache coherence의 개념을 쉽게 이해하실 수 있을 겁니다. (그림 소스 : https://en.wikipedia.org/wiki/Cache_coherence )
여기서 Turek이 이야기하는 coherence라는 것은 CPU와 GPU 간의 coherence를 이야기하는 것입니다. 즉, 원래 CPU는 서버 메모리를, GPU는 GPU 메모리를 각각 따로 가지고 있지만, POWER9과 Volta GPU에서는 CPU와 GPU가 그 각각의 메모리를 마치 한덩어리인 것처럼 사용할 수 있게 된다는 것입니다.
기존 GPU 컴퓨팅에서 매우 골치 아팠던 부분은 크게 2가지였습니다.
1) GPU 메모리 크기의 한계
2) GPU가 연결된 시스템 버스 (PCIe Gen3) 속도의 한계
모든 GPU 컴퓨팅에서, GPU가 뭔가 연산을 하려면 (그것이 전통적 HPC이건 Deep Learning이건) 해당 logic과 data를 CPU 메모리로부터 copy하여 GPU 메모리에 저장부터 해야 했습니다. 그런데 위의 2가지 문제가 항상 그 작업을 어렵게 했습니다. 즉, 보통 12GB ~ 24GB 정도인 GPU 메모리 크기 때문에 원하는 data를 다 집어 넣을 수도 없고, 또 PCIe를 통한 data copy 속도가 충분히 빠르지 않아서 문제였던 것입니다. Deep learning에 있어서도 이 문제는 마찬가지였습니다. 가령 이미지 데이터를 이용해 신경망을 training시킬 때, 한꺼번에 1024장의 이미지를 처리하면 (batch_size=1024) 좋을텐데 그럴 경우 GPU 메모리가 넘치므로 에러가 났습니다. 또 자율주행이나 자연어 처리 (NLP) 처럼 큰 모델을 사용해야 하는 경우엔 아예 GPU 메모리 상에 모델 자체가 들어가질 않아서 돌릴 수가 없었지요. 그런 경우를 해결하기 위해서 여러장의 GPU에 모델을 쪼개 넣는 model-parallelism을 구현하기도 합니다만, 그런 model-parallelism은 구현하기 쉽지 않은 것이 사실입니다.
이런 상황에서 NVIDIA와 IBM이 내놓은 하드웨어 기술 하나가 많은 것을 바꿔놓습니다. 바로 NVLink입니다. NVLink는 GPU 연결에 PCIe 대신 사용하는 시스템 버스 기술로서, 특히 IBM은 POWER8 프로세서에 NVLink port를 박아넣음으로써 CPU와 GPU가 40GB/sec X 2 = 80GB/sec로 통신하여 기존 PCIe 대비 2.5배의 대역폭을 낼 수 있도록 만들었습니다. 이는 NVLink가 달린 P100 GPU를 사용하더라도 Intel Xeon 프로세서와 GPU 간은 여전히 PCIe를 써야 하는 x86 서버에서는 불가능한 기술로서, 현재는 IBM Minsky 서버 (S822LC for HPC)에만 구현되어 있습니다.
Minsky 서버의 NVLink 기술은 비단 GPU-GPU, 그리고 CPU-GPU 간의 대역폭을 높였다는 것 외에도 CUDA 8과 Pascal 아키텍처와 함께 근본적인 변화를 가져왔습니다. 바로 Unified Memory입니다.
Unified Memory(UM 혹은 UVM)는 GPU가 서버 RAM을 마치 GPU 메모리인 것처럼 사용할 수 있도록 해주는 기술입니다. 이를 이용하면 GPU 메모리 크기로 인해서 오는 많은 불편함을 해결할 수 있습니다. 그러나 이 UM 기술이 CUDA 6.5부터 지원되었음에도 여태까지 그 활용도는 낮았습니다. 이유는 성능 저하였습니다. 아무래도 DDR3로 되어 있는 서버 메모리가 GDDR5인 GPU 메모리보다는 많이 느렸거든요. 그건 서버 메모리가 DDR4로 바뀌고 GPU 메모리가 HBM2로 바뀐 다음에도 마찬가지입니다. 메모리들이 빨리질 수록 그 연결 기술인 PCIe의 한계가 더 뚜렷이 드러날 뿐이었지요. 그런 상황에서 PCIe를 대체하는 NVLink 기술의 도입은 그 성능 저하 문제를 크게 해결해줄 수 있게 된 것입니다.
여전히 UM 사용은 일반화되어 있지 않습니다. 알고보면 일반 NVLink 1개 link의 대역폭은 40GB/sec로서, PCIe gen3의 32GB/sec보다 엄청나게 빠르다고 할 수도 없습니다. 게다가 대부분의 GPU 서버들이 x86 프로세서를 장착하고 있는데, NVLink P100 GPU를 탑재한 서버라고 해도 x86 프로세서와는 PCIe로 통신해야 합니다. 즉, UM 자체에는 여전히 PCIe를 써야 했습니다. 이에 비해, IBM POWER8 프로세서를 탑재한 Minsky 서버는 POWER8 프로세서와 P100 GPU 간을 NVLink 2개를 aggregation시켜 40+40=80GB/sec로 구현했습니다. 다른 NVLink P100 GPU 서버에 비해 2.5배의 대역폭인 셈이지요.
그렇다면 Minsky에서는 UM을 적극적으로 활용하고 있느냐 ? 예, 실은 이제 막 시작되었습니다. 바로 PowerAI의 Large Model Support (LMS)를 통해서입니다. 이는 바로 최근인 8월 5일 (문서에는 7월 25일이라고 되어 있지만 실제로는 더 늦었습니다) 발표된 새로운 기능으로서, UM 기능을 enable한 IBM 버전의 caffe (caffe-ibm)의 옵션 형태로 구현되었습니다. 이에 대해서는 아래 URL에 자세히 나와 있습니다.
https://developer.ibm.com/linuxonpower/deep-learning-powerai/releases/
그나마 클릭하셔서 자세히 보시기 귀찮으신 분들을 위해 핵심부분만 따오면 아래와 같습니다.
Large Model Support (LMS)
IBM caffe를 사용하실 때, -lms <size in KB> 라는 옵션이 추가되었습니다. 가령 -lms 409600 이라고 해놓으시면 400MB 이상의 메모리 chunk는 CPU에 유지하고, 필요할 때만 GPU 메모리로 가져옵니다. 만약 LMS를 disable하고 싶으시면 -lms 10000000000 처럼 엄청나게 큰 메모리 값을 주시면 됩니다. 또 -lms_frac <0에서 1.0 사이의 값>이라는 옵션을 주셔도 되는데, 가령 -lms_frac 0.4로 준면, 최소 40% 이상의 GPU 메모리를 사용할 때만 LMS 기능이 활성화됩니다. 작은 신경망을 training하실 때는 굳이 LMS를 쓰실 필요가 없으니 이 옵션을 쓰시는 것이 좋습니다.
이 LMS 기능은 이번에는 IBM caffe에만 적용되었습니다만, 점차 더 확대하여 tensorflow에도 적용할 예정입니다.
그런데 이 글 초반에 언급했던 David Turek의 인터뷰 내용을 보면 Cache Coherence라는 것은 POWER8 + Pascal GPU가 아닌, POWER9 + Volta GPU에서 처음으로 도입되는 것처럼 씌여 있습니다. 이건 왜 그럴까요 ? 분명히 Cache Coherence는 Unified Memory보다 더 진전된 기능 같은데, 구체적으로 어떤 점이 더 나아지는 것일까요 ?
이에 대해서는 다음 URL에 꽤 자세히 나와 있습니다.
http://on-demand.gputechconf.com/gtc/2017/presentation/s7285-nikolay-sakharnykh-unified-memory-on-pascal-and-volta.pdf
여기서는 간략하게 표로 정리해보았습니다.
Cache coherence에서 UM으로부터 더 향상된 점을 좀더 쉽게 표현하면 이렇습니다. Access counter 기능을 이용하여 이젠 access가 잦은 'hot page'들만 GPU로 migration하는 것이 가능해졌고, 또 GPU가 서버 메모리를 access하는 것 뿐만 아니라 CPU도 GPU 메모리를 CPU cache 레벨까지 써서 자유롭게 access하는 것이 가능해진 것입니다. 그 의미는 간단합니다. GPU 메모리 크기로 인해 제약받았던 기존 GPU 프로그래밍이 상식적인 수준의 성능 저하만 감내한다면 훨씬 더 간편해진다는 것입니다.
적정 수준의 성능 저하만 감내하면 편해진다는데 그 적정 수준이라는 것이 어느 정도이고 또 얼마나 편해지는 것일까요 ? 아직 POWER9 + Volta에 대해서는 자료가 나오지 않았으므로 지금은 POWER8 + Pascal의 UM의 경우를 통해서 짐작해보시지요.
전통적 HPC coding에서도 그렇겠습니다만, deep learning 관점에서도 UM 또는 cache coherence가 주는 혜택은 명백합니다. 한마디로, 과거에는 아예 training을 돌릴 수 없었던 큰 model도 training이 가능해집니다. 기존에는 여러장의 GPU에 걸쳐 복잡한 model-parallelism을 구현해야만 가능했던 training이 훨씬 쉽게 1장의 GPU에서도 가능해지는 것입니다. 또한 과거에는 한번에 (가령) 16장의 이미지만 training 시킬 수 있었다면, 이젠 그 24배인 384장을 한꺼번에 training 시킬 수 있게 됩니다.
다만 이런 편리함은 필연적으로 성능 저하를 불러오는 것이 사실입니다. 아무래도 서버의 DDR4 메모리가 GPU의 HBM2 메모리보다는 훨씬 느린데다, 그걸 PCIe(32GB/sec)가 아닌 NVLink * 2개(80GB/sec)로 연결한다고 해도 메모리 access 속도(115GB/sec)보다는 느리니까요.
아래는 x86 서버에서 NVIDIA Quadro GP100 (Pascal) GPU를 이용해서 Unified Memory로 oversubscription을 한 경우의 deep learning 속도입니다. 그냥 GPU 메모리만 사용할 때에 비해, 속도가 5~9배 느려진 것을 보실 수 있습니다. 이는 x86과 Quadro GP100 사이가 PCIe(32GB/sec)로 연결되었기 때문입니다.
그러나 NVLink *2개(80GB/sec)로 연결된 경우는 어떨까요 ? NVLink *2개는 PCIe보다 2.5배 더 대역폭이 크기 때문에, 산술적으로는 대략 2~2.5배 정도만 느려질 것으로 예상됩니다. 아직 PowerAI의 LMS를 이용한 deep learning training 성능 테스트 결과가 공식적으로 발표된 것은 없습니다. 그러나 아래 HPC의 일종인 AMR (adaptive mesh refinement technique)에 대해 NVIDIA가 POWER8 + Pascal의 oversubscription 기능을 이용해 테스트한 바를 보면 정말 2배 정도만 느려지는 것을 보실 수 있습니다. 과거에는 아예 돌릴 수 없었던 큰 working set을 POWER8 + Pascal의 oversubscription 기능을 이용하면 1장의 GPU로도 훌륭히 수행할 수 있는 것입니다.
2018년에 CORAL 프로젝트의 두 수퍼컴 클러스터인 Summit과 Sierra가 구축되고나면 cache coherence에 대한 좀더 많은 성능 결과치가 나올 것으로 기대합니다.
Source :
https://devblogs.nvidia.com/parallelforall/beyond-gpu-memory-limits-unified-memory-pascal/
http://on-demand.gputechconf.com/gtc/2016/presentation/s6224-mark-harris.pdf
http://cudacoe.m.gsic.titech.ac.jp/lecture/lecture-wiki/index.php?plugin=attach&refer=hpc2016&openfile=hpc2016_ito.pdf
http://on-demand.gputechconf.com/gtc/2017/presentation/s7285-nikolay-sakharnykh-unified-memory-on-pascal-and-volta.pdf
https://www.nextplatform.com/2017/06/21/thinking-cognitive-hpc-nexus-big-blue/
여기서 눈에 띄는 부분은 아래 내용입니다.
TPM: No one else is going to have this coherence between the CPU and the GPU, although AMD might be able to do it now that it is delivering both Epyc processors and Radeon Instinct GPU accelerators. It certain has done some work on coherency in the past with its APUs and that technology could be applied to CPUs and discrete GPUs not on a single die or in a single package. But for now, only Power9 has NVLink and Intel is not offering something that looks like NVLink between its Xeons or Xeon Phis and other types of accelerators. The point is, no one has this yet except IBM and Nvidia.
Dave Turek: Correct. I was down in an exascale conference a couple of weeks ago in Princeton, and Jack Wells, one of the people at Oak Ridge National Laboratories, got up and was talking about progress on the CORAL systems and said that one of the biggest things is going to be this coherency. Forget flops and all of that, the big deal is the coherency. This is a bit under the radar because people are only talking about the technical features of Summit and Sierra machines and they have not realized the impact of this coherence.
이 대화 부분을 요약하면 이렇습니다.
"CORAL 수퍼컴에서는 세계 수퍼컴 최초로 CPU와 GPU간에 coherence가 구현되는데, 진짜 주목할 부분은 (흔히 수퍼컴 성능을 이야기할 때 사용되는) 테라플롭스(TFLOPS) 따위가 아니라 바로 coherence다. 업계 사람들조차도 아직 이 기술의 중요성에 대해 잘 모른다."
이렇게 중요한 기술이라는 coherence라는 것이 대체 무엇일까요 ? 일반적인 cache coherence라는 것은 여러 곳의 메모리/캐쉬에 저장된 data를 일관성있게 유지하는 것을 말합니다. 이는 여러개의 processor를 이용하는 경우 데이터 정합성을 위해 반드시 필요한 기능이며, 대형 SMP 서버의 성능은 CPU와 메모리 등의 성능 외에도, 이 cache coherence를 어떻게 유지하느냐에 달려 있습니다. 아래 그림을 보시면 아마 cache coherence의 개념을 쉽게 이해하실 수 있을 겁니다. (그림 소스 : https://en.wikipedia.org/wiki/Cache_coherence )
(Cache coherence가 되는 경우)
(Cache coherence가 안 되는 경우)
여기서 Turek이 이야기하는 coherence라는 것은 CPU와 GPU 간의 coherence를 이야기하는 것입니다. 즉, 원래 CPU는 서버 메모리를, GPU는 GPU 메모리를 각각 따로 가지고 있지만, POWER9과 Volta GPU에서는 CPU와 GPU가 그 각각의 메모리를 마치 한덩어리인 것처럼 사용할 수 있게 된다는 것입니다.
기존 GPU 컴퓨팅에서 매우 골치 아팠던 부분은 크게 2가지였습니다.
1) GPU 메모리 크기의 한계
2) GPU가 연결된 시스템 버스 (PCIe Gen3) 속도의 한계
모든 GPU 컴퓨팅에서, GPU가 뭔가 연산을 하려면 (그것이 전통적 HPC이건 Deep Learning이건) 해당 logic과 data를 CPU 메모리로부터 copy하여 GPU 메모리에 저장부터 해야 했습니다. 그런데 위의 2가지 문제가 항상 그 작업을 어렵게 했습니다. 즉, 보통 12GB ~ 24GB 정도인 GPU 메모리 크기 때문에 원하는 data를 다 집어 넣을 수도 없고, 또 PCIe를 통한 data copy 속도가 충분히 빠르지 않아서 문제였던 것입니다. Deep learning에 있어서도 이 문제는 마찬가지였습니다. 가령 이미지 데이터를 이용해 신경망을 training시킬 때, 한꺼번에 1024장의 이미지를 처리하면 (batch_size=1024) 좋을텐데 그럴 경우 GPU 메모리가 넘치므로 에러가 났습니다. 또 자율주행이나 자연어 처리 (NLP) 처럼 큰 모델을 사용해야 하는 경우엔 아예 GPU 메모리 상에 모델 자체가 들어가질 않아서 돌릴 수가 없었지요. 그런 경우를 해결하기 위해서 여러장의 GPU에 모델을 쪼개 넣는 model-parallelism을 구현하기도 합니다만, 그런 model-parallelism은 구현하기 쉽지 않은 것이 사실입니다.
이런 상황에서 NVIDIA와 IBM이 내놓은 하드웨어 기술 하나가 많은 것을 바꿔놓습니다. 바로 NVLink입니다. NVLink는 GPU 연결에 PCIe 대신 사용하는 시스템 버스 기술로서, 특히 IBM은 POWER8 프로세서에 NVLink port를 박아넣음으로써 CPU와 GPU가 40GB/sec X 2 = 80GB/sec로 통신하여 기존 PCIe 대비 2.5배의 대역폭을 낼 수 있도록 만들었습니다. 이는 NVLink가 달린 P100 GPU를 사용하더라도 Intel Xeon 프로세서와 GPU 간은 여전히 PCIe를 써야 하는 x86 서버에서는 불가능한 기술로서, 현재는 IBM Minsky 서버 (S822LC for HPC)에만 구현되어 있습니다.
Minsky 서버의 NVLink 기술은 비단 GPU-GPU, 그리고 CPU-GPU 간의 대역폭을 높였다는 것 외에도 CUDA 8과 Pascal 아키텍처와 함께 근본적인 변화를 가져왔습니다. 바로 Unified Memory입니다.
Unified Memory(UM 혹은 UVM)는 GPU가 서버 RAM을 마치 GPU 메모리인 것처럼 사용할 수 있도록 해주는 기술입니다. 이를 이용하면 GPU 메모리 크기로 인해서 오는 많은 불편함을 해결할 수 있습니다. 그러나 이 UM 기술이 CUDA 6.5부터 지원되었음에도 여태까지 그 활용도는 낮았습니다. 이유는 성능 저하였습니다. 아무래도 DDR3로 되어 있는 서버 메모리가 GDDR5인 GPU 메모리보다는 많이 느렸거든요. 그건 서버 메모리가 DDR4로 바뀌고 GPU 메모리가 HBM2로 바뀐 다음에도 마찬가지입니다. 메모리들이 빨리질 수록 그 연결 기술인 PCIe의 한계가 더 뚜렷이 드러날 뿐이었지요. 그런 상황에서 PCIe를 대체하는 NVLink 기술의 도입은 그 성능 저하 문제를 크게 해결해줄 수 있게 된 것입니다.
여전히 UM 사용은 일반화되어 있지 않습니다. 알고보면 일반 NVLink 1개 link의 대역폭은 40GB/sec로서, PCIe gen3의 32GB/sec보다 엄청나게 빠르다고 할 수도 없습니다. 게다가 대부분의 GPU 서버들이 x86 프로세서를 장착하고 있는데, NVLink P100 GPU를 탑재한 서버라고 해도 x86 프로세서와는 PCIe로 통신해야 합니다. 즉, UM 자체에는 여전히 PCIe를 써야 했습니다. 이에 비해, IBM POWER8 프로세서를 탑재한 Minsky 서버는 POWER8 프로세서와 P100 GPU 간을 NVLink 2개를 aggregation시켜 40+40=80GB/sec로 구현했습니다. 다른 NVLink P100 GPU 서버에 비해 2.5배의 대역폭인 셈이지요.
그렇다면 Minsky에서는 UM을 적극적으로 활용하고 있느냐 ? 예, 실은 이제 막 시작되었습니다. 바로 PowerAI의 Large Model Support (LMS)를 통해서입니다. 이는 바로 최근인 8월 5일 (문서에는 7월 25일이라고 되어 있지만 실제로는 더 늦었습니다) 발표된 새로운 기능으로서, UM 기능을 enable한 IBM 버전의 caffe (caffe-ibm)의 옵션 형태로 구현되었습니다. 이에 대해서는 아래 URL에 자세히 나와 있습니다.
https://developer.ibm.com/linuxonpower/deep-learning-powerai/releases/
그나마 클릭하셔서 자세히 보시기 귀찮으신 분들을 위해 핵심부분만 따오면 아래와 같습니다.
Large Model Support (LMS)
IBM caffe를 사용하실 때, -lms <size in KB> 라는 옵션이 추가되었습니다. 가령 -lms 409600 이라고 해놓으시면 400MB 이상의 메모리 chunk는 CPU에 유지하고, 필요할 때만 GPU 메모리로 가져옵니다. 만약 LMS를 disable하고 싶으시면 -lms 10000000000 처럼 엄청나게 큰 메모리 값을 주시면 됩니다. 또 -lms_frac <0에서 1.0 사이의 값>이라는 옵션을 주셔도 되는데, 가령 -lms_frac 0.4로 준면, 최소 40% 이상의 GPU 메모리를 사용할 때만 LMS 기능이 활성화됩니다. 작은 신경망을 training하실 때는 굳이 LMS를 쓰실 필요가 없으니 이 옵션을 쓰시는 것이 좋습니다.
이 LMS 기능은 이번에는 IBM caffe에만 적용되었습니다만, 점차 더 확대하여 tensorflow에도 적용할 예정입니다.
그런데 이 글 초반에 언급했던 David Turek의 인터뷰 내용을 보면 Cache Coherence라는 것은 POWER8 + Pascal GPU가 아닌, POWER9 + Volta GPU에서 처음으로 도입되는 것처럼 씌여 있습니다. 이건 왜 그럴까요 ? 분명히 Cache Coherence는 Unified Memory보다 더 진전된 기능 같은데, 구체적으로 어떤 점이 더 나아지는 것일까요 ?
이에 대해서는 다음 URL에 꽤 자세히 나와 있습니다.
http://on-demand.gputechconf.com/gtc/2017/presentation/s7285-nikolay-sakharnykh-unified-memory-on-pascal-and-volta.pdf
여기서는 간략하게 표로 정리해보았습니다.
Cache coherence에서 UM으로부터 더 향상된 점을 좀더 쉽게 표현하면 이렇습니다. Access counter 기능을 이용하여 이젠 access가 잦은 'hot page'들만 GPU로 migration하는 것이 가능해졌고, 또 GPU가 서버 메모리를 access하는 것 뿐만 아니라 CPU도 GPU 메모리를 CPU cache 레벨까지 써서 자유롭게 access하는 것이 가능해진 것입니다. 그 의미는 간단합니다. GPU 메모리 크기로 인해 제약받았던 기존 GPU 프로그래밍이 상식적인 수준의 성능 저하만 감내한다면 훨씬 더 간편해진다는 것입니다.
적정 수준의 성능 저하만 감내하면 편해진다는데 그 적정 수준이라는 것이 어느 정도이고 또 얼마나 편해지는 것일까요 ? 아직 POWER9 + Volta에 대해서는 자료가 나오지 않았으므로 지금은 POWER8 + Pascal의 UM의 경우를 통해서 짐작해보시지요.
전통적 HPC coding에서도 그렇겠습니다만, deep learning 관점에서도 UM 또는 cache coherence가 주는 혜택은 명백합니다. 한마디로, 과거에는 아예 training을 돌릴 수 없었던 큰 model도 training이 가능해집니다. 기존에는 여러장의 GPU에 걸쳐 복잡한 model-parallelism을 구현해야만 가능했던 training이 훨씬 쉽게 1장의 GPU에서도 가능해지는 것입니다. 또한 과거에는 한번에 (가령) 16장의 이미지만 training 시킬 수 있었다면, 이젠 그 24배인 384장을 한꺼번에 training 시킬 수 있게 됩니다.
다만 이런 편리함은 필연적으로 성능 저하를 불러오는 것이 사실입니다. 아무래도 서버의 DDR4 메모리가 GPU의 HBM2 메모리보다는 훨씬 느린데다, 그걸 PCIe(32GB/sec)가 아닌 NVLink * 2개(80GB/sec)로 연결한다고 해도 메모리 access 속도(115GB/sec)보다는 느리니까요.
(x86 서버에서는 저 붉은색의 PCIe가 병목이 될 수 밖에 없습니다)
아래는 x86 서버에서 NVIDIA Quadro GP100 (Pascal) GPU를 이용해서 Unified Memory로 oversubscription을 한 경우의 deep learning 속도입니다. 그냥 GPU 메모리만 사용할 때에 비해, 속도가 5~9배 느려진 것을 보실 수 있습니다. 이는 x86과 Quadro GP100 사이가 PCIe(32GB/sec)로 연결되었기 때문입니다.
그러나 NVLink *2개(80GB/sec)로 연결된 경우는 어떨까요 ? NVLink *2개는 PCIe보다 2.5배 더 대역폭이 크기 때문에, 산술적으로는 대략 2~2.5배 정도만 느려질 것으로 예상됩니다. 아직 PowerAI의 LMS를 이용한 deep learning training 성능 테스트 결과가 공식적으로 발표된 것은 없습니다. 그러나 아래 HPC의 일종인 AMR (adaptive mesh refinement technique)에 대해 NVIDIA가 POWER8 + Pascal의 oversubscription 기능을 이용해 테스트한 바를 보면 정말 2배 정도만 느려지는 것을 보실 수 있습니다. 과거에는 아예 돌릴 수 없었던 큰 working set을 POWER8 + Pascal의 oversubscription 기능을 이용하면 1장의 GPU로도 훌륭히 수행할 수 있는 것입니다.
2018년에 CORAL 프로젝트의 두 수퍼컴 클러스터인 Summit과 Sierra가 구축되고나면 cache coherence에 대한 좀더 많은 성능 결과치가 나올 것으로 기대합니다.
Source :
https://devblogs.nvidia.com/parallelforall/beyond-gpu-memory-limits-unified-memory-pascal/
http://on-demand.gputechconf.com/gtc/2016/presentation/s6224-mark-harris.pdf
http://cudacoe.m.gsic.titech.ac.jp/lecture/lecture-wiki/index.php?plugin=attach&refer=hpc2016&openfile=hpc2016_ito.pdf
http://on-demand.gputechconf.com/gtc/2017/presentation/s7285-nikolay-sakharnykh-unified-memory-on-pascal-and-volta.pdf
2017년 8월 2일 수요일
Minsky 서버에서의 jupyter notebook 설치/사용
Minsky 등 ppc64le 환경에서도 당연히 jupyter notebook 사용이 가능합니다. Miniconda를 이용하여 간단히 설치가 가능한데, Miniconda 자체의 설치에 대해서는 여기를 클릭하세요.
일단 Miniconda가 설치되어 conda를 쓸 수 있게 되면 아래와 같이 하면 됩니다.
mirhenge@powerai:~/miniconda2$ conda install jupyter
Fetching package metadata .........
Solving package specifications: .
Package plan for installation in environment /home/mirhenge/miniconda2:
The following NEW packages will be INSTALLED:
backports: 1.0-py27_0
backports_abc: 0.5-py27_0
bleach: 1.5.0-py27_0
configparser: 3.5.0-py27_0
decorator: 4.0.11-py27_0
entrypoints: 0.2.2-py27_1
functools32: 3.2.3.2-py27_0
get_terminal_size: 1.0.0-py27_0
html5lib: 0.999-py27_0
ipykernel: 4.6.1-py27_0
ipython: 5.3.0-py27_0
ipython_genutils: 0.2.0-py27_0
ipywidgets: 6.0.0-py27_0
jinja2: 2.9.6-py27_0
jsonschema: 2.6.0-py27_0
jupyter: 1.0.0-py27_3
jupyter_client: 5.0.1-py27_0
jupyter_console: 5.1.0-py27_0
jupyter_core: 4.3.0-py27_0
libsodium: 1.0.10-0
markupsafe: 0.23-py27_2
mistune: 0.7.4-py27_0
nbconvert: 5.1.1-py27_0
nbformat: 4.3.0-py27_0
notebook: 5.0.0-py27_0
pandocfilters: 1.4.1-py27_0
path.py: 10.3.1-py27_0
pathlib2: 2.2.1-py27_0
pexpect: 4.2.1-py27_0
pickleshare: 0.7.4-py27_0
prompt_toolkit: 1.0.14-py27_0
ptyprocess: 0.5.1-py27_0
pygments: 2.2.0-py27_0
python-dateutil: 2.6.0-py27_0
pyzmq: 16.0.2-py27_0
scandir: 1.5-py27_0
simplegeneric: 0.8.1-py27_1
singledispatch: 3.4.0.3-py27_0
ssl_match_hostname: 3.4.0.2-py27_1
terminado: 0.6-py27_0
testpath: 0.3-py27_0
tornado: 4.5.1-py27_0
traitlets: 4.3.2-py27_0
wcwidth: 0.1.7-py27_0
widgetsnbextension: 2.0.0-py27_0
zeromq: 4.1.5-0
The following packages will be UPDATED:
conda: 4.3.14-py27_0 --> 4.3.21-py27_0
Proceed ([y]/n)? y
...
entrypoints-0. 100% |#########################################| Time: 0:00:00 15.14 MB/s
jupyter_core-4 100% |#########################################| Time: 0:00:00 304.20 kB/s
pickleshare-0. 100% |#########################################| Time: 0:00:00 23.47 MB/s
testpath-0.3-p 100% |#########################################| Time: 0:00:00 35.33 MB/s
tornado-4.5.1- 100% |#########################################| Time: 0:00:00 613.23 kB/s
ipython-5.3.0- 100% |#########################################| Time: 0:00:01 851.46 kB/s
jupyter_client 100% |#########################################| Time: 0:00:00 329.04 kB/s
nbformat-4.3.0 100% |#########################################| Time: 0:00:00 360.09 kB/s
terminado-0.6- 100% |#########################################| Time: 0:00:00 20.31 MB/s
conda-4.3.21-p 100% |#########################################| Time: 0:00:01 503.31 kB/s
ipykernel-4.6. 100% |#########################################| Time: 0:00:00 249.29 kB/s
nbconvert-5.1. 100% |#########################################| Time: 0:00:00 465.37 kB/s
jupyter_consol 100% |#########################################| Time: 0:00:00 39.17 MB/s
notebook-5.0.0 100% |#########################################| Time: 0:00:02 2.07 MB/s
widgetsnbexten 100% |#########################################| Time: 0:00:01 762.68 kB/s
ipywidgets-6.0 100% |#########################################| Time: 0:00:00 167.32 kB/s
jupyter-1.0.0- 100% |#########################################| Time: 0:00:00 11.56 MB/s
이제 다시 login을 하든가 ~/.bashrc를 새로 수행하면 PATH 환경변수가 잡히면서 jupyter 사용이 가능합니다.
mirhenge@powerai:~/miniconda2$ which jupyter
/home/mirhenge/miniconda2/bin/jupyter
Web browser로는 firefox를 사용하시면 됩니다. 여기서는 X 환경을 위해 tightvncviewer를 이용하므로 DISPLAY를 unix:0으로 설정합니다.
mirhenge@powerai:~/miniconda2$ export BROWSER=/usr/bin/firefox
mirhenge@powerai:~/miniconda2$ export DISPLAY=unix:0
이제 jupyter notebook를 구동하면 다음과 같은 메시지가 나옵니다.
mirhenge@powerai:~/miniconda2$ jupyter notebook
[I 13:40:32.487 NotebookApp] Serving notebooks from local directory: /home/mirhenge/miniconda2
[I 13:40:32.488 NotebookApp] 0 active kernels
[I 13:40:32.488 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=9d13bb86a1a68d0c408740c877045adb2278535287737f5f
[I 13:40:32.488 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 13:40:32.488 NotebookApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://localhost:8888/?token=9d13bb86a1a68d0c408740c877045adb2278535287737f5f
[I 13:40:35.286 NotebookApp] Accepting one-time-token-authenticated connection from 127.0.0.1
이때 tightvncserver를 설정해 놓았다면 그 화면을 통해 vncviewer에서 browser가 열립니다.
이후로는 vncviewer를 통하지 않고도 remote에서도 web browser를 이용해 접속할 수 있도록 아래와 같이 설정 파일을 생성하고 이어서 수정해줍니다.
mirhenge@powerai:~$ jupyter notebook --generate-config
mirhenge@powerai:~$ vi /home/mirhenge/.jupyter/jupyter_notebook_config.py
...
## The IP address the notebook server will listen on.
#c.NotebookApp.ip = 'localhost'
c.NotebookApp.ip = '*'
이제 다시 start해주면 굳이 local server에서 띄운 browser 뿐만 아니라 외부 PC에서 띄운 browser로도 접속이 가능합니다.
mirhenge@powerai:~$ jupyter notebook
[W 13:57:17.150 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using encryption. This is not recommended.
[I 13:57:17.158 NotebookApp] Serving notebooks from local directory: /home/mirhenge
[I 13:57:17.158 NotebookApp] 0 active kernels
[I 13:57:17.158 NotebookApp] The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/?token=acde16ba9020fd7cc174d894f760772af7257c619579519d
[I 13:57:17.158 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 13:57:17.159 NotebookApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://localhost:8888/?token=acde16ba9020fd7cc174d894f760772af7257c619579519d
[I 13:57:18.245 NotebookApp] Accepting one-time-token-authenticated connection from 127.0.0.1
[I 13:57:32.011 NotebookApp] 302 GET / (211.109.178.33) 0.33ms
[I 13:57:32.165 NotebookApp] 302 GET /tree? (211.109.178.33) 0.54ms
이때 처음 접속할 때는 위에 display된 token(위의 붉은색 부분)을 copy & paste 해서 넣어야 합니다.
한번 테스트를 해봅니다. 다음과 같이 IBM lab service에서 만든 demo용 English --> French 번역 deep learning용 package를 다운로드 받습니다.
mirhenge@powerai:~$ git clone https://github.com/ppradhan01/dl-language-translation.git
Cloning into 'dl-language-translation'...
remote: Counting objects: 13, done.
remote: Total 13 (delta 0), reused 0 (delta 0), pack-reused 13
Unpacking objects: 100% (13/13), done.
Checking connectivity... done.
mirhenge@powerai:~$ cd dl-language-translation/
mirhenge@powerai:~/dl-language-translation$ ls
code.ipynb data helper.py problem_unittests.py README.md
mirhenge@powerai:~/dl-language-translation$ cd data
mirhenge@powerai:~/dl-language-translation/data$ ls
small_vocab_en small_vocab_fr
mirhenge@powerai:~/dl-language-translation/data$ head small_vocab_en
new jersey is sometimes quiet during autumn , and it is snowy in april .
the united states is usually chilly during july , and it is usually freezing in november .
california is usually quiet during march , and it is usually hot in june .
the united states is sometimes mild during june , and it is cold in september .
your least liked fruit is the grape , but my least liked is the apple .
his favorite fruit is the orange , but my favorite is the grape .
paris is relaxing during december , but it is usually chilly in july .
new jersey is busy during spring , and it is never hot in march .
our least liked fruit is the lemon , but my least liked is the grape .
the united states is sometimes busy during january , and it is sometimes warm in november .
mirhenge@powerai:~/dl-language-translation/data$ head small_vocab_fr
new jersey est parfois calme pendant l' automne , et il est neigeux en avril .
les états-unis est généralement froid en juillet , et il gèle habituellement en novembre .
california est généralement calme en mars , et il est généralement chaud en juin .
les états-unis est parfois légère en juin , et il fait froid en septembre .
votre moins aimé fruit est le raisin , mais mon moins aimé est la pomme .
son fruit préféré est l'orange , mais mon préféré est le raisin .
paris est relaxant en décembre , mais il est généralement froid en juillet .
new jersey est occupé au printemps , et il est jamais chaude en mars .
notre fruit est moins aimé le citron , mais mon moins aimé est le raisin .
les états-unis est parfois occupé en janvier , et il est parfois chaud en novembre .
이제 browser의 notebook에서, 위에서 download 받은 dl-language-translation directory로 찾아내려가 code.ipynb를 클릭하면 됩니다.
그러면 이제 notebook이 열리고, 필요시 위쪽 메뉴 bar에 있는 play 버튼 (player의 삼각형 버튼)을 눌러서 해당 code 부분을 직접 수행해볼 수도 있습니다.
일단 Miniconda가 설치되어 conda를 쓸 수 있게 되면 아래와 같이 하면 됩니다.
mirhenge@powerai:~/miniconda2$ conda install jupyter
Fetching package metadata .........
Solving package specifications: .
Package plan for installation in environment /home/mirhenge/miniconda2:
The following NEW packages will be INSTALLED:
backports: 1.0-py27_0
backports_abc: 0.5-py27_0
bleach: 1.5.0-py27_0
configparser: 3.5.0-py27_0
decorator: 4.0.11-py27_0
entrypoints: 0.2.2-py27_1
functools32: 3.2.3.2-py27_0
get_terminal_size: 1.0.0-py27_0
html5lib: 0.999-py27_0
ipykernel: 4.6.1-py27_0
ipython: 5.3.0-py27_0
ipython_genutils: 0.2.0-py27_0
ipywidgets: 6.0.0-py27_0
jinja2: 2.9.6-py27_0
jsonschema: 2.6.0-py27_0
jupyter: 1.0.0-py27_3
jupyter_client: 5.0.1-py27_0
jupyter_console: 5.1.0-py27_0
jupyter_core: 4.3.0-py27_0
libsodium: 1.0.10-0
markupsafe: 0.23-py27_2
mistune: 0.7.4-py27_0
nbconvert: 5.1.1-py27_0
nbformat: 4.3.0-py27_0
notebook: 5.0.0-py27_0
pandocfilters: 1.4.1-py27_0
path.py: 10.3.1-py27_0
pathlib2: 2.2.1-py27_0
pexpect: 4.2.1-py27_0
pickleshare: 0.7.4-py27_0
prompt_toolkit: 1.0.14-py27_0
ptyprocess: 0.5.1-py27_0
pygments: 2.2.0-py27_0
python-dateutil: 2.6.0-py27_0
pyzmq: 16.0.2-py27_0
scandir: 1.5-py27_0
simplegeneric: 0.8.1-py27_1
singledispatch: 3.4.0.3-py27_0
ssl_match_hostname: 3.4.0.2-py27_1
terminado: 0.6-py27_0
testpath: 0.3-py27_0
tornado: 4.5.1-py27_0
traitlets: 4.3.2-py27_0
wcwidth: 0.1.7-py27_0
widgetsnbextension: 2.0.0-py27_0
zeromq: 4.1.5-0
The following packages will be UPDATED:
conda: 4.3.14-py27_0 --> 4.3.21-py27_0
Proceed ([y]/n)? y
...
entrypoints-0. 100% |#########################################| Time: 0:00:00 15.14 MB/s
jupyter_core-4 100% |#########################################| Time: 0:00:00 304.20 kB/s
pickleshare-0. 100% |#########################################| Time: 0:00:00 23.47 MB/s
testpath-0.3-p 100% |#########################################| Time: 0:00:00 35.33 MB/s
tornado-4.5.1- 100% |#########################################| Time: 0:00:00 613.23 kB/s
ipython-5.3.0- 100% |#########################################| Time: 0:00:01 851.46 kB/s
jupyter_client 100% |#########################################| Time: 0:00:00 329.04 kB/s
nbformat-4.3.0 100% |#########################################| Time: 0:00:00 360.09 kB/s
terminado-0.6- 100% |#########################################| Time: 0:00:00 20.31 MB/s
conda-4.3.21-p 100% |#########################################| Time: 0:00:01 503.31 kB/s
ipykernel-4.6. 100% |#########################################| Time: 0:00:00 249.29 kB/s
nbconvert-5.1. 100% |#########################################| Time: 0:00:00 465.37 kB/s
jupyter_consol 100% |#########################################| Time: 0:00:00 39.17 MB/s
notebook-5.0.0 100% |#########################################| Time: 0:00:02 2.07 MB/s
widgetsnbexten 100% |#########################################| Time: 0:00:01 762.68 kB/s
ipywidgets-6.0 100% |#########################################| Time: 0:00:00 167.32 kB/s
jupyter-1.0.0- 100% |#########################################| Time: 0:00:00 11.56 MB/s
이제 다시 login을 하든가 ~/.bashrc를 새로 수행하면 PATH 환경변수가 잡히면서 jupyter 사용이 가능합니다.
mirhenge@powerai:~/miniconda2$ which jupyter
/home/mirhenge/miniconda2/bin/jupyter
Web browser로는 firefox를 사용하시면 됩니다. 여기서는 X 환경을 위해 tightvncviewer를 이용하므로 DISPLAY를 unix:0으로 설정합니다.
mirhenge@powerai:~/miniconda2$ export BROWSER=/usr/bin/firefox
mirhenge@powerai:~/miniconda2$ export DISPLAY=unix:0
이제 jupyter notebook를 구동하면 다음과 같은 메시지가 나옵니다.
mirhenge@powerai:~/miniconda2$ jupyter notebook
[I 13:40:32.487 NotebookApp] Serving notebooks from local directory: /home/mirhenge/miniconda2
[I 13:40:32.488 NotebookApp] 0 active kernels
[I 13:40:32.488 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=9d13bb86a1a68d0c408740c877045adb2278535287737f5f
[I 13:40:32.488 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 13:40:32.488 NotebookApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://localhost:8888/?token=9d13bb86a1a68d0c408740c877045adb2278535287737f5f
[I 13:40:35.286 NotebookApp] Accepting one-time-token-authenticated connection from 127.0.0.1
이때 tightvncserver를 설정해 놓았다면 그 화면을 통해 vncviewer에서 browser가 열립니다.
이후로는 vncviewer를 통하지 않고도 remote에서도 web browser를 이용해 접속할 수 있도록 아래와 같이 설정 파일을 생성하고 이어서 수정해줍니다.
mirhenge@powerai:~$ jupyter notebook --generate-config
mirhenge@powerai:~$ vi /home/mirhenge/.jupyter/jupyter_notebook_config.py
...
## The IP address the notebook server will listen on.
#c.NotebookApp.ip = 'localhost'
c.NotebookApp.ip = '*'
이제 다시 start해주면 굳이 local server에서 띄운 browser 뿐만 아니라 외부 PC에서 띄운 browser로도 접속이 가능합니다.
mirhenge@powerai:~$ jupyter notebook
[W 13:57:17.150 NotebookApp] WARNING: The notebook server is listening on all IP addresses and not using encryption. This is not recommended.
[I 13:57:17.158 NotebookApp] Serving notebooks from local directory: /home/mirhenge
[I 13:57:17.158 NotebookApp] 0 active kernels
[I 13:57:17.158 NotebookApp] The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/?token=acde16ba9020fd7cc174d894f760772af7257c619579519d
[I 13:57:17.158 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 13:57:17.159 NotebookApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://localhost:8888/?token=acde16ba9020fd7cc174d894f760772af7257c619579519d
[I 13:57:18.245 NotebookApp] Accepting one-time-token-authenticated connection from 127.0.0.1
[I 13:57:32.011 NotebookApp] 302 GET / (211.109.178.33) 0.33ms
[I 13:57:32.165 NotebookApp] 302 GET /tree? (211.109.178.33) 0.54ms
이때 처음 접속할 때는 위에 display된 token(위의 붉은색 부분)을 copy & paste 해서 넣어야 합니다.
한번 테스트를 해봅니다. 다음과 같이 IBM lab service에서 만든 demo용 English --> French 번역 deep learning용 package를 다운로드 받습니다.
mirhenge@powerai:~$ git clone https://github.com/ppradhan01/dl-language-translation.git
Cloning into 'dl-language-translation'...
remote: Counting objects: 13, done.
remote: Total 13 (delta 0), reused 0 (delta 0), pack-reused 13
Unpacking objects: 100% (13/13), done.
Checking connectivity... done.
mirhenge@powerai:~$ cd dl-language-translation/
mirhenge@powerai:~/dl-language-translation$ ls
code.ipynb data helper.py problem_unittests.py README.md
mirhenge@powerai:~/dl-language-translation$ cd data
mirhenge@powerai:~/dl-language-translation/data$ ls
small_vocab_en small_vocab_fr
mirhenge@powerai:~/dl-language-translation/data$ head small_vocab_en
new jersey is sometimes quiet during autumn , and it is snowy in april .
the united states is usually chilly during july , and it is usually freezing in november .
california is usually quiet during march , and it is usually hot in june .
the united states is sometimes mild during june , and it is cold in september .
your least liked fruit is the grape , but my least liked is the apple .
his favorite fruit is the orange , but my favorite is the grape .
paris is relaxing during december , but it is usually chilly in july .
new jersey is busy during spring , and it is never hot in march .
our least liked fruit is the lemon , but my least liked is the grape .
the united states is sometimes busy during january , and it is sometimes warm in november .
mirhenge@powerai:~/dl-language-translation/data$ head small_vocab_fr
new jersey est parfois calme pendant l' automne , et il est neigeux en avril .
les états-unis est généralement froid en juillet , et il gèle habituellement en novembre .
california est généralement calme en mars , et il est généralement chaud en juin .
les états-unis est parfois légère en juin , et il fait froid en septembre .
votre moins aimé fruit est le raisin , mais mon moins aimé est la pomme .
son fruit préféré est l'orange , mais mon préféré est le raisin .
paris est relaxant en décembre , mais il est généralement froid en juillet .
new jersey est occupé au printemps , et il est jamais chaude en mars .
notre fruit est moins aimé le citron , mais mon moins aimé est le raisin .
les états-unis est parfois occupé en janvier , et il est parfois chaud en novembre .
이제 browser의 notebook에서, 위에서 download 받은 dl-language-translation directory로 찾아내려가 code.ipynb를 클릭하면 됩니다.
그러면 이제 notebook이 열리고, 필요시 위쪽 메뉴 bar에 있는 play 버튼 (player의 삼각형 버튼)을 눌러서 해당 code 부분을 직접 수행해볼 수도 있습니다.
피드 구독하기:
글 (Atom)

















