test_util_modules.py 11 KB

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