data_utils.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import sys
  17. import tensorflow as tf
  18. from utils import image_processing
  19. from utils import dali_utils
  20. from utils import hvd_wrapper as hvd
  21. __all__ = ["get_synth_input_fn", "normalized_inputs"]
  22. _R_MEAN = 123.68
  23. _G_MEAN = 116.28
  24. _B_MEAN = 103.53
  25. _CHANNEL_MEANS = [_R_MEAN, _G_MEAN, _B_MEAN]
  26. _CHANNEL_STDS = [58.395, 57.120, 57.385]
  27. _NUM_CHANNELS = 3
  28. def get_synth_input_fn(batch_size, height, width, num_channels, data_format, num_classes, dtype=tf.float32):
  29. """Returns an input function that returns a dataset with random data.
  30. This input_fn returns a data set that iterates over a set of random data and
  31. bypasses all preprocessing, e.g. jpeg decode and copy. The host to device
  32. copy is still included. This used to find the upper throughput bound when
  33. tunning the full input pipeline.
  34. Args:
  35. height: Integer height that will be used to create a fake image tensor.
  36. width: Integer width that will be used to create a fake image tensor.
  37. num_channels: Integer depth that will be used to create a fake image tensor.
  38. num_classes: Number of classes that should be represented in the fake labels
  39. tensor
  40. dtype: Data type for features/images.
  41. Returns:
  42. An input_fn that can be used in place of a real one to return a dataset
  43. that can be used for iteration.
  44. """
  45. if data_format not in ["NHWC", "NCHW"]:
  46. raise ValueError("Unknown data_format: %s" % str(data_format))
  47. if data_format == "NHWC":
  48. input_shape = [batch_size, height, width, num_channels]
  49. else:
  50. input_shape = [batch_size, num_channels, height, width]
  51. # Convert the inputs to a Dataset.
  52. inputs = tf.truncated_normal(input_shape, dtype=dtype, mean=127, stddev=60, name='synthetic_inputs')
  53. labels = tf.random_uniform([batch_size], minval=0, maxval=num_classes - 1, dtype=tf.int32, name='synthetic_labels')
  54. data = tf.data.Dataset.from_tensors((inputs, labels))
  55. data = data.repeat()
  56. data = data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
  57. return data
  58. def get_tfrecords_input_fn(filenames, batch_size, height, width, training, distort_color, num_threads, deterministic):
  59. shuffle_buffer_size = 4096
  60. if deterministic:
  61. seed = 13 * hvd.rank()
  62. else:
  63. seed = None
  64. ds = tf.data.Dataset.from_tensor_slices(filenames)
  65. if hvd.size() > 1 and training:
  66. ds = ds.shard(hvd.size(), hvd.rank())
  67. ds = ds.interleave(tf.data.TFRecordDataset, cycle_length=10, block_length=8)
  68. def preproc_func(record):
  69. return image_processing.preprocess_image_record(record, height, width, _NUM_CHANNELS, training)
  70. if training:
  71. ds = ds.shuffle(buffer_size=shuffle_buffer_size, seed=seed)
  72. ds = ds.repeat().map(preproc_func, num_parallel_calls=num_threads)
  73. ds = ds.batch(batch_size=batch_size, drop_remainder=True)
  74. ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
  75. return ds
  76. def get_inference_input_fn(filenames, height, width, num_threads):
  77. ds = tf.data.Dataset.from_tensor_slices(filenames)
  78. counter = tf.data.Dataset.range(sys.maxsize)
  79. ds = tf.data.Dataset.zip((ds, counter))
  80. def preproc_func(record, counter_):
  81. return image_processing.preprocess_image_file(record, height, width, _NUM_CHANNELS, is_training=False)
  82. ds = ds.apply(
  83. tf.data.experimental.map_and_batch(map_func=preproc_func, num_parallel_calls=num_threads, batch_size=1)
  84. )
  85. ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
  86. return ds
  87. def get_dali_input_fn(
  88. filenames, idx_filenames, batch_size, height, width, training, distort_color, num_threads, deterministic
  89. ):
  90. if idx_filenames is None:
  91. raise ValueError("Must provide idx_filenames for DALI's reader")
  92. preprocessor = dali_utils.DALIPreprocessor(
  93. filenames,
  94. idx_filenames,
  95. height,
  96. width,
  97. batch_size,
  98. num_threads,
  99. dali_cpu=False,
  100. deterministic=deterministic,
  101. training=training
  102. )
  103. images, labels = preprocessor.get_device_minibatches()
  104. return (images, labels)
  105. def normalized_inputs(inputs):
  106. num_channels = inputs.get_shape()[-1]
  107. if inputs.get_shape().ndims != 4:
  108. raise ValueError('Input must be of size [batch_size, height, width, C>0]')
  109. if len(_CHANNEL_MEANS) != num_channels:
  110. raise ValueError('len(means) must match the number of channels')
  111. # We have a 1-D tensor of means; convert to 3-D.
  112. means_per_channel = tf.reshape(_CHANNEL_MEANS, [1, 1, num_channels])
  113. means_per_channel = tf.cast(means_per_channel, dtype=inputs.dtype)
  114. stds_per_channel = tf.reshape(_CHANNEL_STDS, [1, 1, num_channels])
  115. stds_per_channel = tf.cast(stds_per_channel, dtype=inputs.dtype)
  116. inputs = tf.subtract(inputs, means_per_channel)
  117. return tf.divide(inputs, stds_per_channel)
  118. def get_serving_input_receiver_fn(batch_size, height, width, num_channels, data_format, dtype=tf.float32):
  119. if data_format not in ["NHWC", "NCHW"]:
  120. raise ValueError("Unknown data_format: %s" % str(data_format))
  121. if data_format == "NHWC":
  122. input_shape = [batch_size] + [height, width, num_channels]
  123. else:
  124. input_shape = [batch_size] + [num_channels, height, width]
  125. def serving_input_receiver_fn():
  126. features = tf.placeholder(dtype=dtype, shape=input_shape, name='input_tensor')
  127. return tf.estimator.export.TensorServingInputReceiver(features=features, receiver_tensors=features)
  128. return serving_input_receiver_fn