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