2018년 8월 21일 화요일

Session-based tensorflow training에 LMS 적용한 MNIST python code

이 MNIST training을 위한 tensorflow python code는 원래 /opt/DL/tensorflow/lib/python3.6/site-packages/tensorflow/examples/tutorials/mnist/mnist_deep.py 에 LMS를 적용한 것입니다.  보시다시피 graph라는 단어가 나오기 때문에 Session-based tensorflow training이고, 그에 따라 LMS가 적용되어 있습니다.  

실제 LMS 구현을 위한 부분은 굵은 파란색으로 표시했습니다.  의외로 간단하다는 것을 보실 수 있습니다.  해당 부분들을 제거하면 그냥 LMS 없는 평범한 MNIST training code가 됩니다.

이 example code도 PowerAI 5.2를 설치하면 딸려오는 /opt/DL/tensorflow/lib/python3.6/site-packages/tensorflow/contrib/lms/examples/mnist_deep_lms.py 을 그대로 가져다 놓은 것입니다.

실제 수행해보면 다음과 같이 동작하며, 27개의 tensor가 host 서버의 RAM으로 swap-out/in 되는 것을 보실 수 있습니다.



[bsyu@p57a22 examples]$ CUDA_VISIBLE_DEVICES=3 python mnist_deep_lms.py
...
INFO:tensorflow:[LMS][0] Editing model for LMS
INFO:tensorflow:[LMS][0] n_tensors: all tensors
INFO:tensorflow:[LMS][0] lb: 3
INFO:tensorflow:[LMS][0] Edited model is valid and logically equivalent to the original one
INFO:tensorflow:[LMS][0] Added 53 ops into the model
INFO:tensorflow:[LMS][0] Editing model for LMS, took: 179.62193489074707 ms
INFO:tensorflow:[LMS][0] 27 tensors will be swapped out(in) to(from) the host
Saving graph to: /tmp/tmpz5ozc9jr
2018-08-20 21:37:47.954552: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1356] Found device 0 with properties:
....
step 19900, training accuracy 1
test accuracy 0.9918




[bsyu@p57a22 doc]$ cd /opt/DL/tensorflow/lib/python3.6/site-packages/tensorflow/contrib/lms/examples/


[bsyu@p57a22 examples]$ source /opt/DL/tensorflow/bin/tensorflow-activate

[bsyu@p57a22 examples]$ cat /opt/DL/tensorflow/lib/python3.6/site-packages/tensorflow/contrib/lms/examples/mnist_deep_lms.py

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""A deep MNIST classifier using convolutional layers.

See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import tempfile

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)
FLAGS = None


def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.

  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.

  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  return y_conv, keep_prob


def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')


def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)


def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)


def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.int64, [None])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.losses.sparse_softmax_cross_entropy(
        labels=y_, logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), y_)
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  # Enable Large Model Support
  from tensorflow.contrib.lms import LMS
  lms_model = LMS({'adam_optimizer'},
                  excl_scopes = {'loss', 'accuracy', 'dropout'},
                  lb=3)
  lms_model.run(tf.get_default_graph())

  graph_location = tempfile.mkdtemp()
  print('Saving graph to: %s' % graph_location)
  train_writer = tf.summary.FileWriter(graph_location)
  train_writer.add_graph(tf.get_default_graph())

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20000):    
      batch = mnist.train.next_batch(50)   
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()

  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

Estimator-based tensorflow training에 LMS 적용한 MNIST python code


이 MNIST training을 위한 tensorflow python code는 원래 /opt/DL/tensorflow/lib/python3.6/site-packages/tensorflow/examples/tutorials/layers/cnn_mnist.py 에 LMS를 적용한 것입니다.  보시다시피 hook를 사용하기 때문에 Estimator-based tensorflow training이고, 그에 따라 LMS가 적용되어 있습니다. 

LMS가 동작하는 message 확인이라든가, 다중 사용자를 위한 permission 등을 위한 부분도 있습니다만 그건 LMS와는 무관한 부분이고, 그 부분들은 빨간색으로 표시를 했습니다.  실제 LMS 구현을 위한 부분은 굵은 파란색으로 표시했습니다.  의외로 간단하다는 것을 보실 수 있습니다.  해당 부분들을 제거하면 그냥 LMS 없는 평범한 MNIST training code가 됩니다.

이 example code도 PowerAI 5.2를 설치하면 딸려오는 /opt/DL/tensorflow/lib/python3.6/site-packages/tensorflow/contrib/lms/examples/cnn_mnist_lms.py 을 그대로 가져다 놓은 것입니다.

실제 수행해보면 다음과 같이 동작하며, 12개의 tensor가 host 서버의 RAM으로 swap-out/in 되는 것을 보실 수 있습니다.

[bsyu@p57a22 ~]$ cd /opt/DL/tensorflow/lib/python3.6/site-packages/tensorflow/contrib/lms/examples

[bsyu@p57a22 examples]$ source /opt/DL/tensorflow/bin/tensorflow-activate

[bsyu@p57a22 examples]$ python cnn_mnist_lms.py
...
INFO:tensorflow:[LMS][1] Tensor sparse_softmax_cross_entropy_loss/Sum_1:0 will be placed on /cpu:0
INFO:tensorflow:[LMS][1] Operation: adam_optimizer/gradients/sparse_softmax_cross_entropy_loss/div_grad/RealDiv_1, order 23, type RealDiv
INFO:tensorflow:[LMS][1] Tensor adam_optimizer/gradients/sparse_softmax_cross_entropy_loss/div_grad/RealDiv_1:0 will be placed on /cpu:0
INFO:tensorflow:[LMS][1] Consuming op adam_optimizer/gradients/sparse_softmax_cross_entropy_loss/div_grad/RealDiv_2 (order 24) swaps in adam_optimizer/gradients/sparse_softmax_cross_entropy_loss/div_grad/RealDiv_1:0
INFO:tensorflow:[LMS][1] No control dependency op needed for swap in of op adam_optimizer/gradients/sparse_softmax_cross_entropy_loss/div_grad/RealDiv_1.
INFO:tensorflow:[LMS][0] Edited model is valid and logically equivalent to the original one
INFO:tensorflow:[LMS][0] Added 25 ops into the model
INFO:tensorflow:[LMS][0] Editing model for LMS, took: 88.58513832092285 ms
INFO:tensorflow:[LMS][0] 12 tensors will be swapped out(in) to(from) the host
INFO:tensorflow:Graph was finalized.
...
{'accuracy': 0.9702, 'loss': 0.098796368, 'global_step': 20000}



