test_util_modules.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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.proto.runtime_pb2 import CompressionType
  13. from hivemind.utils import BatchTensorDescriptor, DHTExpiration, HeapEntry, MSGPackSerializer, ValueWithExpiration
  14. from hivemind.utils.asyncio import (
  15. achain,
  16. aenumerate,
  17. aiter_with_timeout,
  18. amap_in_executor,
  19. anext,
  20. as_aiter,
  21. asingle,
  22. attach_event_on_finished,
  23. azip,
  24. cancel_and_wait,
  25. enter_asynchronously,
  26. )
  27. from hivemind.utils.mpfuture import InvalidStateError
  28. from hivemind.utils.performance_ema import PerformanceEMA
  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. time.sleep(0.1) # giving enough time for the futures to be destroyed
  239. assert len(hivemind.MPFuture._active_futures) == 700
  240. for future in some_fork_futures:
  241. future.set_running_or_notify_cancel()
  242. for future in random.sample(some_fork_futures, 200):
  243. future.set_result(321)
  244. evt.set()
  245. for future in main_futures:
  246. future.cancel()
  247. time.sleep(0.1) # giving enough time for the futures to be destroyed
  248. assert len(hivemind.MPFuture._active_futures) == 0
  249. p.join()
  250. def test_serialize_tuple():
  251. test_pairs = (
  252. ((1, 2, 3), [1, 2, 3]),
  253. (("1", False, 0), ["1", False, 0]),
  254. (("1", False, 0), ("1", 0, 0)),
  255. (("1", b"qq", (2, 5, "0")), ["1", b"qq", (2, 5, "0")]),
  256. )
  257. for first, second in test_pairs:
  258. assert MSGPackSerializer.loads(MSGPackSerializer.dumps(first)) == first
  259. assert MSGPackSerializer.loads(MSGPackSerializer.dumps(second)) == second
  260. assert MSGPackSerializer.dumps(first) != MSGPackSerializer.dumps(second)
  261. def test_split_parts():
  262. tensor = torch.randn(910, 512)
  263. serialized_tensor_part = serialize_torch_tensor(tensor, allow_inplace=False)
  264. chunks1 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 16384))
  265. assert len(chunks1) == int(np.ceil(tensor.numel() * tensor.element_size() / 16384))
  266. chunks2 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10_000))
  267. assert len(chunks2) == int(np.ceil(tensor.numel() * tensor.element_size() / 10_000))
  268. chunks3 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10**9))
  269. assert len(chunks3) == 1
  270. compressed_tensor_part = serialize_torch_tensor(tensor, CompressionType.FLOAT16, allow_inplace=False)
  271. chunks4 = list(hivemind.utils.split_for_streaming(compressed_tensor_part, 16384))
  272. assert len(chunks4) == int(np.ceil(tensor.numel() * 2 / 16384))
  273. combined1 = hivemind.utils.combine_from_streaming(chunks1)
  274. combined2 = hivemind.utils.combine_from_streaming(iter(chunks2))
  275. combined3 = hivemind.utils.combine_from_streaming(chunks3)
  276. combined4 = hivemind.utils.combine_from_streaming(chunks4)
  277. for combined in combined1, combined2, combined3:
  278. assert torch.allclose(tensor, deserialize_torch_tensor(combined), rtol=1e-5, atol=1e-8)
  279. assert torch.allclose(tensor, deserialize_torch_tensor(combined4), rtol=1e-3, atol=1e-3)
  280. combined_incomplete = hivemind.utils.combine_from_streaming(chunks4[:5])
  281. combined_incomplete2 = hivemind.utils.combine_from_streaming(chunks4[:1])
  282. combined_incomplete3 = hivemind.utils.combine_from_streaming(chunks4[:-1])
  283. for combined in combined_incomplete, combined_incomplete2, combined_incomplete3:
  284. with pytest.raises(RuntimeError):
  285. deserialize_torch_tensor(combined)
  286. # note: we rely on this being RuntimeError in hivemind.averaging.allreduce.AllReduceRunner
  287. def test_generic_data_classes():
  288. value_with_exp = ValueWithExpiration(value="string_value", expiration_time=DHTExpiration(10))
  289. assert value_with_exp.value == "string_value" and value_with_exp.expiration_time == DHTExpiration(10)
  290. heap_entry = HeapEntry(expiration_time=DHTExpiration(10), key="string_value")
  291. assert heap_entry.key == "string_value" and heap_entry.expiration_time == DHTExpiration(10)
  292. sorted_expirations = sorted([DHTExpiration(value) for value in range(1, 1000)])
  293. sorted_heap_entries = sorted([HeapEntry(DHTExpiration(value), key="any") for value in range(1, 1000)[::-1]])
  294. assert all([entry.expiration_time == value for entry, value in zip(sorted_heap_entries, sorted_expirations)])
  295. @pytest.mark.asyncio
  296. async def test_asyncio_utils():
  297. res = [i async for i, item in aenumerate(as_aiter("a", "b", "c"))]
  298. assert res == list(range(len(res)))
  299. num_steps = 0
  300. async for elem in amap_in_executor(lambda x: x**2, as_aiter(*range(100)), max_prefetch=5):
  301. assert elem == num_steps**2
  302. num_steps += 1
  303. assert num_steps == 100
  304. ours = [
  305. elem
  306. async for elem in amap_in_executor(max, as_aiter(*range(7)), as_aiter(*range(-50, 50, 10)), max_prefetch=1)
  307. ]
  308. ref = list(map(max, range(7), range(-50, 50, 10)))
  309. assert ours == ref
  310. ours = [row async for row in azip(as_aiter("a", "b", "c"), as_aiter(1, 2, 3))]
  311. ref = list(zip(["a", "b", "c"], [1, 2, 3]))
  312. assert ours == ref
  313. async def _aiterate():
  314. yield "foo"
  315. yield "bar"
  316. yield "baz"
  317. iterator = _aiterate()
  318. assert (await anext(iterator)) == "foo"
  319. tail = [item async for item in iterator]
  320. assert tail == ["bar", "baz"]
  321. with pytest.raises(StopAsyncIteration):
  322. await anext(iterator)
  323. assert [item async for item in achain(_aiterate(), as_aiter(*range(5)))] == ["foo", "bar", "baz"] + list(range(5))
  324. assert await asingle(as_aiter(1)) == 1
  325. with pytest.raises(ValueError):
  326. await asingle(as_aiter())
  327. with pytest.raises(ValueError):
  328. await asingle(as_aiter(1, 2, 3))
  329. async def iterate_with_delays(delays):
  330. for i, delay in enumerate(delays):
  331. await asyncio.sleep(delay)
  332. yield i
  333. async for _ in aiter_with_timeout(iterate_with_delays([0.1] * 5), timeout=0.2):
  334. pass
  335. sleepy_aiter = iterate_with_delays([0.1, 0.1, 0.3, 0.1, 0.1])
  336. num_steps = 0
  337. with pytest.raises(asyncio.TimeoutError):
  338. async for _ in aiter_with_timeout(sleepy_aiter, timeout=0.2):
  339. num_steps += 1
  340. assert num_steps == 2
  341. event = asyncio.Event()
  342. async for i in attach_event_on_finished(iterate_with_delays([0, 0, 0, 0, 0]), event):
  343. assert not event.is_set()
  344. assert event.is_set()
  345. event = asyncio.Event()
  346. sleepy_aiter = iterate_with_delays([0.1, 0.1, 0.3, 0.1, 0.1])
  347. with pytest.raises(asyncio.TimeoutError):
  348. async for _ in attach_event_on_finished(aiter_with_timeout(sleepy_aiter, timeout=0.2), event):
  349. assert not event.is_set()
  350. assert event.is_set()
  351. @pytest.mark.asyncio
  352. async def test_cancel_and_wait():
  353. finished_gracefully = False
  354. async def coro_with_finalizer():
  355. nonlocal finished_gracefully
  356. try:
  357. await asyncio.Event().wait()
  358. except asyncio.CancelledError:
  359. await asyncio.sleep(0.05)
  360. finished_gracefully = True
  361. raise
  362. task = asyncio.create_task(coro_with_finalizer())
  363. await asyncio.sleep(0.05)
  364. assert await cancel_and_wait(task)
  365. assert finished_gracefully
  366. async def coro_with_result():
  367. return 777
  368. async def coro_with_error():
  369. raise ValueError("error")
  370. task_with_result = asyncio.create_task(coro_with_result())
  371. task_with_error = asyncio.create_task(coro_with_error())
  372. await asyncio.sleep(0.05)
  373. assert not await cancel_and_wait(task_with_result)
  374. assert not await cancel_and_wait(task_with_error)
  375. @pytest.mark.asyncio
  376. async def test_async_context():
  377. lock = mp.Lock()
  378. async def coro1():
  379. async with enter_asynchronously(lock):
  380. await asyncio.sleep(0.2)
  381. async def coro2():
  382. await asyncio.sleep(0.1)
  383. async with enter_asynchronously(lock):
  384. await asyncio.sleep(0.1)
  385. await asyncio.wait_for(asyncio.gather(coro1(), coro2()), timeout=0.5)
  386. # running this without enter_asynchronously would deadlock the event loop
  387. @pytest.mark.asyncio
  388. async def test_async_context_flooding():
  389. """
  390. test for a possible deadlock when many coroutines await the lock and overwhelm the underlying ThreadPoolExecutor
  391. Here's how the test below works: suppose that the thread pool has at most N workers;
  392. If at least N + 1 coroutines await lock1 concurrently, N of them occupy workers and the rest are awaiting workers;
  393. When the first of N workers acquires lock1, it lets coroutine A inside lock1 and into await sleep(1e-2);
  394. During that sleep, one of the worker-less coroutines will take up the worker freed by coroutine A.
  395. Finally, coroutine A finishes sleeping and immediately gets stuck at lock2, because there are no free workers.
  396. Thus, every single coroutine is either awaiting an already acquired lock, or awaiting for free workers in executor.
  397. """
  398. lock1, lock2 = mp.Lock(), mp.Lock()
  399. async def coro():
  400. async with enter_asynchronously(lock1):
  401. await asyncio.sleep(1e-2)
  402. async with enter_asynchronously(lock2):
  403. await asyncio.sleep(1e-2)
  404. num_coros = max(100, mp.cpu_count() * 5 + 1)
  405. # note: if we deprecate py3.7, this can be reduced to max(33, cpu + 5); see https://bugs.python.org/issue35279
  406. await asyncio.wait({coro() for _ in range(num_coros)})
  407. def test_batch_tensor_descriptor_msgpack():
  408. tensor_descr = BatchTensorDescriptor.from_tensor(torch.ones(1, 3, 3, 7))
  409. tensor_descr_roundtrip = MSGPackSerializer.loads(MSGPackSerializer.dumps(tensor_descr))
  410. assert (
  411. tensor_descr.size == tensor_descr_roundtrip.size
  412. and tensor_descr.dtype == tensor_descr_roundtrip.dtype
  413. and tensor_descr.layout == tensor_descr_roundtrip.layout
  414. and tensor_descr.device == tensor_descr_roundtrip.device
  415. and tensor_descr.requires_grad == tensor_descr_roundtrip.requires_grad
  416. and tensor_descr.pin_memory == tensor_descr.pin_memory
  417. and tensor_descr.compression == tensor_descr.compression
  418. )
  419. @pytest.mark.parametrize("max_workers", [1, 2, 10])
  420. def test_performance_ema_threadsafe(
  421. max_workers: int,
  422. interval: float = 0.01,
  423. num_updates: int = 100,
  424. alpha: float = 0.05,
  425. bias_power: float = 0.7,
  426. tolerance: float = 0.05,
  427. ):
  428. def run_task(ema):
  429. task_size = random.randint(1, 4)
  430. with ema.update_threadsafe(task_size):
  431. time.sleep(task_size * interval * (0.9 + 0.2 * random.random()))
  432. return task_size
  433. with ThreadPoolExecutor(max_workers) as pool:
  434. ema = PerformanceEMA(alpha=alpha)
  435. start_time = time.perf_counter()
  436. futures = [pool.submit(run_task, ema) for i in range(num_updates)]
  437. total_size = sum(future.result() for future in futures)
  438. end_time = time.perf_counter()
  439. target = total_size / (end_time - start_time)
  440. assert ema.samples_per_second >= (1 - tolerance) * target * max_workers ** (bias_power - 1)
  441. assert ema.samples_per_second <= (1 + tolerance) * target