test_util_modules.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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.proto.dht_pb2_grpc import DHTStub
  11. from hivemind.proto.runtime_pb2 import CompressionType
  12. from hivemind.proto.runtime_pb2_grpc import ConnectionHandlerStub
  13. from hivemind.utils import DHTExpiration, HeapEntry, MSGPackSerializer, ValueWithExpiration
  14. from hivemind.utils.asyncio import (
  15. achain,
  16. aenumerate,
  17. afirst,
  18. aiter_with_timeout,
  19. amap_in_executor,
  20. anext,
  21. as_aiter,
  22. asingle,
  23. azip,
  24. cancel_and_wait,
  25. )
  26. from hivemind.utils.compression import deserialize_torch_tensor, serialize_torch_tensor
  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. def test_tensor_compression(size=(128, 128, 64), alpha=5e-08, beta=0.0008):
  248. torch.manual_seed(0)
  249. X = torch.randn(*size)
  250. assert torch.allclose(deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.NONE)), X)
  251. error = deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.MEANSTD_16BIT)) - X
  252. assert error.square().mean() < alpha
  253. error = deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.FLOAT16)) - X
  254. assert error.square().mean() < alpha
  255. error = deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.QUANTILE_8BIT)) - X
  256. assert error.square().mean() < beta
  257. error = deserialize_torch_tensor(serialize_torch_tensor(X, CompressionType.UNIFORM_8BIT)) - X
  258. assert error.square().mean() < beta
  259. zeros = torch.zeros(5, 5)
  260. for compression_type in CompressionType.values():
  261. assert deserialize_torch_tensor(serialize_torch_tensor(zeros, compression_type)).isfinite().all()
  262. @pytest.mark.forked
  263. @pytest.mark.asyncio
  264. async def test_channel_cache():
  265. hivemind.ChannelCache.MAXIMUM_CHANNELS = 3
  266. hivemind.ChannelCache.EVICTION_PERIOD_SECONDS = 0.1
  267. c1 = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=False)
  268. c2 = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=True)
  269. c3 = hivemind.ChannelCache.get_stub("localhost:1338", DHTStub, aio=False)
  270. c3_again = hivemind.ChannelCache.get_stub("localhost:1338", DHTStub, aio=False)
  271. c1_again = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=False)
  272. c4 = hivemind.ChannelCache.get_stub("localhost:1339", DHTStub, aio=True)
  273. c2_anew = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=True)
  274. c1_yetagain = hivemind.ChannelCache.get_stub("localhost:1337", DHTStub, aio=False)
  275. await asyncio.sleep(0.2)
  276. c1_anew = hivemind.ChannelCache.get_stub(target="localhost:1337", aio=False, stub_type=DHTStub)
  277. c1_anew_again = hivemind.ChannelCache.get_stub(target="localhost:1337", aio=False, stub_type=DHTStub)
  278. c1_otherstub = hivemind.ChannelCache.get_stub(target="localhost:1337", aio=False, stub_type=ConnectionHandlerStub)
  279. await asyncio.sleep(0.05)
  280. c1_otherstub_again = hivemind.ChannelCache.get_stub(
  281. target="localhost:1337", aio=False, stub_type=ConnectionHandlerStub
  282. )
  283. all_channels = [c1, c2, c3, c4, c3_again, c1_again, c2_anew, c1_yetagain, c1_anew, c1_anew_again, c1_otherstub]
  284. assert all(isinstance(c, DHTStub) for c in all_channels[:-1])
  285. assert isinstance(all_channels[-1], ConnectionHandlerStub)
  286. assert "aio" in repr(c2.rpc_find)
  287. assert "aio" not in repr(c1.rpc_find)
  288. duplicates = {
  289. (c1, c1_again),
  290. (c1, c1_yetagain),
  291. (c1_again, c1_yetagain),
  292. (c3, c3_again),
  293. (c1_anew, c1_anew_again),
  294. (c1_otherstub, c1_otherstub_again),
  295. }
  296. for i in range(len(all_channels)):
  297. for j in range(i + 1, len(all_channels)):
  298. ci, cj = all_channels[i], all_channels[j]
  299. assert (ci is cj) == ((ci, cj) in duplicates), (i, j)
  300. def test_serialize_tensor():
  301. tensor = torch.randn(512, 12288)
  302. serialized_tensor = serialize_torch_tensor(tensor, CompressionType.NONE)
  303. for chunk_size in [1024, 64 * 1024, 64 * 1024 + 1, 10 ** 9]:
  304. chunks = list(hivemind.split_for_streaming(serialized_tensor, chunk_size))
  305. assert len(chunks) == (len(serialized_tensor.buffer) - 1) // chunk_size + 1
  306. restored = hivemind.combine_from_streaming(chunks)
  307. assert torch.allclose(deserialize_torch_tensor(restored), tensor)
  308. chunk_size = 30 * 1024
  309. serialized_tensor = serialize_torch_tensor(tensor, CompressionType.FLOAT16)
  310. chunks = list(hivemind.split_for_streaming(serialized_tensor, chunk_size))
  311. assert len(chunks) == (len(serialized_tensor.buffer) - 1) // chunk_size + 1
  312. restored = hivemind.combine_from_streaming(chunks)
  313. assert torch.allclose(deserialize_torch_tensor(restored), tensor, rtol=0, atol=1e-2)
  314. tensor = torch.randint(0, 100, (512, 1, 1))
  315. serialized_tensor = serialize_torch_tensor(tensor, CompressionType.NONE)
  316. chunks = list(hivemind.split_for_streaming(serialized_tensor, chunk_size))
  317. assert len(chunks) == (len(serialized_tensor.buffer) - 1) // chunk_size + 1
  318. restored = hivemind.combine_from_streaming(chunks)
  319. assert torch.allclose(deserialize_torch_tensor(restored), tensor)
  320. scalar = torch.tensor(1.0)
  321. serialized_scalar = serialize_torch_tensor(scalar, CompressionType.NONE)
  322. assert torch.allclose(deserialize_torch_tensor(serialized_scalar), scalar)
  323. serialized_scalar = serialize_torch_tensor(scalar, CompressionType.FLOAT16)
  324. assert torch.allclose(deserialize_torch_tensor(serialized_scalar), scalar)
  325. def test_serialize_tuple():
  326. test_pairs = (
  327. ((1, 2, 3), [1, 2, 3]),
  328. (("1", False, 0), ["1", False, 0]),
  329. (("1", False, 0), ("1", 0, 0)),
  330. (("1", b"qq", (2, 5, "0")), ["1", b"qq", (2, 5, "0")]),
  331. )
  332. for first, second in test_pairs:
  333. assert MSGPackSerializer.loads(MSGPackSerializer.dumps(first)) == first
  334. assert MSGPackSerializer.loads(MSGPackSerializer.dumps(second)) == second
  335. assert MSGPackSerializer.dumps(first) != MSGPackSerializer.dumps(second)
  336. def test_split_parts():
  337. tensor = torch.randn(910, 512)
  338. serialized_tensor_part = serialize_torch_tensor(tensor, allow_inplace=False)
  339. chunks1 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 16384))
  340. assert len(chunks1) == int(np.ceil(tensor.numel() * tensor.element_size() / 16384))
  341. chunks2 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10_000))
  342. assert len(chunks2) == int(np.ceil(tensor.numel() * tensor.element_size() / 10_000))
  343. chunks3 = list(hivemind.utils.split_for_streaming(serialized_tensor_part, 10 ** 9))
  344. assert len(chunks3) == 1
  345. compressed_tensor_part = serialize_torch_tensor(tensor, CompressionType.FLOAT16, allow_inplace=False)
  346. chunks4 = list(hivemind.utils.split_for_streaming(compressed_tensor_part, 16384))
  347. assert len(chunks4) == int(np.ceil(tensor.numel() * 2 / 16384))
  348. combined1 = hivemind.utils.combine_from_streaming(chunks1)
  349. combined2 = hivemind.utils.combine_from_streaming(iter(chunks2))
  350. combined3 = hivemind.utils.combine_from_streaming(chunks3)
  351. combined4 = hivemind.utils.combine_from_streaming(chunks4)
  352. for combined in combined1, combined2, combined3:
  353. assert torch.allclose(tensor, deserialize_torch_tensor(combined), rtol=1e-5, atol=1e-8)
  354. assert torch.allclose(tensor, deserialize_torch_tensor(combined4), rtol=1e-3, atol=1e-3)
  355. combined_incomplete = hivemind.utils.combine_from_streaming(chunks4[:5])
  356. combined_incomplete2 = hivemind.utils.combine_from_streaming(chunks4[:1])
  357. combined_incomplete3 = hivemind.utils.combine_from_streaming(chunks4[:-1])
  358. for combined in combined_incomplete, combined_incomplete2, combined_incomplete3:
  359. with pytest.raises(RuntimeError):
  360. deserialize_torch_tensor(combined)
  361. # note: we rely on this being RuntimeError in hivemind.averaging.allreduce.AllreduceRunner
  362. def test_generic_data_classes():
  363. value_with_exp = ValueWithExpiration(value="string_value", expiration_time=DHTExpiration(10))
  364. assert value_with_exp.value == "string_value" and value_with_exp.expiration_time == DHTExpiration(10)
  365. heap_entry = HeapEntry(expiration_time=DHTExpiration(10), key="string_value")
  366. assert heap_entry.key == "string_value" and heap_entry.expiration_time == DHTExpiration(10)
  367. sorted_expirations = sorted([DHTExpiration(value) for value in range(1, 1000)])
  368. sorted_heap_entries = sorted([HeapEntry(DHTExpiration(value), key="any") for value in range(1, 1000)[::-1]])
  369. assert all([entry.expiration_time == value for entry, value in zip(sorted_heap_entries, sorted_expirations)])
  370. @pytest.mark.asyncio
  371. async def test_asyncio_utils():
  372. res = [i async for i, item in aenumerate(as_aiter("a", "b", "c"))]
  373. assert res == list(range(len(res)))
  374. num_steps = 0
  375. async for elem in amap_in_executor(lambda x: x ** 2, as_aiter(*range(100)), max_prefetch=5):
  376. assert elem == num_steps ** 2
  377. num_steps += 1
  378. assert num_steps == 100
  379. ours = [
  380. elem
  381. async for elem in amap_in_executor(max, as_aiter(*range(7)), as_aiter(*range(-50, 50, 10)), max_prefetch=1)
  382. ]
  383. ref = list(map(max, range(7), range(-50, 50, 10)))
  384. assert ours == ref
  385. ours = [row async for row in azip(as_aiter("a", "b", "c"), as_aiter(1, 2, 3))]
  386. ref = list(zip(["a", "b", "c"], [1, 2, 3]))
  387. assert ours == ref
  388. async def _aiterate():
  389. yield "foo"
  390. yield "bar"
  391. yield "baz"
  392. iterator = _aiterate()
  393. assert (await anext(iterator)) == "foo"
  394. tail = [item async for item in iterator]
  395. assert tail == ["bar", "baz"]
  396. with pytest.raises(StopAsyncIteration):
  397. await anext(iterator)
  398. assert [item async for item in achain(_aiterate(), as_aiter(*range(5)))] == ["foo", "bar", "baz"] + list(range(5))
  399. assert await asingle(as_aiter(1)) == 1
  400. with pytest.raises(ValueError):
  401. await asingle(as_aiter())
  402. with pytest.raises(ValueError):
  403. await asingle(as_aiter(1, 2, 3))
  404. assert await afirst(as_aiter(1)) == 1
  405. assert await afirst(as_aiter()) is None
  406. assert await afirst(as_aiter(), -1) == -1
  407. assert await afirst(as_aiter(1, 2, 3)) == 1
  408. async def iterate_with_delays(delays):
  409. for i, delay in enumerate(delays):
  410. await asyncio.sleep(delay)
  411. yield i
  412. async for _ in aiter_with_timeout(iterate_with_delays([0.1] * 5), timeout=0.2):
  413. pass
  414. sleepy_aiter = iterate_with_delays([0.1, 0.1, 0.3, 0.1, 0.1])
  415. num_steps = 0
  416. with pytest.raises(asyncio.TimeoutError):
  417. async for _ in aiter_with_timeout(sleepy_aiter, timeout=0.2):
  418. num_steps += 1
  419. assert num_steps == 2
  420. @pytest.mark.asyncio
  421. async def test_cancel_and_wait():
  422. finished_gracefully = False
  423. async def coro_with_finalizer():
  424. nonlocal finished_gracefully
  425. try:
  426. await asyncio.Event().wait()
  427. except asyncio.CancelledError:
  428. await asyncio.sleep(0.05)
  429. finished_gracefully = True
  430. raise
  431. task = asyncio.create_task(coro_with_finalizer())
  432. await asyncio.sleep(0.05)
  433. assert await cancel_and_wait(task)
  434. assert finished_gracefully
  435. async def coro_with_result():
  436. return 777
  437. async def coro_with_error():
  438. raise ValueError("error")
  439. task_with_result = asyncio.create_task(coro_with_result())
  440. task_with_error = asyncio.create_task(coro_with_error())
  441. await asyncio.sleep(0.05)
  442. assert not await cancel_and_wait(task_with_result)
  443. assert not await cancel_and_wait(task_with_error)