Files
models/models/cluster.py
T

53 lines
2.2 KiB
Python

"""Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is
installed (the `dask` extra, for testing on a cluster) they run on the scheduler at
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores. Without it (the
product) joblib runs them on local processes. BATCH_JOBS caps how many run at once: each
task carries its data (a recording), so a cap paces a slow link."""
import os
from collections.abc import Callable, Iterable
from importlib.util import find_spec
from typing import Any
from joblib import Parallel, delayed
def jobs() -> int:
"""How many tasks run at once: BATCH_JOBS, or every core (or worker)."""
return int(os.environ.get("BATCH_JOBS", "-1"))
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
"""`task(*a)` for each tuple of `arguments`, results in their order. The arguments are
drawn as tasks start, so at most `jobs()` of them are held at once."""
if find_spec("distributed") is None:
return Parallel(n_jobs=jobs())(delayed(task)(*a) for a in arguments)
from distributed import Client, LocalCluster, as_completed
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
# one process per core, no dashboard port to collide with (8787 is often taken)
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
try:
with Client(where) as client:
limit = jobs() if jobs() > 0 else sum(client.nthreads().values())
pending = iter(enumerate(arguments))
results: dict[int, Any] = {}
order: dict[Any, int] = {}
def submit() -> Any | None:
if (item := next(pending, None)) is None:
return None
future = client.submit(task, *item[1], pure=False)
order[future] = item[0]
return future
running = as_completed([f for f in (submit() for _ in range(limit)) if f])
for done in running:
results[order.pop(done)] = done.result()
if (future := submit()) is not None:
running.add(future)
return [results[i] for i in range(len(results))]
finally:
if not address:
where.close()