test_util_modules.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. error = deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.UNIFORM_8BIT)) - X
  111. assert error.square().mean() < beta
  112. @pytest.mark.forked
  113. @pytest.mark.asyncio
  114. async def test_channel_cache():
  115. hivemind.ChannelCache.MAXIMUM_CHANNELS = 3
  116. hivemind.ChannelCache.EVICTION_PERIOD_SECONDS = 0.1
  117. c1 = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=False)
  118. c2 = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=True)
  119. c3 = hivemind.ChannelCache.get_stub('localhost:1338', DHTStub, aio=False)
  120. c3_again = hivemind.ChannelCache.get_stub('localhost:1338', DHTStub, aio=False)
  121. c1_again = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=False)
  122. c4 = hivemind.ChannelCache.get_stub('localhost:1339', DHTStub, aio=True)
  123. c2_anew = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=True)
  124. c1_yetagain = hivemind.ChannelCache.get_stub('localhost:1337', DHTStub, aio=False)
  125. await asyncio.sleep(0.2)
  126. c1_anew = hivemind.ChannelCache.get_stub(target='localhost:1337', aio=False, stub_type=DHTStub)
  127. c1_anew_again = hivemind.ChannelCache.get_stub(target='localhost:1337', aio=False, stub_type=DHTStub)
  128. c1_otherstub = hivemind.ChannelCache.get_stub(target='localhost:1337', aio=False, stub_type=ConnectionHandlerStub)
  129. await asyncio.sleep(0.05)
  130. c1_otherstub_again = hivemind.ChannelCache.get_stub(target='localhost:1337', aio=False,
  131. stub_type=ConnectionHandlerStub)
  132. all_channels = [c1, c2, c3, c4, c3_again, c1_again, c2_anew, c1_yetagain, c1_anew, c1_anew_again, c1_otherstub]
  133. assert all(isinstance(c, DHTStub) for c in all_channels[:-1])
  134. assert isinstance(all_channels[-1], ConnectionHandlerStub)
  135. assert 'aio' in repr(c2.rpc_find)
  136. assert 'aio' not in repr(c1.rpc_find)
  137. duplicates = {(c1, c1_again), (c1, c1_yetagain), (c1_again, c1_yetagain), (c3, c3_again),
  138. (c1_anew, c1_anew_again), (c1_otherstub, c1_otherstub_again)}
  139. for i in range(len(all_channels)):
  140. for j in range(i + 1, len(all_channels)):
  141. ci, cj = all_channels[i], all_channels[j]
  142. assert (ci is cj) == ((ci, cj) in duplicates), (i, j)
  143. def test_serialize_tensor():
  144. tensor = torch.randn(512, 12288)
  145. serialized_tensor = serialize_torch_tensor(tensor, CompressionType.NONE)
  146. for chunk_size in [1024, 64 * 1024, 64 * 1024 + 1, 10 ** 9]:
  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(deserialize_torch_tensor(restored), tensor)
  151. chunk_size = 30 * 1024
  152. serialized_tensor = serialize_torch_tensor(tensor, CompressionType.FLOAT16)
  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(deserialize_torch_tensor(restored), tensor, rtol=0, atol=1e-2)
  157. tensor = torch.randint(0, 100, (512, 1, 1))
  158. serialized_tensor = serialize_torch_tensor(tensor, CompressionType.NONE)
  159. chunks = list(hivemind.split_for_streaming(serialized_tensor, chunk_size))
  160. assert len(chunks) == (len(serialized_tensor.buffer) - 1) // chunk_size + 1
  161. restored = hivemind.combine_from_streaming(chunks)
  162. assert torch.allclose(deserialize_torch_tensor(restored), tensor)
  163. scalar = torch.tensor(1.)
  164. serialized_scalar = serialize_torch_tensor(scalar, CompressionType.NONE)
  165. assert torch.allclose(deserialize_torch_tensor(serialized_scalar), scalar)
  166. serialized_scalar = serialize_torch_tensor(scalar, CompressionType.FLOAT16)
  167. assert torch.allclose(deserialize_torch_tensor(serialized_scalar), scalar)
  168. def test_serialize_tuple():
  169. test_pairs = (
  170. ((1, 2, 3), [1, 2, 3]),
  171. (('1', False, 0), ['1', False, 0]),
  172. (('1', False, 0), ('1', 0, 0)),
  173. (('1', b'qq', (2, 5, '0')), ['1', b'qq', (2, 5, '0')]),
  174. )
  175. for first, second in test_pairs:
  176. assert MSGPackSerializer.loads(MSGPackSerializer.dumps(first)) == first
  177. assert MSGPackSerializer.loads(MSGPackSerializer.dumps(second)) == second
  178. assert MSGPackSerializer.dumps(first) != MSGPackSerializer.dumps(second)
  179. def test_split_parts():
  180. tensor = torch.randn(910, 512)
  181. serialized_tensor_part = serialize_torch_tensor(tensor, allow_inplace=False)
  182. chunks1 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 16384))
  183. assert len(chunks1) == int(np.ceil(tensor.numel() * tensor.element_size() / 16384))
  184. chunks2 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10_000))
  185. assert len(chunks2) == int(np.ceil(tensor.numel() * tensor.element_size() / 10_000))
  186. chunks3 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10 ** 9))
  187. assert len(chunks3) == 1
  188. compressed_tensor_part = serialize_torch_tensor(tensor, CompressionType.FLOAT16, allow_inplace=False)
  189. chunks4 = list(hivemind.utils.split_for_streaming(compressed_tensor_part, 16384))
  190. assert len(chunks4) == int(np.ceil(tensor.numel() * 2 / 16384))
  191. combined1 = hivemind.utils.combine_from_streaming(chunks1)
  192. combined2 = hivemind.utils.combine_from_streaming(iter(chunks2))
  193. combined3 = hivemind.utils.combine_from_streaming(chunks3)
  194. combined4 = hivemind.utils.combine_from_streaming(chunks4)
  195. for combined in combined1, combined2, combined3:
  196. assert torch.allclose(tensor, deserialize_torch_tensor(combined), rtol=1e-5, atol=1e-8)
  197. assert torch.allclose(tensor, deserialize_torch_tensor(combined4), rtol=1e-3, atol=1e-3)
  198. combined_incomplete = hivemind.utils.combine_from_streaming(chunks4[:5])
  199. combined_incomplete2 = hivemind.utils.combine_from_streaming(chunks4[:1])
  200. combined_incomplete3 = hivemind.utils.combine_from_streaming(chunks4[:-1])
  201. for combined in combined_incomplete, combined_incomplete2, combined_incomplete3:
  202. with pytest.raises(RuntimeError):
  203. deserialize_torch_tensor(combined)
  204. # note: we rely on this being RuntimeError in hivemind.client.averager.allreduce.AllreduceProtocol
  205. def test_generic_data_classes():
  206. from hivemind.utils import ValueWithExpiration, HeapEntry, DHTExpiration
  207. value_with_exp = ValueWithExpiration(value="string_value", expiration_time=DHTExpiration(10))
  208. assert value_with_exp.value == "string_value" and value_with_exp.expiration_time == DHTExpiration(10)
  209. heap_entry = HeapEntry(expiration_time=DHTExpiration(10), key="string_value")
  210. assert heap_entry.key == "string_value" and heap_entry.expiration_time == DHTExpiration(10)
  211. sorted_expirations = sorted([DHTExpiration(value) for value in range(1, 1000)])
  212. sorted_heap_entries = sorted([HeapEntry(DHTExpiration(value), key="any") for value in range(1, 1000)[::-1]])
  213. assert all([entry.expiration_time == value for entry, value in zip(sorted_heap_entries, sorted_expirations)])