benchmark_throughput.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import argparse
  2. import multiprocessing as mp
  3. import random
  4. import sys
  5. import time
  6. import torch
  7. import hivemind
  8. from hivemind import find_open_port
  9. from hivemind.server import layers
  10. from hivemind.utils.threading import increase_file_limit
  11. def print_device_info(device=None):
  12. """Prints device stats. Code from https://stackoverflow.com/a/53374933/12891528"""
  13. device = torch.device(device or ('cuda' if torch.cuda.is_available() else 'cpu'))
  14. print('Using device:', device)
  15. # Additional Info when using cuda
  16. if device.type == 'cuda':
  17. print(torch.cuda.get_device_name(0))
  18. print('Memory Usage:')
  19. print('Allocated:', round(torch.cuda.memory_allocated(0) / 1024 ** 3, 1), 'GB')
  20. print('Cached: ', round(torch.cuda.memory_cached(0) / 1024 ** 3, 1), 'GB')
  21. def client_process(can_start, benchmarking_failed, port, num_experts, batch_size, hid_dim, num_batches, backprop=True):
  22. torch.set_num_threads(1)
  23. can_start.wait()
  24. experts = [hivemind.RemoteExpert(f"expert{i}", endpoint=f"{hivemind.LOCALHOST}:{port}") for i in range(num_experts)]
  25. try:
  26. dummy_batch = torch.randn(batch_size, hid_dim)
  27. for batch_i in range(num_batches):
  28. expert = random.choice(experts)
  29. out = expert(dummy_batch)
  30. if backprop:
  31. out.sum().backward()
  32. except BaseException as e:
  33. benchmarking_failed.set()
  34. raise e
  35. def benchmark_throughput(num_experts=16, num_handlers=None, num_clients=128, num_batches_per_client=16,
  36. expert_cls='ffn', hid_dim=1024, batch_size=2048, max_batch_size=None, backprop=True,
  37. device=None, port=None):
  38. assert not hasattr(torch.cuda, 'is_initialized') or not torch.cuda.is_initialized() \
  39. or torch.device(device) == torch.device('cpu')
  40. assert expert_cls in layers.name_to_block
  41. port = port or find_open_port()
  42. max_batch_size = max_batch_size or batch_size * 4
  43. num_handlers = max(1, num_handlers or num_clients // 2)
  44. benchmarking_failed = mp.Event()
  45. can_start = mp.Event()
  46. timestamps = dict(started=time.perf_counter())
  47. try:
  48. # start clients and await server
  49. # Note: client processes must be launched BEFORE touching gpu, even torch.cuda.is_available can cause trouble
  50. clients = [
  51. mp.Process(
  52. target=client_process, name=f'client_process-{i}',
  53. args=(can_start, benchmarking_failed, port, num_experts, batch_size,
  54. hid_dim, num_batches_per_client, backprop))
  55. for i in range(num_clients)]
  56. for client in clients:
  57. client.daemon = True
  58. client.start()
  59. timestamps['launched_clients'] = timestamps['began_launching_server'] = time.perf_counter()
  60. # start server
  61. device = device or ('cuda' if torch.cuda.is_available() else 'cpu')
  62. experts = {}
  63. for i in range(num_experts):
  64. expert = torch.jit.script(layers.name_to_block[expert_cls](hid_dim))
  65. experts[f'expert{i}'] = hivemind.ExpertBackend(name=f'expert{i}',
  66. expert=expert,
  67. optimizer=torch.optim.Adam(expert.parameters()),
  68. args_schema=(hivemind.BatchTensorDescriptor(hid_dim),),
  69. outputs_schema=hivemind.BatchTensorDescriptor(hid_dim),
  70. max_batch_size=max_batch_size,
  71. )
  72. timestamps['created_experts'] = time.perf_counter()
  73. server = hivemind.Server(None, experts, listen_on=f"{hivemind.LOCALHOST}:{port}",
  74. num_connection_handlers=num_handlers, device=device)
  75. server.start()
  76. server.ready.wait()
  77. timestamps['server_ready'] = time.perf_counter()
  78. can_start.set()
  79. for client in clients:
  80. client.join()
  81. timestamps['clients_finished'] = time.perf_counter()
  82. except BaseException as e:
  83. benchmarking_failed.set()
  84. raise e
  85. finally:
  86. for client in clients:
  87. if client.is_alive():
  88. client.terminate()
  89. server.shutdown()
  90. timestamps['server_shutdown_finished'] = time.perf_counter()
  91. server.join()
  92. sys.stdout.flush()
  93. sys.stderr.flush()
  94. time_between = lambda key1, key2: \
  95. abs(timestamps[key2] - timestamps[key1]) if (key1 in timestamps and key2 in timestamps) else float('nan')
  96. total_examples = batch_size * num_clients * num_batches_per_client
  97. print('\n' * 3)
  98. print("Benchmark finished, status:" + ["Success", "Failure"][benchmarking_failed.is_set()])
  99. print(f"Server parameters: num_experts={num_experts}, num_handlers={num_handlers}, max_batch_size={max_batch_size},"
  100. f" expert_cls={expert_cls}, hid_dim={hid_dim}, device={device}")
  101. print(f"Client parameters: num_clients={num_clients}, num_batches_per_client={num_batches_per_client}, "
  102. f"batch_size={batch_size}, backprop={backprop}")
  103. print("Results: ")
  104. print(f"\tServer startup took {time_between('began_launching_server', 'server_ready') :.3f} s. "
  105. f"({time_between('began_launching_server', 'created_experts') :.3f} s. experts + "
  106. f"{time_between('created_experts', 'server_ready') :.3f} s. networking)")
  107. print(f"\tProcessed {total_examples} examples in {time_between('server_ready', 'clients_finished') :.3f}")
  108. print(f"\tThroughput for {'forward + backward' if backprop else 'forward'} passes: "
  109. f"{total_examples / time_between('server_ready', 'clients_finished') :.3f} samples / s.")
  110. print(f"\tBenchmarking took {time_between('started', 'server_shutdown_finished') :.3f} s.")
  111. if benchmarking_failed.is_set():
  112. print("Note: benchmark code failed, timing/memory results only indicate time till failure!")
  113. print_device_info(device)
  114. print(flush=True)
  115. assert not benchmarking_failed.is_set()
  116. if __name__ == "__main__":
  117. parser = argparse.ArgumentParser()
  118. parser.add_argument('--preset', type=str, default='default', required=False)
  119. parser.add_argument('--num_batches_per_client', type=int, default=16, required=False)
  120. args = parser.parse_args()
  121. if args.preset in ('default', 'ffn_forward_backward'):
  122. benchmark_throughput()
  123. elif args.preset == 'ffn_forward':
  124. benchmark_throughput(backprop=False, num_batches_per_client=args.num_batches_per_client)
  125. elif args.preset == 'ffn_small_batch':
  126. benchmark_throughput(backprop=False, num_experts=4, batch_size=32, max_batch_size=8192,
  127. num_batches_per_client=args.num_batches_per_client)
  128. elif args.preset == 'ffn_small_batch_512clients':
  129. benchmark_throughput(backprop=True, num_experts=1, batch_size=1, max_batch_size=8192,
  130. num_clients=512, num_batches_per_client=args.num_batches_per_client)
  131. elif args.preset == 'ffn_small_batch_512clients_32handlers':
  132. benchmark_throughput(backprop=True, num_experts=1, batch_size=1, max_batch_size=8192, num_handlers=32,
  133. num_clients=512, num_batches_per_client=args.num_batches_per_client)
  134. elif args.preset == 'ffn_massive':
  135. increase_file_limit()
  136. benchmark_throughput(backprop=False, num_clients=512, batch_size=512,
  137. max_batch_size=8192, num_batches_per_client=args.num_batches_per_client)
  138. elif args.preset == 'minimalistic':
  139. benchmark_throughput(num_experts=1, num_clients=1, num_handlers=1,
  140. num_batches_per_client=args.num_batches_per_client)
  141. elif args.preset == 'nop':
  142. benchmark_throughput(expert_cls='nop', backprop=False, num_batches_per_client=args.num_batches_per_client)
  143. else:
  144. raise ValueError(f"No such benchmark preset: {args.preset}")