test_allreduce.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import asyncio
  2. import random
  3. import time
  4. from typing import Sequence
  5. import pytest
  6. import torch
  7. from hivemind import aenumerate
  8. from hivemind.averaging.allreduce import AllReduceRunner, AveragingMode
  9. from hivemind.averaging.partition import TensorPartContainer, TensorPartReducer
  10. from hivemind.p2p import P2P, StubBase
  11. from hivemind.proto.runtime_pb2 import CompressionType
  12. from hivemind.utils import deserialize_torch_tensor
  13. @pytest.mark.forked
  14. @pytest.mark.asyncio
  15. async def test_partitioning():
  16. all_tensors = [
  17. torch.randn(30_000, 128),
  18. torch.rand(128),
  19. torch.ones(1, 1, 1, 1, 1, 1, 8),
  20. torch.ones(1, 0),
  21. torch.zeros(0),
  22. torch.zeros([]),
  23. torch.randn(65536),
  24. torch.rand(512, 2048),
  25. torch.randn(1024, 1024).add(-9),
  26. torch.zeros(1020),
  27. torch.randn(4096),
  28. ]
  29. # note: this test does _not_ use parameterization to reuse sampled tensors
  30. for num_tensors in 1, 3, 5:
  31. for part_size_bytes in 31337, 2 ** 20, 10 ** 10:
  32. for weights in [(1, 1), (0.333, 0.1667, 0.5003), (1.0, 0.0), [0.0, 0.4, 0.6, 0.0]]:
  33. tensors = random.choices(all_tensors, k=num_tensors)
  34. partition = TensorPartContainer(tensors, weights, part_size_bytes=part_size_bytes)
  35. async def write_tensors():
  36. for peer_index in range(partition.group_size):
  37. async for part_index, part in aenumerate(partition.iterate_input_parts_for(peer_index)):
  38. output_tensor = torch.sin(deserialize_torch_tensor(part))
  39. partition.register_processed_part(peer_index, part_index, output_tensor)
  40. task = asyncio.create_task(write_tensors())
  41. tensor_index = 0
  42. async for output_tensor in partition.iterate_output_tensors():
  43. assert torch.allclose(output_tensor, torch.sin(tensors[tensor_index]))
  44. tensor_index += 1
  45. assert tensor_index == len(tensors)
  46. await task
  47. @pytest.mark.parametrize(
  48. "tensors",
  49. [
  50. [torch.zeros(0)],
  51. [torch.zeros(0), torch.zeros(0), torch.zeros(1)],
  52. [torch.zeros(0), torch.zeros(999), torch.zeros(0), torch.zeros(0)],
  53. ],
  54. )
  55. @pytest.mark.parametrize("peer_fractions", [(0.33, 0.44, 0.23), (0.5, 0.5), (0.1, 0.0, 0.9), (1.0,), (0.1,) * 9])
  56. @pytest.mark.forked
  57. @pytest.mark.asyncio
  58. async def test_partitioning_edge_cases(tensors: Sequence[torch.Tensor], peer_fractions: Sequence[float]):
  59. partition = TensorPartContainer(tensors, peer_fractions, part_size_bytes=16)
  60. for peer_index in range(len(peer_fractions)):
  61. async for part_index, part in aenumerate(partition.iterate_input_parts_for(peer_index)):
  62. partition.register_processed_part(peer_index, part_index, deserialize_torch_tensor(part))
  63. tensor_index = 0
  64. async for output_tensor in partition.iterate_output_tensors():
  65. assert torch.allclose(output_tensor, tensors[tensor_index])
  66. tensor_index += 1
  67. @pytest.mark.forked
  68. @pytest.mark.asyncio
  69. async def test_partitioning_asynchronous():
  70. """ensure that tensor partitioning does not interfere with asynchronous code"""
  71. tensors = [torch.randn(2048, 2048), torch.randn(1024, 4096), torch.randn(4096, 1024), torch.randn(30_000, 1024)]
  72. peer_fractions = [0.4, 0.3, 0.2, 0.1]
  73. partition = TensorPartContainer(tensors, peer_fractions, compression_type=CompressionType.QUANTILE_8BIT)
  74. read_started, read_finished = asyncio.Event(), asyncio.Event()
  75. async def write_tensors():
  76. for peer_index in range(partition.group_size):
  77. async for part_index, part in aenumerate(partition.iterate_input_parts_for(peer_index)):
  78. partition.register_processed_part(peer_index, part_index, deserialize_torch_tensor(part))
  79. assert read_started.is_set(), "partitioner should have started reading before it finished writing"
  80. async def read_tensors():
  81. async for _ in partition.iterate_output_tensors():
  82. read_started.set()
  83. read_finished.set()
  84. async def wait_synchronously():
  85. time_in_waiting = 0.0
  86. while not read_finished.is_set():
  87. await asyncio.sleep(0.01)
  88. time_in_waiting += 0.01
  89. return time_in_waiting
  90. start_time = time.perf_counter()
  91. *_, time_in_waiting = await asyncio.gather(write_tensors(), read_tensors(), wait_synchronously())
  92. wall_time = time.perf_counter() - start_time
  93. # check that event loop had enough time to respond to incoming requests; this is over 50% most of the time
  94. # we set 33% threshold to ensure that the test will pass reliably. If we break prefetch, this drops to <10%
  95. assert time_in_waiting > wall_time / 3, f"Event loop could only run {time_in_waiting / wall_time :.5f} of the time"
  96. @pytest.mark.parametrize("num_senders", [1, 2, 4, 10])
  97. @pytest.mark.parametrize("num_parts", [0, 1, 100])
  98. @pytest.mark.parametrize("synchronize_prob", [1.0, 0.1, 0.0])
  99. @pytest.mark.forked
  100. @pytest.mark.asyncio
  101. async def test_reducer(num_senders: int, num_parts: int, synchronize_prob: float):
  102. tensor_part_shapes = [torch.Size([i]) for i in range(num_parts)]
  103. reducer = TensorPartReducer(tensor_part_shapes, num_senders)
  104. local_tensors_by_sender = [[torch.randn(i) for i in range(num_parts)] for j in range(num_senders)]
  105. async def send_tensors(sender_index: int):
  106. local_tensors = local_tensors_by_sender[sender_index]
  107. averaged_parts = []
  108. pending_tasks = []
  109. for part_index in range(num_parts):
  110. pending_tasks.append(
  111. asyncio.create_task(reducer.accumulate_part(sender_index, part_index, local_tensors[part_index]))
  112. )
  113. if random.random() < synchronize_prob or part_index == num_parts - 1:
  114. averaged_parts.extend(await asyncio.gather(*pending_tasks))
  115. pending_tasks = []
  116. return averaged_parts
  117. averaged_tensors_by_peer = await asyncio.gather(*map(send_tensors, range(num_senders)))
  118. reference = [
  119. sum(local_tensors_by_sender[sender_index][part_index] for sender_index in range(num_senders)) / num_senders
  120. for part_index in range(num_parts)
  121. ]
  122. for averaged_tensors in averaged_tensors_by_peer:
  123. assert len(averaged_tensors) == len(reference)
  124. for averaging_result, reference_tensor in zip(averaged_tensors, reference):
  125. assert torch.allclose(averaging_result, reference_tensor, rtol=1e-3, atol=1e-5)
  126. NODE, CLIENT, AUX = AveragingMode.NODE, AveragingMode.CLIENT, AveragingMode.AUX
  127. @pytest.mark.parametrize(
  128. "peer_modes, averaging_weights, peer_fractions, part_size_bytes",
  129. [
  130. ((NODE, NODE, NODE, NODE), (1, 1, 1, 1), (1, 1, 1, 1), 2 ** 20),
  131. ((NODE, NODE, NODE, NODE), (0.1, 0.2, 0.3, 0.4), (1, 1, 1, 1), 2 ** 20),
  132. ((NODE, NODE, NODE, NODE), (1, 1, 1, 1), (1, 2, 3, 0), 2 ** 20),
  133. ((NODE, NODE, NODE, CLIENT), (1, 1, 1, 1), (1, 2, 3, 0), 2 ** 20),
  134. ((NODE, NODE, NODE, AUX), (1, 1, 1, 0), (1, 2, 3, 4), 2 ** 20),
  135. ((NODE, NODE, NODE, NODE), (0.15, 0.0, 0.35, 0.45), (1, 1, 1, 1), 2 ** 20),
  136. ((NODE, AUX, NODE, CLIENT), (0.15, 0.0, 0.35, 0.45), (150, 200, 67, 0), 2 ** 20),
  137. ((NODE, AUX, NODE, CLIENT), (0.15, 0.0, 0.35, 0.45), (150, 200, 67, 0), 256),
  138. ((NODE, AUX, NODE, CLIENT), (0.15, 0.0, 0.35, 0.45), (150, 200, 67, 0), 19),
  139. ((AUX, AUX, AUX, AUX), (0.0, 0.0, 0.0, 0.0), (1, 2, 3, 4), 2 ** 20),
  140. ],
  141. )
  142. @pytest.mark.forked
  143. @pytest.mark.asyncio
  144. async def test_allreduce_protocol(peer_modes, averaging_weights, peer_fractions, part_size_bytes):
  145. """Run group allreduce protocol manually without grpc, see if the internal logic is working as intended"""
  146. p2ps = [await P2P.create()]
  147. visible_maddrs = await p2ps[0].get_visible_maddrs()
  148. p2ps += await asyncio.gather(*[P2P.create(initial_peers=visible_maddrs) for _ in range(3)])
  149. peers = [instance.id for instance in p2ps]
  150. tensors_by_peer = {
  151. peer: [torch.randn(3, 128), torch.rand(32), torch.tensor(i, dtype=torch.float32)]
  152. for i, peer in enumerate(peers)
  153. }
  154. group_id = random.getrandbits(160).to_bytes(length=20, byteorder="big")
  155. allreduce_protocols = []
  156. for p2p in p2ps:
  157. allreduce_protocol = AllReduceRunner(
  158. p2p=p2p,
  159. servicer_type=AllReduceRunner,
  160. prefix=None,
  161. group_id=group_id,
  162. tensors=[x.clone() for x in tensors_by_peer[p2p.id]],
  163. ordered_group_endpoints=peers,
  164. peer_fractions=peer_fractions,
  165. modes=peer_modes,
  166. weights=averaging_weights,
  167. part_size_bytes=part_size_bytes,
  168. )
  169. await allreduce_protocol.add_p2p_handlers(p2p)
  170. allreduce_protocols.append(allreduce_protocol)
  171. async def _run_allreduce_inplace(allreduce: AllReduceRunner):
  172. async for tensor_index, tensor_delta in aenumerate(allreduce):
  173. allreduce.tensor_part_container.local_tensors[tensor_index].add_(tensor_delta)
  174. await asyncio.gather(*map(_run_allreduce_inplace, allreduce_protocols))
  175. reference_tensors = [
  176. sum(tensors_by_peer[peer][i] * averaging_weights[peer_index] for peer_index, peer in enumerate(peers))
  177. / sum(averaging_weights)
  178. for i in range(len(tensors_by_peer[peers[0]]))
  179. ]
  180. for peer_index, protocol in enumerate(allreduce_protocols):
  181. assert protocol._future.done()
  182. if protocol.modes[peer_index] != AveragingMode.AUX:
  183. targets_for_peer = reference_tensors
  184. else:
  185. targets_for_peer = tensors_by_peer[peers[peer_index]]
  186. output_tensors = protocol.tensor_part_container.local_tensors
  187. assert len(output_tensors) == len(targets_for_peer)
  188. assert all(torch.allclose(our, ref, atol=1e-6, rtol=0) for our, ref in zip(output_tensors, targets_for_peer))
  189. for instance in p2ps:
  190. await instance.shutdown()