test_util_modules.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import asyncio
  2. import torch
  3. import numpy as np
  4. import pytest
  5. import hivemind
  6. from hivemind.proto.dht_pb2_grpc import DHTStub
  7. from hivemind.proto.runtime_pb2_grpc import ConnectionHandlerStub
  8. from concurrent.futures import CancelledError
  9. def test_mpfuture_result():
  10. f1, f2 = hivemind.MPFuture.make_pair()
  11. f1.set_result(321)
  12. assert f2.result() == 321
  13. assert f1.result() == 321
  14. for future in [f1, f2]:
  15. with pytest.raises(RuntimeError):
  16. future.set_result(123)
  17. with pytest.raises(RuntimeError):
  18. future.set_exception(ValueError())
  19. assert future.cancel() is False
  20. assert future.done() and not future.running() and not future.cancelled()
  21. f1, f2 = hivemind.MPFuture.make_pair()
  22. with pytest.raises(TimeoutError):
  23. f1.result(timeout=1e-3)
  24. f2.set_result(['abacaba', 123])
  25. assert f1.result() == ['abacaba', 123]
  26. def test_mpfuture_exception():
  27. f1, f2 = hivemind.MPFuture.make_pair()
  28. with pytest.raises(TimeoutError):
  29. f1.exception(timeout=1e-3)
  30. f2.set_exception(NotImplementedError())
  31. for future in [f1, f2]:
  32. assert isinstance(future.exception(), NotImplementedError)
  33. with pytest.raises(NotImplementedError):
  34. future.result()
  35. assert future.cancel() is False
  36. assert future.done() and not future.running() and not future.cancelled()
  37. def test_mpfuture_cancel():
  38. f1, f2 = hivemind.MPFuture.make_pair()
  39. assert not f2.cancelled()
  40. f1.cancel()
  41. for future in [f1, f2]:
  42. with pytest.raises(CancelledError):
  43. future.result()
  44. with pytest.raises(CancelledError):
  45. future.exception()
  46. with pytest.raises(RuntimeError):
  47. future.set_result(123)
  48. with pytest.raises(RuntimeError):
  49. future.set_exception(NotImplementedError())
  50. assert future.cancelled() and future.done() and not future.running()
  51. def test_mpfuture_status():
  52. f1, f2 = hivemind.MPFuture.make_pair()
  53. assert f1.set_running_or_notify_cancel() is True
  54. for future in [f1, f2]:
  55. assert future.running() and not future.done() and not future.cancelled()
  56. with pytest.raises(RuntimeError):
  57. future.set_running_or_notify_cancel()
  58. f2.cancel()
  59. for future in [f1, f2]:
  60. assert not future.running() and future.done() and future.cancelled()
  61. assert future.set_running_or_notify_cancel() is False
  62. f1, f2 = hivemind.MPFuture.make_pair()
  63. f1.cancel()
  64. for future in [f1, f2]:
  65. assert future.set_running_or_notify_cancel() is False
  66. @pytest.mark.asyncio
  67. async def test_await_mpfuture():
  68. # await result
  69. f1, f2 = hivemind.MPFuture.make_pair()
  70. async def wait_and_assign():
  71. assert f2.set_running_or_notify_cancel() is True
  72. await asyncio.sleep(0.1)
  73. f2.set_result((123, 'ololo'))
  74. asyncio.create_task(wait_and_assign())
  75. for future in [f1, f2]:
  76. res = await future
  77. assert res == (123, 'ololo')
  78. # await cancel
  79. f1, f2 = hivemind.MPFuture.make_pair()
  80. async def wait_and_cancel():
  81. await asyncio.sleep(0.1)
  82. f1.cancel()
  83. asyncio.create_task(wait_and_cancel())
  84. for future in [f1, f2]:
  85. with pytest.raises(CancelledError):
  86. await future
  87. # await exception
  88. f1, f2 = hivemind.MPFuture.make_pair()
  89. async def wait_and_raise():
  90. await asyncio.sleep(0.1)
  91. f1.set_exception(SystemError())
  92. asyncio.create_task(wait_and_raise())
  93. for future in [f1, f2]:
  94. with pytest.raises(SystemError):
  95. await future
  96. def test_vector_compression(size=(128, 128, 64), alpha=5e-08):
  97. torch.manual_seed(0)
  98. from hivemind.proto.runtime_pb2 import CompressionType
  99. from hivemind.utils import serialize_torch_tensor, deserialize_torch_tensor
  100. X = torch.randn(*size)
  101. assert torch.allclose(deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.NONE)), X)
  102. error = deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.MEANSTD_LAST_AXIS_FLOAT16))-X
  103. assert error.square().mean() < alpha
  104. error = deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.FLOAT16)) - X
  105. assert error.square().mean() < alpha
  106. @pytest.mark.forked
  107. @pytest.mark.asyncio
  108. async def test_channel_cache():
  109. hivemind.ChannelCache.MAXIMUM_CHANNELS = 3
  110. hivemind.ChannelCache.EVICTION_PERIOD_SECONDS = 0.1
  111. c1 = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=False)
  112. c2 = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=True)
  113. c3 = hivemind.ChannelCache.get_stub('localhost:1338', DHTStub, aio=False)
  114. c3_again = hivemind.ChannelCache.get_stub('localhost:1338', DHTStub, aio=False)
  115. c1_again = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=False)
  116. c4 = hivemind.ChannelCache.get_stub('localhost:1339', DHTStub, aio=True)
  117. c2_anew = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=True)
  118. c1_yetagain = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=False)
  119. await asyncio.sleep(0.2)
  120. c1_anew = hivemind.ChannelCache.get_stub(target='localhost:1337', aio=False, stub_type=DHTStub)
  121. c1_anew_again = hivemind.ChannelCache.get_stub(target='localhost:1337', aio=False, stub_type=DHTStub)
  122. c1_otherstub = hivemind.ChannelCache.get_stub(target='localhost:1337', aio=False, stub_type=ConnectionHandlerStub)
  123. await asyncio.sleep(0.05)
  124. c1_otherstub_again = hivemind.ChannelCache.get_stub(target='localhost:1337', aio=False,
  125. stub_type=ConnectionHandlerStub)
  126. all_channels = [c1, c2, c3, c4, c3_again, c1_again, c2_anew, c1_yetagain, c1_anew, c1_anew_again, c1_otherstub]
  127. assert all(isinstance(c, DHTStub) for c in all_channels[:-1])
  128. assert isinstance(all_channels[-1], ConnectionHandlerStub)
  129. assert 'aio' in repr(c2.rpc_find)
  130. assert 'aio' not in repr(c1.rpc_find)
  131. duplicates = {(c1, c1_again), (c1, c1_yetagain), (c1_again, c1_yetagain), (c3, c3_again),
  132. (c1_anew, c1_anew_again), (c1_otherstub, c1_otherstub_again)}
  133. for i in range(len(all_channels)):
  134. for j in range(i + 1, len(all_channels)):
  135. ci, cj = all_channels[i], all_channels[j]
  136. assert (ci is cj) == ((ci, cj) in duplicates), (i, j)
  137. def test_serialize_tensor():
  138. tensor = torch.randn(512, 12288)
  139. serialized_tensor = hivemind.serialize_torch_tensor(tensor, hivemind.CompressionType.NONE)
  140. for chunk_size in [1024, 64 * 1024, 64 * 1024 + 1, 10 ** 9]:
  141. chunks = list(hivemind.split_for_streaming(serialized_tensor, chunk_size))
  142. assert len(chunks) == (len(serialized_tensor.buffer) - 1) // chunk_size + 1
  143. restored = hivemind.combine_from_streaming(chunks)
  144. assert torch.allclose(hivemind.deserialize_torch_tensor(restored), tensor)
  145. chunk_size = 30 * 1024
  146. serialized_tensor = hivemind.serialize_torch_tensor(tensor, hivemind.CompressionType.FLOAT16)
  147. chunks = list(hivemind.split_for_streaming(serialized_tensor, chunk_size))
  148. assert len(chunks) == (len(serialized_tensor.buffer) - 1) // chunk_size + 1
  149. restored = hivemind.combine_from_streaming(chunks)
  150. assert torch.allclose(hivemind.deserialize_torch_tensor(restored), tensor, rtol=0, atol=1e-2)
  151. tensor = torch.randint(0, 100, (512, 1, 1))
  152. serialized_tensor = hivemind.serialize_torch_tensor(tensor, hivemind.CompressionType.NONE)
  153. chunks = list(hivemind.split_for_streaming(serialized_tensor, chunk_size))
  154. assert len(chunks) == (len(serialized_tensor.buffer) - 1) // chunk_size + 1
  155. restored = hivemind.combine_from_streaming(chunks)
  156. assert torch.allclose(hivemind.deserialize_torch_tensor(restored), tensor)
  157. def test_split_parts():
  158. tensor = torch.randn(910, 512)
  159. serialized_tensor_part = hivemind.utils.serialize_torch_tensor(tensor, allow_inplace=False)
  160. chunks1 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 16384))
  161. assert len(chunks1) == int(np.ceil(tensor.numel() * tensor.element_size() / 16384))
  162. chunks2 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10_000))
  163. assert len(chunks2) == int(np.ceil(tensor.numel() * tensor.element_size() / 10_000))
  164. chunks3 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10 ** 9))
  165. assert len(chunks3) == 1
  166. compressed_tensor_part = hivemind.utils.serialize_torch_tensor(tensor, hivemind.CompressionType.FLOAT16,
  167. allow_inplace=False)
  168. chunks4 = list(hivemind.utils.split_for_streaming(compressed_tensor_part, 16384))
  169. assert len(chunks4) == int(np.ceil(tensor.numel() * 2 / 16384))
  170. combined1 = hivemind.utils.combine_from_streaming(chunks1)
  171. combined2 = hivemind.utils.combine_from_streaming(iter(chunks2))
  172. combined3 = hivemind.utils.combine_from_streaming(chunks3)
  173. combined4 = hivemind.utils.combine_from_streaming(chunks4)
  174. for combined in combined1, combined2, combined3:
  175. assert torch.allclose(tensor, hivemind.deserialize_torch_tensor(combined), rtol=1e-5, atol=1e-8)
  176. assert torch.allclose(tensor, hivemind.deserialize_torch_tensor(combined4), rtol=1e-3, atol=1e-3)
  177. combined_incomplete = hivemind.utils.combine_from_streaming(chunks4[:5])
  178. combined_incomplete2 = hivemind.utils.combine_from_streaming(chunks4[:1])
  179. combined_incomplete3 = hivemind.utils.combine_from_streaming(chunks4[:-1])
  180. for combined in combined_incomplete, combined_incomplete2, combined_incomplete3:
  181. with pytest.raises(RuntimeError):
  182. hivemind.deserialize_torch_tensor(combined)
  183. # note: we rely on this being RuntimeError in hivemind.client.averager.allreduce.AllreduceProtocol
  184. def test_generic_data_classes():
  185. from hivemind.utils import ValueWithExpiration, HeapEntry, DHTExpiration
  186. value_with_exp = ValueWithExpiration(value="string_value", expiration_time=DHTExpiration(10))
  187. assert value_with_exp.value == "string_value" and value_with_exp.expiration_time == DHTExpiration(10)
  188. heap_entry = HeapEntry(expiration_time=DHTExpiration(10), key="string_value")
  189. assert heap_entry.key == "string_value" and heap_entry.expiration_time == DHTExpiration(10)
  190. sorted_expirations = sorted([DHTExpiration(value) for value in range(1, 1000)])
  191. sorted_heap_entry = sorted([HeapEntry(expiration_time=DHTExpiration(value), key="any") for value in range(1, 1000)[::-1]])
  192. assert all([heap_entry.expiration_time == value for heap_entry, value in zip(sorted_heap_entry, sorted_expirations)])