|
| 1 | +import tensorflow as tf |
| 2 | +import time |
| 3 | +from utils import * |
| 4 | + |
| 5 | +FLAGS = tf.app.flags.FLAGS |
| 6 | + |
| 7 | +class Worker(object): |
| 8 | + def __init__(self, job_name, task_index, server): |
| 9 | + self.job_name = job_name |
| 10 | + self.task_index = task_index |
| 11 | + self.server = server |
| 12 | + |
| 13 | + # For shared parameters, including global step. |
| 14 | + global_device = '/job:{}/task:{}/cpu:0'.format(job_name, task_index) |
| 15 | + |
| 16 | + # For local computations, |
| 17 | + """ |
| 18 | + The gradient is computed at each "local_device". |
| 19 | + Since CUDA_VISIBLE_DEVICES for each worker process allocates single |
| 20 | + gpu, '/gpu:0' is used. |
| 21 | + """ |
| 22 | + local_device = '/job:{}/task:{}/gpu:0'.format(job_name, task_index) |
| 23 | + |
| 24 | + with tf.device(tf.train.replica_device_setter(1, |
| 25 | + worker_device=global_device)): |
| 26 | + |
| 27 | + with tf.variable_scope('global'): |
| 28 | + self.build_net() |
| 29 | + self.global_step = tf.get_variable('global_step', [], tf.int32, |
| 30 | + initializer=tf.constant_initializer(0, dtype=tf.int32), |
| 31 | + trainable=False) |
| 32 | + self.counter_op = self.global_step.assign_add(1) |
| 33 | + |
| 34 | + with tf.device(local_device): |
| 35 | + with tf.variable_scope('local'): |
| 36 | + self.build_net() |
| 37 | + self.build_loss() |
| 38 | + self.build_sync_op() |
| 39 | + self.build_train_op() |
| 40 | + self.build_summary_op() |
| 41 | + |
| 42 | + self.build_init_op() |
| 43 | + self.build_saver() |
| 44 | + |
| 45 | + |
| 46 | + def build_net(self): |
| 47 | + self.x = tf.placeholder(tf.float32, [None, 784]) |
| 48 | + |
| 49 | + def _net(inputs): |
| 50 | + net = tf.layers.dense(inputs, 100, activation=tf.nn.sigmoid, |
| 51 | + kernel_initializer=tf.random_normal_initializer()) |
| 52 | + logits = tf.layers.dense(net, 10, |
| 53 | + kernel_initializer=tf.random_normal_initializer()) |
| 54 | + net = tf.nn.softmax(logits) |
| 55 | + return net, logits |
| 56 | + |
| 57 | + self.net, self.logits = _net(self.x) |
| 58 | + |
| 59 | + def build_loss(self): |
| 60 | + self.y = tf.placeholder(tf.float32, [None, 10]) |
| 61 | + |
| 62 | + def _loss(labels, logits): |
| 63 | + cross_entropy = tf.nn.softmax_cross_entropy_with_logits( |
| 64 | + labels=labels, logits=logits) |
| 65 | + |
| 66 | + return tf.reduce_mean(cross_entropy) |
| 67 | + |
| 68 | + self.loss = _loss(self.y, self.logits) |
| 69 | + |
| 70 | + def build_train_op(self): |
| 71 | + optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate) |
| 72 | + gvs = optimizer.compute_gradients(self.loss, |
| 73 | + var_list=get_vars('local')) |
| 74 | + |
| 75 | + global_gvs = [] |
| 76 | + for v, gv in zip(get_vars('global'), gvs): |
| 77 | + global_gvs.append((gv[0], v)) |
| 78 | + |
| 79 | + self.train_op = optimizer.apply_gradients(global_gvs) |
| 80 | + |
| 81 | + def build_sync_op(self): |
| 82 | + local_vars = get_vars('local') |
| 83 | + global_vars = get_vars('global') |
| 84 | + self.sync_op = tf.group(*[v1.assign(v2)\ |
| 85 | + for v1, v2 in zip(local_vars, global_vars)]) |
| 86 | + |
| 87 | + def build_summary_op(self): |
| 88 | + with tf.name_scope('accuracy'): |
| 89 | + correct_prediction = tf.equal(tf.argmax(self.net, 1), tf.argmax(self.y, 1)) |
| 90 | + accuracy = self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) |
| 91 | + |
| 92 | + tf.summary.scalar('loss', self.loss) |
| 93 | + tf.summary.scalar('accuracy', accuracy) |
| 94 | + |
| 95 | + self.summary_op = tf.summary.merge_all() |
| 96 | + self.summary_writer = tf.summary.FileWriter(FLAGS.logdir + '_%d' % self.task_index) |
| 97 | + |
| 98 | + def build_init_op(self): |
| 99 | + self.global_init_op = tf.variables_initializer(get_vars('global', False)) |
| 100 | + self.local_init_op = tf.variables_initializer(get_vars('local', False)) |
| 101 | + |
| 102 | + def build_saver(self): |
| 103 | + self.saver = FastSaver(get_vars('global', False)) |
| 104 | + |
| 105 | + def learn(self, dataset): |
| 106 | + |
| 107 | + sv = tf.train.Supervisor(is_chief=(self.task_index==0), |
| 108 | + logdir=FLAGS.logdir, |
| 109 | + saver=self.saver, |
| 110 | + summary_op=None, |
| 111 | + summary_writer=self.summary_writer, |
| 112 | + ready_op=tf.report_uninitialized_variables( |
| 113 | + get_vars('global', False)), |
| 114 | + global_step=self.global_step, |
| 115 | + save_model_secs=30, |
| 116 | + save_summaries_secs=30, |
| 117 | + init_op=self.global_init_op, |
| 118 | + local_init_op=self.local_init_op) |
| 119 | + |
| 120 | + config = tf.ConfigProto(allow_soft_placement=True, |
| 121 | + log_device_placement=True) |
| 122 | + |
| 123 | + with sv.managed_session(self.server.target, config=config) as sess, sess.as_default(): |
| 124 | + |
| 125 | + begin_time = time.time() |
| 126 | + frequency = 100 |
| 127 | + # perform training cycles |
| 128 | + start_time = time.time() |
| 129 | + |
| 130 | + epoch = 0 |
| 131 | + while not sv.should_stop() and epoch < FLAGS.training_epochs: |
| 132 | + # number of batches in one epoch |
| 133 | + batch_count = int(dataset.train.num_examples/FLAGS.batch_size) |
| 134 | + count = 0 |
| 135 | + for i in range(batch_count): |
| 136 | + sess.run(self.sync_op) |
| 137 | + batch_x, batch_y = dataset.train.next_batch(FLAGS.batch_size) |
| 138 | + |
| 139 | + # perform the operations we defined earlier on batch |
| 140 | + _, cost, summary, step = sess.run( |
| 141 | + [self.train_op, self.loss, self.summary_op, self.global_step], |
| 142 | + feed_dict={self.x: batch_x, self.y: batch_y}) |
| 143 | + self.summary_writer.add_summary(summary, step) |
| 144 | + |
| 145 | + count += 1 |
| 146 | + if count % frequency == 0 or i+1 == batch_count: |
| 147 | + elapsed_time = time.time() - start_time |
| 148 | + start_time = time.time() |
| 149 | + print("Step: %d," % (step+1), |
| 150 | + " Epoch: %2d," % (epoch+1), |
| 151 | + " Batch: %3d of %3d," % (i+1, batch_count), |
| 152 | + " Cost: %.4f," % cost, |
| 153 | + " AvgTime: %3.2fms" % float(elapsed_time*1000/frequency)) |
| 154 | + count = 0 |
| 155 | + sess.run(self.counter_op) |
| 156 | + |
| 157 | + epoch += 1 |
| 158 | + |
| 159 | + print("Test-Accuracy: %2.2f" % sess.run(self.accuracy, |
| 160 | + feed_dict={self.x: dataset.test.images, self.y: dataset.test.labels})) |
| 161 | + print("Total Time: %3.2fs" % float(time.time() - begin_time)) |
| 162 | + print("Final Cost: %.4f" % cost) |
| 163 | + |
| 164 | + print("done") |
0 commit comments