|
| 1 | +#!/usr/bin/env python |
| 2 | +# encoding: utf-8 |
| 3 | + |
| 4 | +''' |
| 5 | +============================================================== |
| 6 | + Copyright © 2019 Intel Corporation |
| 7 | +
|
| 8 | + SPDX-License-Identifier: MIT |
| 9 | +============================================================== |
| 10 | +
|
| 11 | +============================================================== |
| 12 | +Copyright 2015 The TensorFlow Authors. All Rights Reserved. |
| 13 | +
|
| 14 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 15 | +you may not use this file except in compliance with the License. |
| 16 | +You may obtain a copy of the License at |
| 17 | +
|
| 18 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 19 | +
|
| 20 | +Unless required by applicable law or agreed to in writing, software |
| 21 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 22 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 23 | +See the License for the specific language governing permissions and |
| 24 | +limitations under the License. |
| 25 | +============================================================== |
| 26 | +''' |
| 27 | + |
| 28 | +"""A deep MNIST classifier using convolutional layers. |
| 29 | +
|
| 30 | +See extensive documentation at |
| 31 | +https://www.tensorflow.org/get_started/mnist/pros |
| 32 | +""" |
| 33 | +"""Convolutional Neural Network Estimator for MNIST, built with tf.layers.""" |
| 34 | + |
| 35 | +import time |
| 36 | +import os |
| 37 | +import errno |
| 38 | +import tensorflow as tf |
| 39 | +import horovod.tensorflow as hvd |
| 40 | +import numpy as np |
| 41 | + |
| 42 | +from tensorflow import keras |
| 43 | + |
| 44 | +tf.compat.v1.disable_eager_execution() |
| 45 | +''' |
| 46 | +Environment settings: |
| 47 | +Set MKLDNN_VERBOSE=1 to show DNNL run time verbose |
| 48 | +Set KMP_AFFINITY=verbose to show OpenMP thread information |
| 49 | +''' |
| 50 | +#import os; os.environ["MKLDNN_VERBOSE"] = "1" |
| 51 | +import os; os.environ["KMP_AFFINITY"] = "granularity=fine,compact,1,0" |
| 52 | + |
| 53 | +def cnn_model_fn(feature, target, mode): |
| 54 | + |
| 55 | + """Model function for CNN.""" |
| 56 | + """2-layer convolution model.""" |
| 57 | + |
| 58 | + # Convert the target to a one-hot tensor of shape (batch_size, 10) and |
| 59 | + # with a on-value of 1 for each one-hot vector of length 10. |
| 60 | + target = tf.one_hot(tf.cast(target, tf.int32), 10, 1, 0) |
| 61 | + |
| 62 | + |
| 63 | + # Input Layer |
| 64 | + # Reshape X to 4-D tensor: [batch_size, width, height, channels] |
| 65 | + # MNIST images are 28x28 pixels, and have one color channel |
| 66 | + feature = tf.reshape(feature, [-1, 28, 28, 1]) |
| 67 | + |
| 68 | + # First Convolutional Layer #1 |
| 69 | + # Computes 32 features using a 5x5 filter with ReLU activation. |
| 70 | + # Padding is added to preserve width and height. |
| 71 | + # Input Tensor Shape: [batch_size, 28, 28, 1] |
| 72 | + # Output Tensor Shape: [batch_size, 28, 28, 32] |
| 73 | + conv1 = tf.compat.v1.layers.conv2d( |
| 74 | + inputs=feature, |
| 75 | + filters=32, |
| 76 | + kernel_size=[5, 5], |
| 77 | + padding="SAME", |
| 78 | + activation=tf.nn.relu) |
| 79 | + |
| 80 | + # Pooling Layer #1 |
| 81 | + # First max pooling layer with a 2x2 filter and stride of 2 |
| 82 | + # Input Tensor Shape: [batch_size, 28, 28, 32] |
| 83 | + # Output Tensor Shape: [batch_size, 14, 14, 32] |
| 84 | + pool1 = tf.nn.max_pool2d(input=conv1, |
| 85 | + ksize=[1, 2, 2, 1], |
| 86 | + strides=[1, 2, 2, 1], |
| 87 | + padding="SAME") |
| 88 | + |
| 89 | + # Convolutional Layer #2 |
| 90 | + # Computes 64 features using a 5x5 filter. |
| 91 | + # Padding is added to preserve width and height. |
| 92 | + # Input Tensor Shape: [batch_size, 14, 14, 32] |
| 93 | + # Output Tensor Shape: [batch_size, 14, 14, 64] |
| 94 | + conv2 = tf.compat.v1.layers.conv2d( |
| 95 | + inputs=pool1, |
| 96 | + filters=64, |
| 97 | + kernel_size=[5, 5], |
| 98 | + padding="SAME", |
| 99 | + activation=tf.nn.relu) |
| 100 | + |
| 101 | + # Pooling Layer #2 |
| 102 | + # Second max pooling layer with a 2x2 filter and stride of 2 |
| 103 | + # Input Tensor Shape: [batch_size, 14, 14, 64] |
| 104 | + # Output Tensor Shape: [batch_size, 7, 7, 64] |
| 105 | + pool2 = tf.nn.max_pool2d(input=conv2, |
| 106 | + ksize=[1, 2, 2, 1], |
| 107 | + strides=[1, 2, 2, 1], |
| 108 | + padding="SAME") |
| 109 | + |
| 110 | + # Flatten tensor into a batch of vectors |
| 111 | + # Reshape tensor into a batch of vectors |
| 112 | + # Input Tensor Shape: [batch_size, 7, 7, 64] |
| 113 | + # Output Tensor Shape: [batch_size, 7 * 7 * 64] |
| 114 | + pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) |
| 115 | + |
| 116 | + # Dense Layer |
| 117 | + # Densely connected layer with 1024 neurons |
| 118 | + # Input Tensor Shape: [batch_size, 7 * 7 * 64] |
| 119 | + # Output Tensor Shape: [batch_size, 1024] |
| 120 | + dense = tf.compat.v1.layers.dense(inputs=pool2_flat, |
| 121 | + units=1024, |
| 122 | + activation=tf.nn.relu) |
| 123 | + |
| 124 | + # Add dropout operation; 0.6 probability that element will be kept |
| 125 | + dropout = tf.compat.v1.layers.dropout(inputs=dense, |
| 126 | + rate=0.6, |
| 127 | + training=mode == tf.estimator.ModeKeys.TRAIN) |
| 128 | + |
| 129 | + # Logits layer |
| 130 | + # Input Tensor Shape: [batch_size, 1024] |
| 131 | + # Output Tensor Shape: [batch_size, 10] |
| 132 | + logits = tf.compat.v1.layers.dense(dropout, 10, activation=None) |
| 133 | + |
| 134 | + # Calculate Loss (for both TRAIN and EVAL modes) |
| 135 | + loss = tf.compat.v1.losses.softmax_cross_entropy(target, logits) |
| 136 | + |
| 137 | + return tf.argmax(input=logits, axis=1), loss |
| 138 | + |
| 139 | +def train_input_generator(x_train, y_train, batch_size=64): |
| 140 | + if len(x_train) == len(y_train): |
| 141 | + p = np.random.permutation(len(x_train)) |
| 142 | + x_train, y_train = x_train[p], y_train[p] |
| 143 | + index = 0 |
| 144 | + while index <= len(x_train) - batch_size: |
| 145 | + yield x_train[index:index + batch_size], \ |
| 146 | + y_train[index:index + batch_size], |
| 147 | + index += batch_size |
| 148 | + else: |
| 149 | + None |
| 150 | + |
| 151 | +def main(unused_argv): |
| 152 | + # Initialize Horovod |
| 153 | + hvd.init() |
| 154 | + # Keras automatically creates a cache directory in ~/.keras/datasets for |
| 155 | + # storing the downloaded MNIST data. This creates a race |
| 156 | + # condition among the workers that share the same filesystem. If the |
| 157 | + # directory already exists by the time this worker gets around to creating |
| 158 | + # it, ignore the resulting exception and continue. |
| 159 | + cache_dir = os.path.join(os.path.expanduser('~'), '.keras', 'datasets') |
| 160 | + if not os.path.exists(cache_dir): |
| 161 | + try: |
| 162 | + os.mkdir(cache_dir) |
| 163 | + except OSError as e: |
| 164 | + if e.errno == errno.EEXIST and os.path.isdir(cache_dir): |
| 165 | + pass |
| 166 | + else: |
| 167 | + raise |
| 168 | + |
| 169 | + # Load training and eval data |
| 170 | + # Download and load MNIST dataset. |
| 171 | + (x_train, y_train), (x_test, y_test) = \ |
| 172 | + keras.datasets.mnist.load_data('MNIST-data-%d' % hvd.rank()) |
| 173 | + # The shape of downloaded data is (-1, 28, 28), hence we need to reshape it |
| 174 | + # into (-1, 784) to feed into our network. Also, need to normalize the |
| 175 | + # features between 0 and 1. |
| 176 | + x_train = np.reshape(x_train, (-1, 784)) / 255.0 |
| 177 | + x_test = np.reshape(x_test, (-1, 784)) / 255.0 |
| 178 | + # Build model... |
| 179 | + with tf.compat.v1.name_scope('input'): |
| 180 | + image = tf.compat.v1.placeholder(tf.float32, [None, 784], name='image') |
| 181 | + label = tf.compat.v1.placeholder(tf.float32, [None], name='label') |
| 182 | + predict, loss = cnn_model_fn(image, label, tf.estimator.ModeKeys.TRAIN) |
| 183 | + |
| 184 | + # Horovod: adjust learning rate based on number of MPI Tasks. |
| 185 | + opt = tf.compat.v1.train.RMSPropOptimizer(0.001 * hvd.size()) |
| 186 | + opt = hvd.DistributedOptimizer(opt) |
| 187 | + |
| 188 | + global_step = tf.compat.v1.train.get_or_create_global_step() |
| 189 | + train_op = opt.minimize(loss, global_step=global_step) |
| 190 | + |
| 191 | + hooks = [ |
| 192 | + # Horovod: BroadcastGlobalVariablesHook broadcasts initial variable states |
| 193 | + # from rank 0 to all other processes. This is necessary to ensure consistent |
| 194 | + # initialization of all workers when training is started with random weights |
| 195 | + # or restored from a checkpoint. |
| 196 | + hvd.BroadcastGlobalVariablesHook(0), |
| 197 | + |
| 198 | + # Horovod: adjust number of steps based on number of MPI tasks. |
| 199 | + tf.estimator.StopAtStepHook(last_step=1000 // hvd.size()), |
| 200 | + |
| 201 | + tf.estimator.LoggingTensorHook(tensors={'step': global_step, 'loss': loss}, |
| 202 | + every_n_iter=100), |
| 203 | + ] |
| 204 | + # Horovod: save checkpoints only on worker 0 to prevent other workers from |
| 205 | + # corrupting them. |
| 206 | + checkpoint_dir = './checkpoints' if hvd.rank() == 0 else None |
| 207 | + training_batch_generator = train_input_generator(x_train, |
| 208 | + y_train, batch_size=100) |
| 209 | + # The MonitoredTrainingSession takes care of session initialization, |
| 210 | + # restoring from a checkpoint, saving to a checkpoint, and closing when done |
| 211 | + # or an error occurs. |
| 212 | + |
| 213 | + config = tf.compat.v1.ConfigProto() |
| 214 | +# config.inter_op_parallelism_threads = 2 |
| 215 | +# config.intra_op_parallelism_threads = 4 |
| 216 | + |
| 217 | + |
| 218 | + time_start = time.time() |
| 219 | + |
| 220 | + with tf.compat.v1.train.MonitoredTrainingSession(checkpoint_dir=checkpoint_dir, |
| 221 | + hooks=hooks, |
| 222 | + config=config) as mon_sess: |
| 223 | + while not mon_sess.should_stop(): |
| 224 | + # Run a training step synchronously. |
| 225 | + image_, label_ = next(training_batch_generator) |
| 226 | + mon_sess.run(train_op, feed_dict={image: image_, label: label_}) |
| 227 | + |
| 228 | + if hvd.rank() == 0: |
| 229 | + print('============================') |
| 230 | + print('Number of tasks: ', hvd.size()) |
| 231 | + print('Total time is: %g' % (time.time() - time_start)) |
| 232 | + |
| 233 | + |
| 234 | +if __name__ == '__main__': |
| 235 | + tf.compat.v1.app.run() |
0 commit comments