test_util_modules.py 12 KB

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