test_util_modules.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. import asyncio
  2. import concurrent.futures
  3. import multiprocessing as mp
  4. import random
  5. import time
  6. import numpy as np
  7. import pytest
  8. import torch
  9. import hivemind
  10. from hivemind.compression import deserialize_torch_tensor, serialize_torch_tensor
  11. from hivemind.proto.dht_pb2_grpc import DHTStub
  12. from hivemind.proto.runtime_pb2 import CompressionType
  13. from hivemind.proto.runtime_pb2_grpc import ConnectionHandlerStub
  14. from hivemind.utils import DHTExpiration, HeapEntry, MSGPackSerializer, ValueWithExpiration
  15. from hivemind.utils.asyncio import (
  16. achain,
  17. aenumerate,
  18. afirst,
  19. aiter_with_timeout,
  20. amap_in_executor,
  21. anext,
  22. as_aiter,
  23. asingle,
  24. azip,
  25. cancel_and_wait,
  26. )
  27. from hivemind.utils.mpfuture import InvalidStateError
  28. @pytest.mark.forked
  29. def test_mpfuture_result():
  30. future = hivemind.MPFuture()
  31. def _proc(future):
  32. with pytest.raises(RuntimeError):
  33. future.result() # only creator process can await result
  34. future.set_result(321)
  35. p = mp.Process(target=_proc, args=(future,))
  36. p.start()
  37. p.join()
  38. assert future.result() == 321
  39. assert future.exception() is None
  40. assert future.cancel() is False
  41. assert future.done() and not future.running() and not future.cancelled()
  42. future = hivemind.MPFuture()
  43. with pytest.raises(concurrent.futures.TimeoutError):
  44. future.result(timeout=1e-3)
  45. future.set_result(["abacaba", 123])
  46. assert future.result() == ["abacaba", 123]
  47. @pytest.mark.forked
  48. def test_mpfuture_exception():
  49. future = hivemind.MPFuture()
  50. with pytest.raises(concurrent.futures.TimeoutError):
  51. future.exception(timeout=1e-3)
  52. def _proc(future):
  53. future.set_exception(NotImplementedError())
  54. p = mp.Process(target=_proc, args=(future,))
  55. p.start()
  56. p.join()
  57. assert isinstance(future.exception(), NotImplementedError)
  58. with pytest.raises(NotImplementedError):
  59. future.result()
  60. assert future.cancel() is False
  61. assert future.done() and not future.running() and not future.cancelled()
  62. @pytest.mark.forked
  63. def test_mpfuture_cancel():
  64. future = hivemind.MPFuture()
  65. assert not future.cancelled()
  66. future.cancel()
  67. evt = mp.Event()
  68. def _proc():
  69. with pytest.raises(concurrent.futures.CancelledError):
  70. future.result()
  71. with pytest.raises(concurrent.futures.CancelledError):
  72. future.exception()
  73. with pytest.raises(InvalidStateError):
  74. future.set_result(123)
  75. with pytest.raises(InvalidStateError):
  76. future.set_exception(NotImplementedError())
  77. assert future.cancelled() and future.done() and not future.running()
  78. evt.set()
  79. p = mp.Process(target=_proc)
  80. p.start()
  81. p.join()
  82. assert evt.is_set()
  83. @pytest.mark.forked
  84. def test_mpfuture_status():
  85. evt = mp.Event()
  86. future = hivemind.MPFuture()
  87. def _proc1(future):
  88. assert future.set_running_or_notify_cancel() is True
  89. evt.set()
  90. p = mp.Process(target=_proc1, args=(future,))
  91. p.start()
  92. p.join()
  93. assert evt.is_set()
  94. evt.clear()
  95. assert future.running() and not future.done() and not future.cancelled()
  96. with pytest.raises(InvalidStateError):
  97. future.set_running_or_notify_cancel()
  98. future = hivemind.MPFuture()
  99. assert future.cancel()
  100. def _proc2(future):
  101. assert not future.running() and future.done() and future.cancelled()
  102. assert future.set_running_or_notify_cancel() is False
  103. evt.set()
  104. p = mp.Process(target=_proc2, args=(future,))
  105. p.start()
  106. p.join()
  107. evt.set()
  108. future2 = hivemind.MPFuture()
  109. future2.cancel()
  110. assert future2.set_running_or_notify_cancel() is False
  111. @pytest.mark.asyncio
  112. async def test_await_mpfuture():
  113. # await result from the same process, but a different coroutine
  114. f1, f2 = hivemind.MPFuture(), hivemind.MPFuture()
  115. async def wait_and_assign_async():
  116. assert f2.set_running_or_notify_cancel() is True
  117. await asyncio.sleep(0.1)
  118. f1.set_result((123, "ololo"))
  119. f2.set_result((456, "pyshpysh"))
  120. asyncio.create_task(wait_and_assign_async())
  121. assert (await asyncio.gather(f1, f2)) == [(123, "ololo"), (456, "pyshpysh")]
  122. # await result from separate processes
  123. f1, f2 = hivemind.MPFuture(), hivemind.MPFuture()
  124. def wait_and_assign(future, value):
  125. time.sleep(0.1 * random.random())
  126. future.set_result(value)
  127. p1 = mp.Process(target=wait_and_assign, args=(f1, "abc"))
  128. p2 = mp.Process(target=wait_and_assign, args=(f2, "def"))
  129. for p in p1, p2:
  130. p.start()
  131. assert (await asyncio.gather(f1, f2)) == ["abc", "def"]
  132. for p in p1, p2:
  133. p.join()
  134. # await cancel
  135. f1, f2 = hivemind.MPFuture(), hivemind.MPFuture()
  136. def wait_and_cancel():
  137. time.sleep(0.01)
  138. f2.set_result(123456)
  139. time.sleep(0.1)
  140. f1.cancel()
  141. p = mp.Process(target=wait_and_cancel)
  142. p.start()
  143. with pytest.raises(asyncio.CancelledError):
  144. # note: it is intended that MPFuture raises Cancel
  145. await asyncio.gather(f1, f2)
  146. p.join()
  147. # await exception
  148. f1, f2 = hivemind.MPFuture(), hivemind.MPFuture()
  149. def wait_and_raise():
  150. time.sleep(0.01)
  151. f2.set_result(123456)
  152. time.sleep(0.1)
  153. f1.set_exception(ValueError("we messed up"))
  154. p = mp.Process(target=wait_and_raise)
  155. p.start()
  156. with pytest.raises(ValueError):
  157. # note: it is intended that MPFuture raises Cancel
  158. await asyncio.gather(f1, f2)
  159. p.join()
  160. @pytest.mark.forked
  161. def test_mpfuture_bidirectional():
  162. evt = mp.Event()
  163. future_from_main = hivemind.MPFuture()
  164. def _future_creator():
  165. future_from_fork = hivemind.MPFuture()
  166. future_from_main.set_result(("abc", future_from_fork))
  167. if future_from_fork.result() == ["we", "need", "to", "go", "deeper"]:
  168. evt.set()
  169. p = mp.Process(target=_future_creator)
  170. p.start()
  171. out = future_from_main.result()
  172. assert isinstance(out[1], hivemind.MPFuture)
  173. out[1].set_result(["we", "need", "to", "go", "deeper"])
  174. p.join()
  175. assert evt.is_set()
  176. @pytest.mark.forked
  177. def test_mpfuture_done_callback():
  178. receiver, sender = mp.Pipe(duplex=False)
  179. events = [mp.Event() for _ in range(6)]
  180. def _future_creator():
  181. future1, future2, future3 = hivemind.MPFuture(), hivemind.MPFuture(), hivemind.MPFuture()
  182. def _check_result_and_set(future):
  183. assert future.done()
  184. assert future.result() == 123
  185. events[0].set()
  186. future1.add_done_callback(_check_result_and_set)
  187. future1.add_done_callback(lambda future: events[1].set())
  188. future2.add_done_callback(lambda future: events[2].set())
  189. future3.add_done_callback(lambda future: events[3].set())
  190. sender.send((future1, future2))
  191. future2.cancel() # trigger future2 callback from the same process
  192. events[0].wait()
  193. future1.add_done_callback(
  194. lambda future: events[4].set()
  195. ) # schedule callback after future1 is already finished
  196. events[5].wait()
  197. p = mp.Process(target=_future_creator)
  198. p.start()
  199. future1, future2 = receiver.recv()
  200. future1.set_result(123)
  201. with pytest.raises(RuntimeError):
  202. future1.add_done_callback(lambda future: (1, 2, 3))
  203. assert future1.done() and not future1.cancelled()
  204. assert future2.done() and future2.cancelled()
  205. for i in 0, 1, 4:
  206. events[i].wait(1)
  207. assert events[0].is_set() and events[1].is_set() and events[2].is_set() and events[4].is_set()
  208. assert not events[3].is_set()
  209. events[5].set()
  210. p.join()
  211. @pytest.mark.forked
  212. def test_many_futures():
  213. evt = mp.Event()
  214. receiver, sender = mp.Pipe()
  215. main_futures = [hivemind.MPFuture() for _ in range(1000)]
  216. assert len(hivemind.MPFuture._active_futures) == 1000
  217. def _run_peer():
  218. fork_futures = [hivemind.MPFuture() for _ in range(500)]
  219. assert len(hivemind.MPFuture._active_futures) == 500
  220. for i, future in enumerate(random.sample(main_futures, 300)):
  221. if random.random() < 0.5:
  222. future.set_result(i)
  223. else:
  224. future.set_exception(ValueError(f"{i}"))
  225. sender.send(fork_futures[:-100])
  226. for future in fork_futures[-100:]:
  227. future.cancel()
  228. evt.wait()
  229. assert len(hivemind.MPFuture._active_futures) == 200
  230. for future in fork_futures:
  231. if not future.done():
  232. future.set_result(123)
  233. assert len(hivemind.MPFuture._active_futures) == 0
  234. p = mp.Process(target=_run_peer)
  235. p.start()
  236. some_fork_futures = receiver.recv()
  237. assert len(hivemind.MPFuture._active_futures) == 700
  238. for future in some_fork_futures:
  239. future.set_running_or_notify_cancel()
  240. for future in random.sample(some_fork_futures, 200):
  241. future.set_result(321)
  242. evt.set()
  243. for future in main_futures:
  244. future.cancel()
  245. assert len(hivemind.MPFuture._active_futures) == 0
  246. p.join()
  247. @pytest.mark.forked
  248. @pytest.mark.asyncio
  249. async def test_channel_cache():
  250. hivemind.ChannelCache.MAXIMUM_CHANNELS = 3
  251. hivemind.ChannelCache.EVICTION_PERIOD_SECONDS = 0.1
  252. c1 = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=False)
  253. c2 = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=True)
  254. c3 = hivemind.ChannelCache.get_stub("localhost:1338", DHTStub, aio=False)
  255. c3_again = hivemind.ChannelCache.get_stub("localhost:1338", DHTStub, aio=False)
  256. c1_again = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=False)
  257. c4 = hivemind.ChannelCache.get_stub("localhost:1339", DHTStub, aio=True)
  258. c2_anew = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=True)
  259. c1_yetagain = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=False)
  260. await asyncio.sleep(0.2)
  261. c1_anew = hivemind.ChannelCache.get_stub(target="localhost:1337", aio=False, stub_type=DHTStub)
  262. c1_anew_again = hivemind.ChannelCache.get_stub(target="localhost:1337", aio=False, stub_type=DHTStub)
  263. c1_otherstub = hivemind.ChannelCache.get_stub(target="localhost:1337", aio=False, stub_type=ConnectionHandlerStub)
  264. await asyncio.sleep(0.05)
  265. c1_otherstub_again = hivemind.ChannelCache.get_stub(
  266. target="localhost:1337", aio=False, stub_type=ConnectionHandlerStub
  267. )
  268. all_channels = [c1, c2, c3, c4, c3_again, c1_again, c2_anew, c1_yetagain, c1_anew, c1_anew_again, c1_otherstub]
  269. assert all(isinstance(c, DHTStub) for c in all_channels[:-1])
  270. assert isinstance(all_channels[-1], ConnectionHandlerStub)
  271. assert "aio" in repr(c2.rpc_find)
  272. assert "aio" not in repr(c1.rpc_find)
  273. duplicates = {
  274. (c1, c1_again),
  275. (c1, c1_yetagain),
  276. (c1_again, c1_yetagain),
  277. (c3, c3_again),
  278. (c1_anew, c1_anew_again),
  279. (c1_otherstub, c1_otherstub_again),
  280. }
  281. for i in range(len(all_channels)):
  282. for j in range(i + 1, len(all_channels)):
  283. ci, cj = all_channels[i], all_channels[j]
  284. assert (ci is cj) == ((ci, cj) in duplicates), (i, j)
  285. def test_serialize_tuple():
  286. test_pairs = (
  287. ((1, 2, 3), [1, 2, 3]),
  288. (("1", False, 0), ["1", False, 0]),
  289. (("1", False, 0), ("1", 0, 0)),
  290. (("1", b"qq", (2, 5, "0")), ["1", b"qq", (2, 5, "0")]),
  291. )
  292. for first, second in test_pairs:
  293. assert MSGPackSerializer.loads(MSGPackSerializer.dumps(first)) == first
  294. assert MSGPackSerializer.loads(MSGPackSerializer.dumps(second)) == second
  295. assert MSGPackSerializer.dumps(first) != MSGPackSerializer.dumps(second)
  296. def test_split_parts():
  297. tensor = torch.randn(910, 512)
  298. serialized_tensor_part = serialize_torch_tensor(tensor, allow_inplace=False)
  299. chunks1 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 16384))
  300. assert len(chunks1) == int(np.ceil(tensor.numel() * tensor.element_size() / 16384))
  301. chunks2 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10_000))
  302. assert len(chunks2) == int(np.ceil(tensor.numel() * tensor.element_size() / 10_000))
  303. chunks3 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10 ** 9))
  304. assert len(chunks3) == 1
  305. compressed_tensor_part = serialize_torch_tensor(tensor, CompressionType.FLOAT16, allow_inplace=False)
  306. chunks4 = list(hivemind.utils.split_for_streaming(compressed_tensor_part, 16384))
  307. assert len(chunks4) == int(np.ceil(tensor.numel() * 2 / 16384))
  308. combined1 = hivemind.utils.combine_from_streaming(chunks1)
  309. combined2 = hivemind.utils.combine_from_streaming(iter(chunks2))
  310. combined3 = hivemind.utils.combine_from_streaming(chunks3)
  311. combined4 = hivemind.utils.combine_from_streaming(chunks4)
  312. for combined in combined1, combined2, combined3:
  313. assert torch.allclose(tensor, deserialize_torch_tensor(combined), rtol=1e-5, atol=1e-8)
  314. assert torch.allclose(tensor, deserialize_torch_tensor(combined4), rtol=1e-3, atol=1e-3)
  315. combined_incomplete = hivemind.utils.combine_from_streaming(chunks4[:5])
  316. combined_incomplete2 = hivemind.utils.combine_from_streaming(chunks4[:1])
  317. combined_incomplete3 = hivemind.utils.combine_from_streaming(chunks4[:-1])
  318. for combined in combined_incomplete, combined_incomplete2, combined_incomplete3:
  319. with pytest.raises(RuntimeError):
  320. deserialize_torch_tensor(combined)
  321. # note: we rely on this being RuntimeError in hivemind.averaging.allreduce.AllreduceRunner
  322. def test_generic_data_classes():
  323. value_with_exp = ValueWithExpiration(value="string_value", expiration_time=DHTExpiration(10))
  324. assert value_with_exp.value == "string_value" and value_with_exp.expiration_time == DHTExpiration(10)
  325. heap_entry = HeapEntry(expiration_time=DHTExpiration(10), key="string_value")
  326. assert heap_entry.key == "string_value" and heap_entry.expiration_time == DHTExpiration(10)
  327. sorted_expirations = sorted([DHTExpiration(value) for value in range(1, 1000)])
  328. sorted_heap_entries = sorted([HeapEntry(DHTExpiration(value), key="any") for value in range(1, 1000)[::-1]])
  329. assert all([entry.expiration_time == value for entry, value in zip(sorted_heap_entries, sorted_expirations)])
  330. @pytest.mark.asyncio
  331. async def test_asyncio_utils():
  332. res = [i async for i, item in aenumerate(as_aiter("a", "b", "c"))]
  333. assert res == list(range(len(res)))
  334. num_steps = 0
  335. async for elem in amap_in_executor(lambda x: x ** 2, as_aiter(*range(100)), max_prefetch=5):
  336. assert elem == num_steps ** 2
  337. num_steps += 1
  338. assert num_steps == 100
  339. ours = [
  340. elem
  341. async for elem in amap_in_executor(max, as_aiter(*range(7)), as_aiter(*range(-50, 50, 10)), max_prefetch=1)
  342. ]
  343. ref = list(map(max, range(7), range(-50, 50, 10)))
  344. assert ours == ref
  345. ours = [row async for row in azip(as_aiter("a", "b", "c"), as_aiter(1, 2, 3))]
  346. ref = list(zip(["a", "b", "c"], [1, 2, 3]))
  347. assert ours == ref
  348. async def _aiterate():
  349. yield "foo"
  350. yield "bar"
  351. yield "baz"
  352. iterator = _aiterate()
  353. assert (await anext(iterator)) == "foo"
  354. tail = [item async for item in iterator]
  355. assert tail == ["bar", "baz"]
  356. with pytest.raises(StopAsyncIteration):
  357. await anext(iterator)
  358. assert [item async for item in achain(_aiterate(), as_aiter(*range(5)))] == ["foo", "bar", "baz"] + list(range(5))
  359. assert await asingle(as_aiter(1)) == 1
  360. with pytest.raises(ValueError):
  361. await asingle(as_aiter())
  362. with pytest.raises(ValueError):
  363. await asingle(as_aiter(1, 2, 3))
  364. assert await afirst(as_aiter(1)) == 1
  365. assert await afirst(as_aiter()) is None
  366. assert await afirst(as_aiter(), -1) == -1
  367. assert await afirst(as_aiter(1, 2, 3)) == 1
  368. async def iterate_with_delays(delays):
  369. for i, delay in enumerate(delays):
  370. await asyncio.sleep(delay)
  371. yield i
  372. async for _ in aiter_with_timeout(iterate_with_delays([0.1] * 5), timeout=0.2):
  373. pass
  374. sleepy_aiter = iterate_with_delays([0.1, 0.1, 0.3, 0.1, 0.1])
  375. num_steps = 0
  376. with pytest.raises(asyncio.TimeoutError):
  377. async for _ in aiter_with_timeout(sleepy_aiter, timeout=0.2):
  378. num_steps += 1
  379. assert num_steps == 2
  380. @pytest.mark.asyncio
  381. async def test_cancel_and_wait():
  382. finished_gracefully = False
  383. async def coro_with_finalizer():
  384. nonlocal finished_gracefully
  385. try:
  386. await asyncio.Event().wait()
  387. except asyncio.CancelledError:
  388. await asyncio.sleep(0.05)
  389. finished_gracefully = True
  390. raise
  391. task = asyncio.create_task(coro_with_finalizer())
  392. await asyncio.sleep(0.05)
  393. assert await cancel_and_wait(task)
  394. assert finished_gracefully
  395. async def coro_with_result():
  396. return 777
  397. async def coro_with_error():
  398. raise ValueError("error")
  399. task_with_result = asyncio.create_task(coro_with_result())
  400. task_with_error = asyncio.create_task(coro_with_error())
  401. await asyncio.sleep(0.05)
  402. assert not await cancel_and_wait(task_with_result)
  403. assert not await cancel_and_wait(task_with_error)