|
| 1 | +# Copyright 2018 Google Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import os |
| 16 | +import tensorflow as tf |
| 17 | + |
| 18 | +import trainer.sample_model as sm |
| 19 | + |
| 20 | +FLAGS = tf.app.flags.FLAGS |
| 21 | + |
| 22 | +tf.app.flags.DEFINE_integer( |
| 23 | + 'max_steps', 1000, 'max_step for training.') |
| 24 | +tf.app.flags.DEFINE_string( |
| 25 | + 'output_dir', '', 'GCS location to root directory for checkpoints and exported models.') |
| 26 | +tf.app.flags.DEFINE_string( |
| 27 | + 'model_name', 'sample_model', 'model name.') |
| 28 | +tf.app.flags.DEFINE_integer( |
| 29 | + 'train_batch_size', 200, 'batch size for training.') |
| 30 | +tf.app.flags.DEFINE_integer( |
| 31 | + 'eval_batch_size', 200, 'batch size for evaluation.') |
| 32 | +tf.app.flags.DEFINE_integer( |
| 33 | + 'eval_steps', 50, 'The number of steps that are used in evaluation phase.') |
| 34 | +tf.app.flags.DEFINE_integer( |
| 35 | + 'tf_random_seed', 19851211, '') |
| 36 | +tf.app.flags.DEFINE_integer( |
| 37 | + 'save_checkpoints_steps', 500, '') |
| 38 | +tf.app.flags.DEFINE_string( |
| 39 | + 'train_data_pattern', 'cifar-10/train*.tfrecord', 'path to train dataset on GCS.') |
| 40 | +tf.app.flags.DEFINE_string( |
| 41 | + 'eval_data_pattern', 'cifar-10/valid*.tfrecord', 'path to eval dataset on GCS.') |
| 42 | +tf.app.flags.DEFINE_float( |
| 43 | + 'learning_rate', 1e-3, 'learning rate.') |
| 44 | +tf.app.flags.DEFINE_integer( |
| 45 | + 'num_gpus', 1, 'num of gpus in single-node-multi-GPUs setting.') |
| 46 | +tf.app.flags.DEFINE_integer( |
| 47 | + 'num_gpus_per_worker', 0, 'num of gpus for each node.') |
| 48 | +tf.app.flags.DEFINE_bool( |
| 49 | + 'auto_shard_dataset', False, |
| 50 | + 'whether to auto-shard the dataset when there are multiple workers.') |
| 51 | +tf.app.flags.DEFINE_float( |
| 52 | + 'drop_out_rate', 1e-2, 'drop out rate') |
| 53 | +tf.app.flags.DEFINE_integer( |
| 54 | + 'dense_units', 1024, 'units in dense layer.') |
| 55 | + |
| 56 | +tf.logging.set_verbosity(tf.logging.INFO) |
| 57 | + |
| 58 | +def parse_tfrecord(example): |
| 59 | + feature={'label': tf.FixedLenFeature((), tf.int64), |
| 60 | + 'image': tf.FixedLenFeature((), tf.string, default_value="")} |
| 61 | + parsed = tf.parse_single_example(example, feature) |
| 62 | + image = tf.decode_raw(parsed['image'],tf.float64) |
| 63 | + image = tf.cast(image,tf.float32) |
| 64 | + image = tf.reshape(image,[32,32,3]) |
| 65 | + return image, parsed['label'] |
| 66 | + |
| 67 | + |
| 68 | +def image_scaling(x): |
| 69 | + return tf.image.per_image_standardization(x) |
| 70 | + |
| 71 | +def distort(x): |
| 72 | + x = tf.image.resize_image_with_crop_or_pad(x, 40, 40) |
| 73 | + x = tf.random_crop(x, [32, 32, 3]) |
| 74 | + x = tf.image.random_flip_left_right(x) |
| 75 | + return x |
| 76 | + |
| 77 | +def dataset_input_fn(params): |
| 78 | + dataset = tf.data.TFRecordDataset(params['filenames'], |
| 79 | + num_parallel_reads=params['threads']) |
| 80 | + dataset = dataset.map(parse_tfrecord, num_parallel_calls=params['threads']) |
| 81 | + dataset = dataset.map( |
| 82 | + lambda x,y: (image_scaling(x),y), num_parallel_calls=params['threads']) |
| 83 | + if params['mode']==tf.estimator.ModeKeys.TRAIN: |
| 84 | + dataset = dataset.map( |
| 85 | + lambda x,y: (distort(x),y), num_parallel_calls=params['threads']) |
| 86 | + dataset = dataset.shuffle(buffer_size=params['shuffle_buff']) |
| 87 | + dataset = dataset.repeat() |
| 88 | + dataset = dataset.batch(params['batch']) |
| 89 | + dataset = dataset.prefetch(8*params['batch']) |
| 90 | + return dataset |
| 91 | + |
| 92 | + |
| 93 | +def train_dataset_input_fn(pattern): |
| 94 | + files = tf.gfile.Glob(pattern) |
| 95 | + params = {'filenames': files, 'mode': tf.estimator.ModeKeys.TRAIN, |
| 96 | + 'threads': 16, 'shuffle_buff': 100000, 'batch': FLAGS.train_batch_size} |
| 97 | + return dataset_input_fn(params) |
| 98 | + |
| 99 | + |
| 100 | +def eval_dataset_input_fn(pattern): |
| 101 | + files = tf.gfile.Glob(pattern) |
| 102 | + params = {'filenames': tf.gfile.Glob(pattern), 'mode': tf.estimator.ModeKeys.EVAL, |
| 103 | + 'threads': 16, 'batch': FLAGS.eval_batch_size} |
| 104 | + return dataset_input_fn(params) |
| 105 | + |
| 106 | + |
| 107 | +def serving_input_fn(): |
| 108 | + receiver_tensor = {'images': tf.placeholder(shape=[None, 32, 32, 3], dtype=tf.float32)} |
| 109 | + features = tf.map_fn(image_scaling, receiver_tensor['images']) |
| 110 | + return tf.estimator.export.TensorServingInputReceiver(features, receiver_tensor) |
| 111 | + |
| 112 | + |
| 113 | +def train_and_evaluate(): |
| 114 | + model_dir = os.path.join(FLAGS.output_dir, FLAGS.model_name) |
| 115 | + |
| 116 | + # MirroredStrategy |
| 117 | + if FLAGS.num_gpus_per_worker > 0: |
| 118 | + distribution = tf.contrib.distribute.MirroredStrategy( |
| 119 | + num_gpus_per_worker=FLAGS.num_gpus_per_worker, |
| 120 | + auto_shard_dataset=FLAGS.auto_shard_dataset) |
| 121 | + elif FLAGS.num_gpus > 0: |
| 122 | + distribution = tf.contrib.distribute.MirroredStrategy(num_gpus=FLAGS.num_gpus) |
| 123 | + else: |
| 124 | + distribution = None |
| 125 | + |
| 126 | + # Configuration for Estimator |
| 127 | + config = tf.estimator.RunConfig( |
| 128 | + save_checkpoints_secs=FLAGS.save_checkpoints_steps, |
| 129 | + keep_checkpoint_max=5, |
| 130 | + session_config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True), |
| 131 | + train_distribute=distribution, |
| 132 | + tf_random_seed=FLAGS.tf_random_seed) |
| 133 | + |
| 134 | + model_params = { |
| 135 | + 'drop_out': FLAGS.drop_out_rate, |
| 136 | + 'dense_units': FLAGS.dense_units, |
| 137 | + 'learning_rate': FLAGS.learning_rate, |
| 138 | + 'log': True} |
| 139 | + |
| 140 | + # Create Estimator. |
| 141 | + estimator = tf.estimator.Estimator( |
| 142 | + model_fn=sm.model_fn, |
| 143 | + model_dir=model_dir, |
| 144 | + params=model_params, |
| 145 | + config=config) |
| 146 | + |
| 147 | + # Specify training data paths, batch size and max steps. |
| 148 | + train_spec = tf.estimator.TrainSpec( |
| 149 | + input_fn=lambda: train_dataset_input_fn(FLAGS.train_data_pattern), |
| 150 | + max_steps=FLAGS.max_steps) |
| 151 | + |
| 152 | + # Configuration for model exportation |
| 153 | + exporter = tf.estimator.LatestExporter( |
| 154 | + name='export', |
| 155 | + serving_input_receiver_fn=serving_input_fn, |
| 156 | + assets_extra=None, as_text=False, exports_to_keep=5) |
| 157 | + |
| 158 | + # Specify validation data paths, steps for evaluation and exporter specs |
| 159 | + eval_spec = tf.estimator.EvalSpec( |
| 160 | + input_fn=lambda: eval_dataset_input_fn(FLAGS.eval_data_pattern), |
| 161 | + steps=FLAGS.eval_steps, exporters=exporter) |
| 162 | + |
| 163 | + tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) |
| 164 | + |
| 165 | +def main(unused_argv=None): |
| 166 | + tf.logging.info(tf.__version__) |
| 167 | + train_and_evaluate() |
| 168 | + |
| 169 | +if __name__ == '__main__': |
| 170 | + tf.app.run() |
0 commit comments