Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2689c9a

Browse files
authored
Add eager for keras benchmark (tensorflow#4825)
* Add more arguments * Add eager mode * Add notes for eager mode * Address the comments * Fix argument typos * Add warning for eager and multi-gpu * Fix typo * Fix notes * Fix pylint
1 parent 15b3336 commit 2689c9a

File tree

2 files changed

+45
-18
lines changed

2 files changed

+45
-18
lines changed

official/keras_application_models/benchmark_main.py

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ def run_keras_model_benchmark(_):
5454
raise AssertionError("The --model command line argument should "
5555
"be a key in the `MODELS` dictionary.")
5656

57+
# Check if eager execution is enabled
58+
if FLAGS.eager:
59+
tf.logging.info("Eager execution is enabled...")
60+
tf.enable_eager_execution()
61+
5762
# Load the model
5863
tf.logging.info("Benchmark on {} model...".format(FLAGS.model))
5964
keras_model = MODELS[FLAGS.model]
@@ -64,30 +69,35 @@ def run_keras_model_benchmark(_):
6469
if FLAGS.use_synthetic_data:
6570
tf.logging.info("Using synthetic dataset...")
6671
dataset_name += "_Synthetic"
67-
train_num_images = FLAGS.batch_size
68-
val_num_images = FLAGS.batch_size
6972
train_dataset = dataset.generate_synthetic_input_dataset(
70-
FLAGS.model, train_num_images)
73+
FLAGS.model, FLAGS.batch_size)
7174
val_dataset = dataset.generate_synthetic_input_dataset(
72-
FLAGS.model, val_num_images)
75+
FLAGS.model, FLAGS.batch_size)
7376
else:
7477
raise ValueError("Only synthetic dataset is supported!")
7578

7679
# If run with multiple GPUs
80+
# If eager execution is enabled, only one GPU is utilized even if multiple
81+
# GPUs are provided.
7782
num_gpus = flags_core.get_num_gpus(FLAGS)
78-
if num_gpus > 0:
83+
if num_gpus > 1:
84+
if FLAGS.eager:
85+
tf.logging.warning(
86+
"{} GPUs are provided, but only one GPU is utilized as "
87+
"eager execution is enabled.".format(num_gpus))
7988
model = tf.keras.utils.multi_gpu_model(model, gpus=num_gpus)
8089

81-
# Configure the model
8290
model.compile(loss="categorical_crossentropy",
83-
optimizer="sgd",
91+
optimizer=tf.train.AdamOptimizer(),
8492
metrics=["accuracy"])
8593

8694
# Create benchmark logger for benchmark logging
8795
run_params = {
8896
"batch_size": FLAGS.batch_size,
8997
"synthetic_data": FLAGS.use_synthetic_data,
90-
"train_epochs": FLAGS.train_epochs
98+
"train_epochs": FLAGS.train_epochs,
99+
"num_train_images": FLAGS.num_images,
100+
"num_eval_images": FLAGS.num_images,
91101
}
92102

93103
benchmark_logger = logger.get_benchmark_logger()
@@ -108,8 +118,8 @@ def run_keras_model_benchmark(_):
108118
epochs=FLAGS.train_epochs,
109119
callbacks=callbacks,
110120
validation_data=val_dataset,
111-
steps_per_epoch=int(np.ceil(train_num_images / FLAGS.batch_size)),
112-
validation_steps=int(np.ceil(val_num_images / FLAGS.batch_size))
121+
steps_per_epoch=int(np.ceil(FLAGS.num_images / FLAGS.batch_size)),
122+
validation_steps=int(np.ceil(FLAGS.num_images / FLAGS.batch_size))
113123
)
114124

115125
tf.logging.info("Logging the evaluation results...")
@@ -118,7 +128,7 @@ def run_keras_model_benchmark(_):
118128
"accuracy": history.history["val_acc"][epoch],
119129
"loss": history.history["val_loss"][epoch],
120130
tf.GraphKeys.GLOBAL_STEP: (epoch + 1) * np.ceil(
121-
train_num_images/FLAGS.batch_size)
131+
FLAGS.num_images/FLAGS.batch_size)
122132
}
123133
benchmark_logger.log_evaluation_result(eval_results)
124134

@@ -146,6 +156,18 @@ def define_keras_benchmark_flags():
146156
help=flags_core.help_wrap(
147157
"Model to be benchmarked."))
148158

159+
flags.DEFINE_integer(
160+
name="num_images", default=1000,
161+
help=flags_core.help_wrap(
162+
"The number of synthetic images for training and evaluation. The "
163+
"default value is 1000."))
164+
165+
flags.DEFINE_boolean(
166+
name="eager", default=False, help=flags_core.help_wrap(
167+
"To enable eager execution. Note that if eager execution is enabled, "
168+
"only one GPU is utilized even if multiple GPUs are provided and "
169+
"multi_gpu_model is used."))
170+
149171
flags.DEFINE_list(
150172
name="callbacks",
151173
default=["ExamplesPerSecondCallback", "LoggingMetricCallback"],
@@ -159,6 +181,7 @@ def main(_):
159181
with logger.benchmark_context(FLAGS):
160182
run_keras_model_benchmark(FLAGS)
161183

184+
162185
if __name__ == "__main__":
163186
tf.logging.set_verbosity(tf.logging.INFO)
164187
define_keras_benchmark_flags()

official/keras_application_models/dataset.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919

2020
import tensorflow as tf
2121

22+
from official.utils.misc import model_helpers # pylint: disable=g-bad-import-order
23+
2224
# Default values for dataset.
2325
_NUM_CHANNELS = 3
2426
_NUM_CLASSES = 1000
@@ -34,12 +36,14 @@ def _get_default_image_size(model):
3436
return image_size
3537

3638

37-
def generate_synthetic_input_dataset(model, num_imgs):
39+
def generate_synthetic_input_dataset(model, batch_size):
3840
"""Generate synthetic dataset."""
3941
image_size = _get_default_image_size(model)
40-
input_shape = (num_imgs,) + image_size + (_NUM_CHANNELS,)
41-
42-
images = tf.zeros(input_shape, dtype=tf.float32)
43-
labels = tf.zeros((num_imgs, _NUM_CLASSES), dtype=tf.float32)
44-
45-
return tf.data.Dataset.from_tensors((images, labels)).repeat()
42+
image_shape = (batch_size,) + image_size + (_NUM_CHANNELS,)
43+
label_shape = (batch_size, _NUM_CLASSES)
44+
45+
return model_helpers.generate_synthetic_data(
46+
input_shape=tf.TensorShape(image_shape),
47+
input_dtype=tf.float32,
48+
label_shape=tf.TensorShape(label_shape),
49+
label_dtype=tf.float32)

0 commit comments

Comments
 (0)