test_allreduce.py 9.7 KB

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