test_util_modules.py 18 KB

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