inference.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. #
  2. # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import time
  16. import os
  17. import json
  18. import argparse
  19. import numpy as np
  20. import os
  21. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
  22. import tensorflow as tf
  23. from neumf import ncf_model_ops
  24. import dllogger
  25. def parse_args():
  26. parser = argparse.ArgumentParser(description="Benchmark inference performance of the NCF model")
  27. parser.add_argument('--load_checkpoint_path', default=None, type=str,
  28. help='Path to the checkpoint file to be loaded. If None will use random weights')
  29. parser.add_argument('--n_users', default=138493, type=int,
  30. help='Number of users. Defaults to the number of users in the ml-20m dataset after preprocessing')
  31. parser.add_argument('--n_items', default=26744, type=int,
  32. help='Number of items. Defaults to the number of users in the ml-20m dataset after preprocessing')
  33. parser.add_argument('-f', '--factors', type=int, default=64,
  34. help='Number of predictive factors')
  35. parser.add_argument('--layers', nargs='+', type=int,
  36. default=[256, 256, 128, 64],
  37. help='Sizes of hidden layers for MLP')
  38. parser.add_argument('--batch_sizes', default='1,4,16,64,256,1024,4096,16384,65536,262144,1048576', type=str,
  39. help='A list of comma-separated batch size values to benchmark')
  40. parser.add_argument('--num_batches', default=200, type=int,
  41. help='Number of batches for which to measure latency and throughput')
  42. parser.add_argument('--amp', action='store_true', default=False,
  43. help='Enable automatic mixed precision')
  44. parser.add_argument('--xla', dest='xla', action='store_true', default=False,
  45. help='Enable XLA')
  46. parser.add_argument('--log_path', default='log.json', type=str,
  47. help='Path to the path to store benchmark results')
  48. return parser.parse_args()
  49. def main():
  50. args = parse_args()
  51. if args.amp:
  52. os.environ["TF_ENABLE_AUTO_MIXED_PRECISION"] = "1"
  53. dllogger.init(backends=[dllogger.JSONStreamBackend(verbosity=dllogger.Verbosity.VERBOSE,
  54. filename=args.log_path),
  55. dllogger.StdOutBackend(verbosity=dllogger.Verbosity.VERBOSE)])
  56. dllogger.log(data=vars(args), step='PARAMETER')
  57. batch_sizes = args.batch_sizes.split(',')
  58. batch_sizes = [int(s) for s in batch_sizes]
  59. result_data = {}
  60. for batch_size in batch_sizes:
  61. print('Benchmarking batch size', batch_size)
  62. tf.reset_default_graph()
  63. # Input tensors
  64. users = tf.placeholder(tf.int32, shape=(None,))
  65. items = tf.placeholder(tf.int32, shape=(None,))
  66. dropout = tf.placeholder_with_default(0.0, shape=())
  67. # Model ops and saver
  68. logits_op = ncf_model_ops(users=users, items=items, labels=None, dup_mask=None, mode='INFERENCE',
  69. params={'fp16': False, 'val_batch_size': batch_size, 'num_users': args.n_users,
  70. 'num_items': args.n_items, 'num_factors': args.factors, 'mf_reg': 0,
  71. 'layer_sizes': args.layers, 'layer_regs': [0. for i in args.layers],
  72. 'dropout': 0.0, 'sigmoid': True, 'top_k': None, 'learning_rate': None,
  73. 'beta_1': None, 'beta_2': None, 'epsilon': None, 'loss_scale': None, })
  74. config = tf.ConfigProto()
  75. config.gpu_options.allow_growth = True
  76. if args.xla:
  77. config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1
  78. sess = tf.Session(config=config)
  79. saver = tf.train.Saver()
  80. if args.load_checkpoint_path:
  81. saver.restore(sess, args.load_checkpoint_path)
  82. else:
  83. sess.run(tf.global_variables_initializer())
  84. sess.run(tf.local_variables_initializer())
  85. users_batch = np.random.randint(size=batch_size, low=0, high=args.n_users)
  86. items_batch = np.random.randint(size=batch_size, low=0, high=args.n_items)
  87. latencies = []
  88. for i in range(args.num_batches):
  89. start = time.time()
  90. _ = sess.run(logits_op, feed_dict={users: users_batch, items: items_batch, dropout: 0.0 })
  91. end = time.time()
  92. if i < 10: # warmup iterations
  93. continue
  94. latencies.append(end - start)
  95. result_data[f'batch_{batch_size}_mean_throughput'] = batch_size / np.mean(latencies)
  96. result_data[f'batch_{batch_size}_mean_latency'] = np.mean(latencies)
  97. result_data[f'batch_{batch_size}_p90_latency'] = np.percentile(latencies, 90)
  98. result_data[f'batch_{batch_size}_p95_latency'] = np.percentile(latencies, 95)
  99. result_data[f'batch_{batch_size}_p99_latency'] = np.percentile(latencies, 99)
  100. dllogger.log(data=result_data, step=tuple())
  101. dllogger.flush()
  102. if __name__ == '__main__':
  103. main()