tinygrad/extra/helpers.py

50 lines
1.5 KiB
Python
Raw Normal View History

import multiprocessing, subprocess
2023-07-05 04:51:20 +08:00
import cloudpickle # type: ignore
from typing import Any
def _early_exec_process(qin, qout):
while True:
path, inp = qin.get()
try:
qout.put(subprocess.check_output(path, input=inp))
except Exception as e:
qout.put(e)
2023-05-07 02:56:09 +08:00
def enable_early_exec():
2023-05-07 03:18:54 +08:00
qin: multiprocessing.Queue = multiprocessing.Queue()
qout: multiprocessing.Queue = multiprocessing.Queue()
2023-05-07 02:56:09 +08:00
p = multiprocessing.Process(target=_early_exec_process, args=(qin, qout))
p.daemon = True
p.start()
def early_exec(x):
qin.put(x)
ret = qout.get()
if isinstance(ret, Exception): raise ret
else: return ret
2023-05-07 02:56:09 +08:00
return early_exec
def proc(itermaker, q) -> None:
try:
for x in itermaker(): q.put(x)
except Exception as e:
q.put(e)
finally:
q.put(None)
q.close()
class _CloudpickleFunctionWrapper:
def __init__(self, fn): self.fn = fn
def __getstate__(self): return cloudpickle.dumps(self.fn)
def __setstate__(self, pfn): self.fn = cloudpickle.loads(pfn)
def __call__(self, *args, **kwargs) -> Any: return self.fn(*args, **kwargs)
2023-06-28 12:23:26 +08:00
def cross_process(itermaker, maxsize=16):
2023-05-14 12:25:36 +08:00
q: multiprocessing.Queue = multiprocessing.Queue(maxsize)
# multiprocessing uses pickle which cannot dump lambdas, so use cloudpickle.
p = multiprocessing.Process(target=proc, args=(_CloudpickleFunctionWrapper(itermaker), q))
p.start()
2023-06-28 12:23:26 +08:00
while True:
ret = q.get()
if isinstance(ret, Exception): raise ret
elif ret is None: break
else: yield ret