전체 code 내용은 아래를 보시기 바랍니다.

[bsyu@p57a22 examples]$ cat /opt/DL/tensorflow/lib/python3.6/site-packages/tensorflow/contrib/lms/examples/cnn_mnist_lms.py

#  Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
"""Convolutional Neural Network Estimator for MNIST, built with tf.layers."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tempfile # Change not related to LMS
import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)  #LMS 기능과는 무관. LMS 메시지를 보기 위한 설정.


def cnn_model_fn(features, labels, mode):
  """Model function for CNN."""
  # Input Layer
  # Reshape X to 4-D tensor: [batch_size, width, height, channels]
  # MNIST images are 28x28 pixels, and have one color channel
  input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])

  # Convolutional Layer #1
  # Computes 32 features using a 5x5 filter with ReLU activation.
  # Padding is added to preserve width and height.
  # Input Tensor Shape: [batch_size, 28, 28, 1]
  # Output Tensor Shape: [batch_size, 28, 28, 32]
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  # First max pooling layer with a 2x2 filter and stride of 2
  # Input Tensor Shape: [batch_size, 28, 28, 32]
  # Output Tensor Shape: [batch_size, 14, 14, 32]
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2
  # Computes 64 features using a 5x5 filter.
  # Padding is added to preserve width and height.
  # Input Tensor Shape: [batch_size, 14, 14, 32]
  # Output Tensor Shape: [batch_size, 14, 14, 64]
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #2
  # Second max pooling layer with a 2x2 filter and stride of 2
  # Input Tensor Shape: [batch_size, 14, 14, 64]
  # Output Tensor Shape: [batch_size, 7, 7, 64]
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Flatten tensor into a batch of vectors
  # Input Tensor Shape: [batch_size, 7, 7, 64]
  # Output Tensor Shape: [batch_size, 7 * 7 * 64]
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])

  # Dense Layer
  # Densely connected layer with 1024 neurons
  # Input Tensor Shape: [batch_size, 7 * 7 * 64]
  # Output Tensor Shape: [batch_size, 1024]
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)

  # Add dropout operation; 0.6 probability that element will be kept
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

  # Logits layer
  # Input Tensor Shape: [batch_size, 1024]
  # Output Tensor Shape: [batch_size, 10]
  logits = tf.layers.dense(inputs=dropout, units=10)

  predictions = {
      # Generate predictions (for PREDICT and EVAL mode)
      "classes": tf.argmax(input=logits, axis=1),
      # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
      # `logging_hook`.
      "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
  }
  if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

  # Calculate Loss (for both TRAIN and EVAL modes)
  loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == tf.estimator.ModeKeys.TRAIN:
    with tf.name_scope('adam_optimizer'):
      optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
      train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

  # Add evaluation metrics (for EVAL mode)
  eval_metric_ops = {
      "accuracy": tf.metrics.accuracy(
          labels=labels, predictions=predictions["classes"])}
  return tf.estimator.EstimatorSpec(
      mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)


def main(unused_argv):
  # Load training and eval data
  mnist = tf.contrib.learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # The graph_location changes are not related to LMS enablement
  # but rather allow multiple users to run the example without
  # having permission issues on temp directories.
  graph_location = tempfile.mkdtemp()
  print('Saving graph to: %s' % graph_location)

  # Create the Estimator
  mnist_classifier = tf.estimator.Estimator(
      model_fn=cnn_model_fn, model_dir=graph_location)

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  train_input_fn = tf.estimator.inputs.numpy_input_fn(
      x={"x": train_data},
      y=train_labels,
      batch_size=100,
      num_epochs=None,
      shuffle=True)

  # Hook for Large Model Support
  from tensorflow.contrib.lms import LMSHook
  lms_hook = LMSHook({'adam_optimizer'}, lb=3, debug=True)

  mnist_classifier.train(
      input_fn=train_input_fn,
      steps=20000,
      hooks=[logging_hook, lms_hook])

  # Evaluate the model and print results
  eval_input_fn = tf.estimator.inputs.numpy_input_fn(
      x={"x": eval_data},
      y=eval_labels,
      num_epochs=1,
      shuffle=False)
  eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn)
  print(eval_results)


if __name__ == "__main__":
  tf.app.run()

Tensorflow LMS를 이용한 python coding guide (README-LMS.md)

PowerAI 5.2에 포함된 Tensorflow 1.8에는 IBM이 자랑하는 LMS (Large Model Support) 기능이 통합되어 있습니다.  즉, GPU 메모리가 부족할 경우 host 서버의 RAM을 GPU 메모리처럼 사용할 수 있도록 해주는 기능으로서, 마치 real memory가 부족할 때 disk 상의 swap space로 swap in/out 하는 것과 비슷하다고 생각하시면 됩니다.

Caffe-ibm에는 이것이 -lms 옵션으로 구현되어 있으므로 별다른 코딩 없이 사용하시면 되는데, tensorflow는 그 자체가 원래 python의 library이므로 LMS를 사용하기 위해서는 python coding이 약간 필요합니다.   그에 대한 가이드는 아직 internet 상에는 없고, PowerAI 5.2를 설치하면 딸려오는 /opt/DL/tensorflow/doc/README-LMS.md에 비교적 상세한 설명이 들어 있습니다.

IBM PowerAI 5.2는 Minsky 또는 AC922 서버를 소유하고 계신 고객께서는 추가 비용없이 주문하실 수 있는 무료 SW입니다.  (그러나 공식적으로 주문을 하셔야 받으실 수 있습니다.)  고객 여러분의 편의를 위해 그 README-LMS.md를 여기에 올려놓습니다.

아래 문서에 자세히 나와 있습니다만, tensorflow에서 training하는 방법에는 크게 2가지 방법이 있고, LMS 구현도 그에 따라 2가지 방법이 있습니다.  제가 얼치기로 이해한 것을 요약하면 이렇습니다. 

1) Session-based training : 
기존 tensorflow python code에 graph라는 단어가 나오면 training 부분 전에 아래 block을 집어넣어 LMS를 구현합니다.

from tensorflow.contrib.lms import LMS
lms_obj = LMS({'adam_optimizer'})
lms_obj.run(graph=tf.get_default_graph())   # 파란색 부분을 삽입

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
        batch = mnist.train.next_batch(50)
        train_step.run(feed_dict={x: batch[0], y_: batch[1]})

2) Estimator-based training :
기존 tensorflow python code에 hook이라는 단어가 나오면 아래 block을 집어넣어 LMS를 구현합니다.

from tensorflow.contrib.lms import LMSHook
lms_hook = LMSHook({'adam_optimizer'})    # 파란색 부분을 삽입
...

mnist_classifier.train(
      input_fn=train_input_fn,
      steps=20000
      hooks=[logging_hook, lms_hook])  #lms_hook을 삽입


그리고 LMS 튜닝에 있어서는 2가지 parameter가 중요합니다.  실제로는 n_tensor를 code에서 직접 쓰실 일은 거의 없는 것 같고, lb는 가끔 사용하는 것 같습니다.

n_tensor : host 서버의 RAM으로 swap-out 했다가 필요시 swap-in 할 tensor의 개수입니다.  당연히 많을 수록 GPU memory를 적게 쓰지만, 대신 training 성능은 나빠집니다.  Default 값은 -1로서, 모든 tensor를 다 swap 대상으로 삼습니다만, tensorflow LMS가 초기 estimation 후 자동으로 적절한 값을 산정하여 사용합니다.

lb : Lower Bound의 약자로서, 미리 swap-in 시켜놓을 tensor의 개수입니다.  많을 수록 성능은 좋아지겠지만, 대신 GPU memory를 많이 쓰게 됩니다.  Default 값은 1입니다.


전체 내용은 아래 README-LMS.md를 참조하십시요.

[bsyu@p57a22 doc]$ vi /opt/DL/tensorflow/doc/README-LMS.md

# TFLMS: Graph Editing Library for Large Model Support (LMS) in TensorFlow

This library provides an approach to training large models that cannot be fit into GPU memory.
It takes a computational graph defined by users, and automatically adds swap-in and swap-out nodes for transferring tensors from GPUs to the host and vice versa.
The computational graph is statically modified. Hence, it needs to be done before a session actually starts.

## How to use
TFLMS needs to know some information about user-defined models.
There is one requirement for a user-defined model: it must have scopes for the optimizers/solvers.

Enabling LMS for a model depends on how users write their training. Followings are guidelines for two ways: [Session](https://www.tensorflow.org/programmers_guide/graphs)-based training and [Estimator](https://www.tensorflow.org/programmers_guide/estimators)-based training.

### [Session](https://www.tensorflow.org/programmers_guide/graphs)-based training
#### Step 1: define optimizer/solver scopes
```python
with tf.name_scope('adam_optimizer'):
        train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
```
#### Step 2: define an LMS object and run it
```python
from tensorflow.contrib.lms import LMS
lms_obj = LMS({'adam_optimizer'})
lms_obj.run(graph=tf.get_default_graph())
```
The above lines must be put before starting a training session, for example:
- Before inserting LMS code
```python
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
        batch = mnist.train.next_batch(50)
        train_step.run(feed_dict={x: batch[0], y_: batch[1]})
```
- After inserting LMS code
```python
from tensorflow.contrib.lms import LMS
lms_obj = LMS({'adam_optimizer'})
lms_obj.run(graph=tf.get_default_graph())

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
        batch = mnist.train.next_batch(50)
        train_step.run(feed_dict={x: batch[0], y_: batch[1]})
```
For a working example of LMS integration with Session based training see:
`/opt/DL/tensorflow/lib/python*/site-packages/tensorflow/contrib/lms/examples/mnist_deep_lms.py`
which is an LMS enabled version of `/opt/DL/tensorflow/lib/python*/site-packages/tensorflow/examples/tutorials/mnist/mnist_deep.py`.

### [Estimator](https://www.tensorflow.org/programmers_guide/estimators)-based training
#### Step 1: define optimizer/solver scopes
```python
with tf.name_scope('adam_optimizer'):
      optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
      train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
```
#### Step 2: define an LMSHook (LMSHook and LMS share the same set of parameters)
```python
# Hook for Large Model Support
from tensorflow.contrib.lms import LMSHook
lms_hook = LMSHook({'adam_optimizer'})
```
#### Step 3: add the LMSHook into Estimator's hook list
```python
mnist_classifier.train(
      input_fn=train_input_fn,
      steps=20000
      hooks=[logging_hook, lms_hook])
```

For a working example of LMS integration with Estimator based training see:
`/opt/DL/tensorflow/lib/python*/site-packages/tensorflow/contrib/lms/examples/cnn_mnist_lms.py`
which is an LMS enabled version of `/opt/DL/tensorflow/lib/python*/site-packages/tensorflow/examples/tutorials/layers/cnn_mnist.py`.

### High-Performance Models
A version of TensorFlow High-Performance Models which includes options to use Distributed Deep Learning is included in the tensorflow-performance-models package. These models also have integrated
Large Model Support.  For more information, see:

`/opt/DL/tensorflow-performance-models/tf_cnn_benchmarks/README.md`

### GPU scaling tips

To achieve better scaling performance with LMS on multiple GPUs,
the train script should updated to use PowerAI Distributed Deep Learning and
the training script should be run with the `ddlrun` command.  Additionally,
if running on a single system without an Infiniband set up,
the `--mpiarg -pami_noib` parameter must be added to the ddlrun command
line, for example:

```bash
ddlrun --mpiarg -pami_noib -H host1 python tf_cnn_benchmarks.py --batch_size=512 --num_batches=100 --model=resnet50 --gpu_thread_mode=gpu_shared --num_gpus=1 --display_every=10 --lms=True --lms_lb=3 --lms_n_tensors=80 --variable_update=ddl
```

For more information on using ddlrun, see: `/opt/DL/ddl/doc/README.md` and `/opt/DL/ddl-tensorflow/doc/README.md`.

### Parameters for LMS/LMSHook
#### Required parameters
_graph_ :: the graph we will modify for LMS. This should be the graph of user-defined neural network. (not required in LMSHook)

_optimizer_scopes_ :: scopes for the optimizers/solvers.

#### Optional parameters
_starting_scope_ :: Tensors that are reachable from the operations in this scope will be swapped for LMS. Set this to the scope of the first layer if we would like to modify the whole graph. Default `None`.

_starting_op_names_ :: Tensors that are reachable from the operations with these names will be swapped for LMS. Default `None`.

_excl_scopes_ :: a set of scopes for operations whose tensors will not be swapped out to the host. Default `empty`.

_incl_scopes_ :: a set of scopes for operations whose tensors will be swapped out to the host. Default `empty`.

_excl_types_ :: a set of types for operations whose tensors will not be swapped out to the host. Default `empty`.

_incl_types_ :: a set of types for operations whose tensors will be swapped out to the host. Default `empty`.

_n_tensors_ :: The number of tensors for LMS, counting from the `starting_scope`. To turn off LMS, set `n_tensors` to `0`. Default `-1` (all reachable tensors will be swapped for LMS).

_lb_ :: Lowerbound value for LMS. A tensor will be swapped in during the backward phase at least `lb` nodes before it in the graph. Default `1`.

_ub_ :: Upperbound value for LMS. Default `10000`.

_fuse_swapins_ :: Fuse "close" swap-in operations into one operation. This may improve the performance. Default `False`.

_ctrld_strategy_ :: Two strategies to find control dependency ops for   swapin ops: `chain_rule` and `direct_order`. `chain_rule` strategy starts from a forward operation, goes forward and finds a corresponding backward operation to be a control dependency opepartion. `direct_order` strategy directly gets a backward ops in the topological order to be a control dependency operation. Both strategies depend on `lb` and `ub` to choose a control dependency operation. While the `direct_order` is more exact than `chain_rule` in relation to `lb` and `ub`, it experimentally often results in smaller maximum batch size than `chain_rule`. Default `chain_rule`.

_swap_branches_ :: If True, LMS will swap tensors in branches in the forward phase. Default `False`.

_branch_threshold_ :: If `swap_branches` is enabled and the topological-sort distance between the consuming operation and generating operation of a tensor is greater than `branch_threshold`, then swap the tensor. Default `0`.

_debug_ :: Debug mode for LMS. Default `False`.

_debug_level_ :: Debug level for LMS (1 or 2). Default `1`.


### Performance Tuning LMS

Once you have enabled LMS graph modification in your code you will want to find the combination of tuning parameters that gives the fastest training time and best accuracy with your model. The goal of the performance tuning is to swap out enough tensors to allow your training to run without hitting out of memory errors, while not swapping too many such that the extra swapping communication overhead degrades performance.

The two tuning parameters you should focus on are `n_tensors` and `lb`.  Since `n_tensors` controls the number of tensors that will be swapped, the higher this is set, the lower the peak GPU memory usage will be. The `lb` controls how soon the tensor is swapped back in before use. A low value of `lb` can make the training on the GPU pause and wait while the swap in finishes.  This will degrade performance. A higher value of `lb` can allow the tensor swap in to finish before it's needed and allow training to run without pause.  The downside to swapping in too early is that more tensors will be in GPU memory at any point in time, resulting in higher peak GPU memory usage.

The tuning thus becomes finding the correct balance between `n_tensors` and `lb` that provides the best performance for given model.  To start the performance tuning it's suggested that `n_tensors` be set to -1 which will swap all reachable tensors. The `lb` should be set to the default 1, which is the latest possible swap in. If `tf.logging` verbosity is set to `tf.logging.INFO`, LMS will output a log statement with a count of the number of tensors swapped. It is useful to run with `n_tensors=-1` for the first run to find this maximum value and then adjust it downward. If your model has branches like some UNet models do, you will likely want to set `swap_branches=True` and tune the branch threshold as well.

By default LMS will analyze your graph to find the starting operations to use for finding tensor swap candidates. You can bypass this analysis by placing your starting operations in a named scope and providing the scope on the `starting_scope` parameter, or by providing the names of the starting operations on the `starting_op_names` parameter. This can speed up repeated runs of LMS during tuning. Furthermore, you can enable `debug=True` and `debug_level=1` and LMS will print out the name and type of the starting operations it finds. These names could be passed in on the `starting_op_names` parameter on subsequent runs.

It is recommended that you start with tuning training on a single GPU before enabling your code for multi-GPU with DDL.

2018년 8월 9일 목요일

PowerAI 5.2의 README 파일

아래는 PowerAI 5.2를 설치하면 함께 설치되는 README 파일입니다.  공유를 위해 여기 올려둡니다.

Deep Learning Software Packages

Updated 2018-06-15
PowerAI 1.5.2 provides software packages for several Deep Learning frameworks, supporting libraries, and tools:
ComponentVersion
DDL1.0.0
TensorFlow1.8.0
TensorBoard1.8.0
IBM Caffe1.0.0
BVLC Caffe1.0.0
PyTorch0.4.0
Snap ML1.0.0
Spectrum MPI10.2
Bazel0.10.0
OpenBLAS0.2.20
HDF51.10.1
Protobuf3.4.0
PowerAI is optimized to leverage the unique capabilities of IBM Power Systems accelerated servers, and is not available on any other platforms. It is supported on:
  • IBM AC922 POWER9 system with NVIDIA Tesla V100 GPUs
  • IBM S822LC POWER8 system with NVIDIA Tesla P100 GPUs
PowerAI requires some additional 3rd-party software components (see below for more information):
ComponentRequiredRecommended
Red Hat RHEL7.57.5
NVIDIA CUDA9.29.2.88
NVIDIA GPU driver396396.26
NVIDIA cuDNN7.17.1.4
NVIDIA NCCL2.22.2.12
Anaconda Anaconda5.15.1.0

New Features in 1.5.2

Python 3 support for the framework packages (in addition to the existing Python 2 support; not including Caffe).
A Technology Preview of IBM PowerAI Snap Machine Learning (Snap ML). Snap ML provides classical machine learning functionalities exposed via an sklearn-like interface.
A Technology Preview of PyTorch - a Python library that enables GPU-accelerated tensor computation and provides a rich API for neural network applications.
A Technology Preview of Large Model Support (LMS) is introduced for TensorFlow and enhanced for IBM Caffe. Large Module Support provides an approach to training large models and batch sizes that cannot fit in GPU memory.
Note that a NCCL v1.3.5 package is still included in the PowerAI distribution but is not installed by default. The other PowerAI components are now built against NCCL v2.2.12, which must be downloaded from NVIDIA. The NCCL 1 package is provided for compatibility with existing applications, but may be removed in future releases of PowerAI.

Additional information

For updates to this document please visit https://developer.ibm.com/linuxonpower/deep-learning-powerai/releases/.
More information about PowerAI is available at https://ibm.biz/powerai.
Developer resources can be found at http://ibm.biz/poweraideveloper.
Have questions?
You may find an answer already at the PowerAI space on developerWorks Answers.

System Setup

Operating System

The Deep Learning packages require RHEL 7.5 little endian for IBM POWER8 and IBM POWER9. The RHEL install image and license must be acquired from RedHat.
https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux

Operating System and Repository Setup

  1. Enable 'optional' and 'extra' repo channels
      IBM POWER8:
          $ sudo subscription-manager repos --enable=rhel-7-for-power-le-optional-rpms
          $ sudo subscription-manager repos --enable=rhel-7-for-power-le-extras-rpms
    
      IBM POWER9:
          $ sudo subscription-manager repos --enable=rhel-7-for-power-9-optional-rpms
          $ sudo subscription-manager repos --enable=rhel-7-for-power-9-extras-rpms
  2. Install packages needed for the installation
      $ sudo yum -y install wget nano bzip2
  3. Enable EPEL repo
       $ wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
       $ sudo rpm -ihv epel-release-latest-7.noarch.rpm
  4. Load the latest kernel
      $ sudo yum update kernel kernel-tools kernel-tools-libs kernel-bootwrapper
      $ reboot
    Or do a full update
      $ sudo yum update
      $ sudo reboot

NVIDIA Components

IBM POWER9 specific udev rules

Before installing the NVIDIA components the udev Memory Auto-Onlining Rule must be disabled for the CUDA driver to function properly. To disable it:
  1. Copy the /lib/udev/rules.d/40-redhat.rules file to the directory for user overridden rules.
      $ sudo cp /lib/udev/rules.d/40-redhat.rules /etc/udev/rules.d/
  2. Edit the /etc/udev/rules.d/40-redhat.rules file.
      $ sudo nano /etc/udev/rules.d/40-redhat.rules
  3. Comment out the following line and save the change:
      SUBSYSTEM=="memory", ACTION=="add", PROGRAM="/bin/uname -p", RESULT!="s390*", ATTR{state}=="offline", ATTR{state}="online"
  4. Optionally delete the first line of the file, since the file was copied to a directory where it won't be overwritten.
      # do not edit this file, it will be overwritten on update
  5. Reboot the system for the changes to take effect.
      $ sudo reboot

CUDA, GPU driver, cuDNN and NCCL

The Deep Learning packages require CUDA, cuDNN, NCCL, and GPU driver packages from NVIDIA (see table above)
These components can be installed by:
  1. Download and install NVIDIA CUDA 9.2 from https://developer.nvidia.com/cuda-downloads
    • Select Operating System: Linux
    • Select Architecture: ppc64le
    • Select Distribution RHEL
    • Select Version 7
    • Select Installer Type rpm (local)
    • Follow the Linux POWER installation instructions in the CUDA Quick Start Guide, including the steps describing how to set up the CUDA development environment by updating PATH and LD_LIBRARY_PATH.
    Note: The local rpm is preferred over the network rpm as it will ensure the version installed is the version downloaded. With the network rpm, "yum install cuda" will always install the latest version of the CUDA Toolkit.
  2. Download NVIDIA cuDNN v7.1.4 for CUDA 9.2 from https://developer.nvidia.com/cudnn (Registration in NVIDIA's Accelerated Computing Developer Program is required)
    • cuDNN v7.1.4 Library for Linux (Power8/Power9)
  3. Download NVIDIA NCCL v2.2.12 for CUDA 9.2 from https://developer.nvidia.com/nccl (Registration in NVIDIA's Accelerated Computing Developer Program is required)
    • NCCL 2.2.12 O/S agnostic and CUDA 9.2 and IBM Power
  4. Install the cuDNN v7.1.4 and NCCL v2.2.12 packages. Refresh shared library cache.
       $ sudo tar -C /usr/local --no-same-owner -xzvf cudnn-9.2-linux-ppc64le-v7.1.4.tgz
       $ sudo tar -C /usr/local --no-same-owner -xzvf nccl_2.2.12-1+cuda9.2_ppc64le.tgz
       $ sudo ldconfig

Anaconda

A number of the Deep Learning frameworks require Anaconda. Anaconda is a platform-agnostic data science distribution with a collection of 1,000+ open source packages with free community support.
Anaconda2 with Python 2 should be used to run the Python 2 versions of the Deep Learning frameworks. Anaconda3 with Python 3 is required to run the Python 3 versions of the Deep Learning frameworks.
AnacondaVersionDownload LocationSizemd5sum
Anaconda25.1.0https://repo.continuum.io/archive/Anaconda2-5.1.0-Linux-ppc64le.sh267Me894dcc547a1c7d67deb04f6bba7223a
Anaconda35.1.0https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-ppc64le.sh286M47b5b2b17b7dbac0d4d0f0a4653f5b1c
Download and Install Anaconda. Installation requires input for license agreement, install location (default is $HOME/anaconda2 or $HOME/anaconda3), and permission to modify the PATH environment variable (via .bashrc).
Example download and install setup for Anaconda2:
   $ wget https://repo.continuum.io/archive/Anaconda2-5.1.0-Linux-ppc64le.sh
   $ bash Anaconda2-5.1.0-Linux-ppc64le.sh
   $ source ~/.bashrc
If multiple users are using the same system, each user should install Anaconda individually.

Installing the Deep Learning Frameworks

Software Repository Setup

The PowerAI Deep Learning packages are distributed in a tar.gz file containing an rpm and a README file. The tar.gz file must be extracted on the local machine. Installing the rpm creates an installation repository on the local machine.
Install the repository package:
    $ sudo rpm -ihv mldl-repo-*.rpm

Installing all frameworks at once

The Deep Learning frameworks can be installed all at once using the power-mldl meta-package:
    $ sudo yum install power-mldl
NOTE: This does not include the PowerAI Distributed Deep Learning (DDL) packages. See details of how to install DDL below.

Installing the Python 3 versions of the frameworks

The Python 3 versions of the frameworks can be installed at once using the power-mldl-py3 meta-package
    $ sudo yum install power-mldl-py3

Installing frameworks individually

The Deep Learning frameworks can be installed individually if preferred. The framework packages are:
  • caffe-bvlc - Berkeley Vision and Learning Center (BVLC) upstream Caffe, v1.0.0
  • caffe-ibm - IBM Optimized version of BVLC Caffe, v1.0.0
  • pytorch - PyTorch, v0.4.0
  • tensorflow - TensorFlow, v1.8.0
  • tensorboard - Web Applications for inspecting TensorFlow runs and graphs, v1.8.0
The Python 3 version of each framework appends '-py3' to the package name
  • pytorch-py3 - PyTorch, v0.4.0
  • tensorflow-py3 - TensorFlow, v1.8.0
  • tensorboard-py3 - Web Applications for inspecting TensorFlow runs and graphs, v1.8.0
Each can be installed with:
    $ sudo yum install <framework>

Install IBM PowerAI Distributed Deep Learning (DDL) packages

We recommend PowerAI Distributed Deep Learning for distributing model training across a cluster of Power machines. DDL includes IBM Spectrum MPI for communication among machines.
Install the PowerAI Distributed Deep Learning packages using:
    $ sudo yum install power-ddl
Note: DDL is an optional component. Other PowerAI components can be installed and used without installing DDL.
To use InfiniBand for DDL communications, install the latest Mellanox OFED driver. See the Download tab at: http://www.mellanox.com/page/products_dyn?product_family=26

Install IBM PowerAI Snap ML packages

Install the PowerAI Snap ML packages using:
    $ sudo yum install power-snapml
Note: Snap ML is an optional component. Other PowerAI components can be installed and used without installing Snap ML.

Accept the PowerAI License Agreement

Read the license agreement and accept the terms and conditions before using any of the frameworks.
    $ sudo /opt/DL/license/bin/accept-powerai-license.sh
After reading the license agreement, future installs may be automated to silently accept the license agreement.
    $ sudo IBM_POWERAI_LICENSE_ACCEPT=yes /opt/DL/license/bin/accept-powerai-license.sh

Upgrading from PowerAI 1.5.1

PowerAI 1.5.1 should be uninstalled prior to installing PowerAI 1.5.2.

Upgrading from PowerAI 1.5.0

PowerAI 1.5.2 requires newer versions of NVIDIA CUDA, NVIDIA cuDNN, the GPU driver, and IBM Spectrum MPI than 1.5.0. To upgrade, the older versions should be uninstalled and the newer versions installed. Likewise, the PowerAI 1.5.0 software packages should be uninstalled and the PowerAI 1.5.2 packages installed.

Upgrading from PowerAI 1.5.0 Caffe

The Caffe packages in PowerAI 1.5.0 used the HDF5 library from Anaconda. That library is now packaged with PowerAI so the Anaconda copy is no longer needed. After upgrading to 1.5.2, it is safe to remove the library symlinks from the cache directory:
$ ls -l ~/.powerai/caffe-bvlc/
$ rm -r ~/.powerai/caffe-bvlc

$ ls -l ~/.powerai/caffe-ibm/
$ rm -r ~/.powerai/caffe-ibm

Tuning Recommendations

Recommended settings for optimal Deep Learning performance on the S822LC and AC922 for High Performance Computing are:
  • Enable Performance Governor
       $ sudo yum install kernel-tools
       $ sudo cpupower -c all frequency-set -g performance
  • Enable GPU persistence mode
       $ sudo systemctl enable nvidia-persistenced
       $ sudo systemctl start nvidia-persistenced
  • Set GPU memory and graphics clocks
    • S822LC with NVIDIA Tesla P100, set clocks to maximum
      $ sudo nvidia-smi -ac 715,1480
    • AC922 with NVIDIA Tesla V100, set clocks to NVIDIA defaults
      $ sudo nvidia-smi -rac
  • For TensorFlow, set the SMT mode
    • S822LC with NVIDIA Tesla P100, set SMT=2
      $ sudo ppc64_cpu --smt=2
    • AC922 with NVIDIA Tesla V100, set SMT based on DDL usage:
      $ sudo ppc64_cpu --smt=4 # for TensorFlow WITHOUT DDL
      $ sudo ppc64_cpu --smt=2 # for TensorFlow WITH DDL

Getting Started with MLDL Frameworks

General Setup

Most of the PowerAI packages install outside the normal system search paths (to /opt/DL/...), so each framework package provides a shell script to simplify environmental setup (e.g. PATH, LD_LIBRARY_PATH, PYTHONPATH).
We recommend users update their shell rc file (e.g. .bashrc) to source the desired setup scripts. For example:
$ source /opt/DL/<framework>/bin/<framework>-activate
Each framework also provides a test script to verify some of its functions. These test scripts include tests and examples sourced from the various communities. Note that some of the included tests rely on datasets (ex. MNIST) that are available in the community and are downloaded at runtime. Access and availability to this data is subject to the community and may change at any time.
To run the test script for a particular framework, run:
$ <framework>-test

Note about dependencies

A number of the PowerAI frameworks (for example, TensorFlow, TensorBoard, and PyTorch) have their dependencies satisfied via Anaconda packages. These dependencies are validated by the <framework>-activate script to ensure they are installed and, if not, the script will fail.
For these frameworks, the /opt/DL/<framework>/bin/install_dependencies script must be run prior to activation to install the required packages.
For example:
$ source /opt/DL/tensorflow/bin/tensorflow-activate
Missing dependencies ['backports.weakref', 'mock', 'protobuf']
Run "/opt/DL/tensorflow/bin/install_dependencies" to resolve this problem.

$ /opt/DL/tensorflow/bin/install_dependencies
Fetching package metadata ...........
Solving package specifications: .

Package plan for installation in environment /home/rhel/anaconda2:

The following NEW packages will be INSTALLED:

    backports.weakref: 1.0rc1-py27_0
    libprotobuf:       3.4.0-hd26fab5_0
    mock:              2.0.0-py27_0
    pbr:               1.10.0-py27_0
    protobuf:          3.4.0-py27h7448ec6_0

Proceed ([y]/n)? y

libprotobuf-3. 100% |###############################| Time: 0:00:02   2.04 MB/s
backports.weak 100% |###############################| Time: 0:00:00  12.83 MB/s
protobuf-3.4.0 100% |###############################| Time: 0:00:00   2.20 MB/s
pbr-1.10.0-py2 100% |###############################| Time: 0:00:00   3.35 MB/s
mock-2.0.0-py2 100% |###############################| Time: 0:00:00   3.26 MB/s

$ source /opt/DL/tensorflow/bin/tensorflow-activate
$
Note: PyTorch and TensorFlow have conflicting Anaconda package dependencies. Create separate Anaconda environments for those frameworks.

Getting Started with DDL

The Caffe and TensorFlow sections below describe how to use the DDL support for each of those frameworks.
Some configuration steps are common to all use of DDL:
  • PowerAI frameworks must be installed at the same version on all nodes in the DDL cluster.
  • The DDL master node must be able to log into all the nodes in the cluster using ssh keys. Keys can be created and added by:
    1. Generate ssh private/public key pair on the master node using:
        $ ssh-keygen
    2. Copy the generated public key in ~/.ssh/id_rsa.pub to all the nodes’ ~./ssh/authorized_keys file:
        $ ssh-copy-id -i ~/.ssh/id_rsa.pub $USER@$HOST
  • Linux system firewalls may need to be adjusted to pass MPI traffic. This could be done broadly as shown. Note: Opening only required ports would be more secure. Required ports will vary with configuration.
      $ sudo iptables -A INPUT -p tcp --dport 1024:65535 -j ACCEPT

Getting Started with Caffe

Caffe Alternatives

Packages are provided for upstream BVLC Caffe (/opt/DL/caffe-bvlc) and IBM optimized Caffe (/opt/DL/caffe-ibm). The system default Caffe (/opt/DL/caffe) can be selected using the operating system's alternatives system:
    $ sudo update-alternatives --config caffe
    There are 2 programs which provide 'caffe'.

      Selection    Command
    -----------------------------------------------
       1           /opt/DL/caffe-bvlc
    *+ 2           /opt/DL/caffe-ibm

    Enter to keep the current selection[+], or type selection number:
Users can activate the system default caffe:
    source /opt/DL/caffe/bin/caffe-activate
Or they can activate a specific variant. For example:
    source /opt/DL/caffe-bvlc/bin/caffe-activate
Attempting to activate multiple Caffe packages in a single login session will cause unpredictable behavior.

Caffe Samples and Examples

Each Caffe package includes example scripts and sample models, etc. A script is provided to copy the sample content into a specified directory:
    $ caffe-install-samples <somedir>

More Info

Visit Caffe's website (http://caffe.berkeleyvision.org/) for tutorials and example programs that you can run to get started.
Here are links to a couple of the example programs:

Optimizations in IBM Caffe

The IBM Caffe package (caffe-ibm) in PowerAI is based on BVLC Caffe and includes optimizations and enhancements from IBM:
Note: DDL is to be installed separately as mentioned above.

Command Line Options

IBM Caffe supports all of BVLC Caffe's options and adds a few new ones to control the enhancements. IBM Caffe options related to Distributed Deep Learning (options that start with the word "ddl") will work only if you have DDL installed.
  • -bvlc: Disable CPU/GPU layer-wise reduction
  • -threshold: Tune CPU/GPU layer-wise reduction. If the number of parameters for one layer is greater than or equal to threshold, their accumulation on CPU will be done in parallel. Otherwise, the accumulation will be done using one thread. It is set to 2,000,000 by default.
  • -ddl ["-option1 param -option2 param"]: Enable Distributed Deep Learning, with optional space-delimited parameter string. Supported parameters are:
    • mode <mode>
    • dump_iter <N>
    • dev_sync <0, 1, or 2>
    • rebind_iter <N>
    • dbg_level <0, 1, or 2>
  • -ddl_update: This option instructs Caffe to use a new custom version of the ApplyUpdate function that is optimized for DDL. It is faster, but does not support gradient clipping so is off by default. It can be used in networks that do not support clipping (common).
  • -ddl_align: This option ensures that the gradient buffers have a length that is a multiple of 256 bytes and have start addresses that are multiples of 256. This ensures cache line alignment on multiple platforms as well as alignment with NCCL slices. Off by default
  • -ddl_database_restart: This option ensures every learner always looks at the same data set during an epoch. This allows a system to cache only the pages that are touched by the learners contained within it. It can help size the number of learners needed for a given data set size by establishing a known database footprint per system. This flag should not be used while running caffe on several hosts. Off by default.
  • -lms: Enable Large Model Support. See below.
  • -lms_size_threshold <size in KB>: Set LMS size threshold. See below.
  • -lms_exclude <size in MB>: Tune LMS memory utilization. See below.
  • -affinity: Enable CPU/GPU affinity (default). Specify -noaffinity to disable.
Use the command line options as follows:
    | Feature                         | -bvlc | -ddl | -lms  | -gpu          | -affinity |
    | ------------------------------- | ----- | ---- | ----- | ------------- | --------- |
    | CPU/GPU layer-wise reduction    |   N   |   X  |   X   | multiple GPUs | X         |
    | Distributed Deep Learning (DDL) |   X   |   Y  |   X   | N             | X         |
    | Large model support             |   X   |   X  |   Y   | X             | X         |
    | CPU/GPU affinity                |   X   |   X  |   X   | X             | Y         |

    Y: do specify
    N: don't specifiy
    X: don't care/matter
LMS gets enabled regardless of other options as long as -lms is specified. For example, you can use DDL and LMS together.
CPU/GPU layer-wise reduction is enabled only if multiple GPUs are specified and layer_wise_reduce: false.
Use of multiple GPUs with DDL is specified via the MPI rank file, so the -gpu flag may not be used to specify multiple GPUs for DDL.
While running caffe on several hosts, the use of shared storage for data can lead caffe to hang.

About CPU/GPU Layer-wise Reduction

This optimization aims to reduce the running time of a multiple-GPU training by utilizing CPUs. In particular, gradient accumulation is offloaded to CPUs and done in parallel with the training. To gain the best performance with IBM Caffe, please close unnecessary applications that consume a high percentage of CPU.
If using a single GPU, IBM Caffe and BVLC Caffe will have similar performance.
The optimizations in IBM Caffe do not change the convergence of a neural network during training. IBM Caffe and BVLC Caffe should produce the same convergence results.
CPU/GPU layer-wise reduction is enabled unless the -bvlc commandline flag is used.

About IBM PowerAI Distributed Deep Learning (DDL)

See /opt/DL/ddl/doc/README.md for more information about using IBM PowerAI Distributed Deep Learning.

About Large Model Support (LMS)

IBM Caffe with Large Model Support loads the neural model and data set in system memory and caches activity to GPU memory only when needed for computation. This allows models and training batch size to scale significantly beyond what was previously possible. You can enable Large Model Support by adding -lms. Large Model Support is available as a technology preview.
The -lms_size_threshold <size in KB> option modifies the minimum memory chunk size considered for the LMS cache (default: 1000). Any chunk smaller than this value will be exempt from LMS reuse and will persist in GPU memory. The value can be used to control the performance trade-off.
The -lms_exclude <size in MB> option defines a soft limit on GPU memory allocated for the LMS cache (where limit = GPU-capacity - value). If zero, favors aggressive GPU memory reuse over allocation (default). If specified (> 0), enables aggressive allocation of GPU memory up to the limit. Minimizing this value -- while still allowing enough memory for non-LMS allocations -- may improve performance by increasing GPU memory utilization and reducing data transfers between system and GPU memory.
For example, the following command line options yield the best training performance for the GoogleNet model with high-resolution image data (crop size 2240x2240, batch size 5) using Tesla P100 GPUs:
    $ caffe train -solver=solver.prototxt -gpu all -lms —lms_size_threshold 1000 -lms_exclude 1400
Note that ideal tunings for any given scenario may differ depending on the model's network architecture, data size, batch size and GPU memory capacity.

Combining LMS and DDL

Large Model Support and Distributed Deep Learning can be combined. For example, to run on two hosts named host1 and host2:
    $ ddlrun -H host1,host2 caffe train -solver solver-resnet-152.prototxt -lms

Getting Started with Tensorflow

The TensorFlow homepage (https://www.tensorflow.org/) has a variety of information, including Tutorials, How Tos, and a Getting Started guide.
Additional tutorials and examples are available from the community, for example:

High-Performance Models

A version of TensorFlow High-Performance Models which includes options to use Distributed Deep Learning is included in the tensorflow-performance-models package. For more information, see:
  • /opt/DL/tensorflow-performance-models/scripts/tf_cnn_benchmarks/README.md

Large Model Support (LMS)

This release of PowerAI includes a Technology Preview of large model support for TensorFlow. Large Model Support provides an approach to training large models and batch sizes that cannot fit in GPU memory. It does this by use of a graph editing library that takes the user model's computational graph and automatically adds swap-in and swap-out nodes for transferring tensors from GPU memory to system memory and vice versa during training.
For more information about TensorFlow LMS, see:
  • /opt/DL/tensorflow/doc/README-LMS.md

Distributed Deep Learning (DDL) Custom Operator for TensorFlow

The DDL custom operator uses IBM Spectrum MPI and NCCL to provide high-speed communications for distributed TensorFlow.
The DDL custom operator can be found in the ddl-tensorflow package. For more information about DDL and about the TensorFlow operator, see:
  • /opt/DL/ddl/doc/README.md
  • /opt/DL/ddl-tensorflow/doc/README.md
  • /opt/DL/ddl-tensorflow/doc/README-API.md

Additional TensorFlow Features

The PowerAI TensorFlow packages include TensorBoard. See: https://www.tensorflow.org/get_started/summaries_and_tensorboard
The TensorFlow 1.8.0 package includes support for additional features:

TensorBoard Usage Notes

Additional usage notes are available from the community. See notes at: - https://github.com/tensorflow/tensorboard

Getting started with Snap Machine Learning (Snap ML)

This release of PowerAI includes Technology preview of Snap Machine Learning (Snap ML). Snap ML is a library for training generalized linear models. It is being developed at IBM with the vision to remove training time as a bottleneck for machine learning applications. Snap ML supports a large number of classical machine learning models and scales gracefully to data sets with billions of examples and/or features. It offers distributed training, GPU acceleration and supports sparse data structures.
"With Snap ML you can train your machine learning model faster than you can snap your fingers!"
The Snap ML library offers two different packages:

snap-ml-local

snap-ml-local is used for machine learning on a single machine.
For information on snap-ml-local, see /opt/DL/snap-ml-local/doc/README.md

snap-ml-mpi

snap-ml-mpi is used for distributed training of machine learning models across a cluster of machines.
For information on snap-ml-mpi, see /opt/DL/snap-ml-mpi/doc/README.md

Getting started with PyTorch

This release of PowerAI includes a Technology Preview of PyTorch - deep learning framework for fast, flexible experimentation.

PyTorch Examples

The PyTorch package includes a set of examples. A script is provided to copy the sample content into a specified directory:
    $ pytorch-install-samples <somedir>

More Info

The PyTorch homepage (https://pytorch.org) has a variety of information, including Tutorials and a Getting Started guide.
Additional tutorials and examples are available from the community, for example:

Uninstalling MLDL Frameworks

The MLDL framework packages can be uninstalled individually if desired. Or to uninstall all MLDL packages and the repository package at once:
    $ sudo yum remove powerai-license
    $ sudo yum remove mldl-repo-local
    $ sudo yum autoremove
© Copyright IBM Corporation 2017, 2018
IBM, the IBM logo, ibm.com, POWER, Power, POWER8, POWER9, and Power systems are trademarks of International Business Machines Corp., registered in many jurisdictions worldwide. Other product and service names might be trademarks of IBM or other companies. A current list of IBM trademarks is available on the Web at "Copyright and trademark information" at www.ibm.com/legal/copytrade.shtml.
Linux is a registered trademark of Linus Torvalds in the United States, other countries, or both.
The TensorFlow package includes code from the BoringSSL project. The following notices may apply:
    This product includes software developed by the OpenSSL Project for
    use in the OpenSSL Toolkit. (http://www.openssl.org/)

    This product includes cryptographic software written by Eric Young
    (eay@cryptsoft.com)
This document is current as of the initial date of publication and may be changed by IBM at any time. Not all offerings are available in every country in which IBM operates.
THE INFORMATION IN THIS DOCUMENT IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING WITHOUT ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM products are warranted according to the terms and conditions of the agreements under which they are provided.