test_util_modules.py 19 KB

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