|
7 | 7 | import ctypes.util |
8 | 8 | import multiprocessing as mp |
9 | 9 | import os |
| 10 | +import queue |
10 | 11 | import signal |
11 | 12 | import sys |
| 13 | +import threading |
| 14 | +import time |
12 | 15 | from typing import TYPE_CHECKING |
13 | 16 | from typing import Callable |
| 17 | +from typing import NamedTuple |
14 | 18 | from typing import TypeVar |
15 | 19 |
|
16 | 20 | from .logger import _UNRECOVERABLE_RUNTIME_ERROR_RE |
|
21 | 25 | _T = TypeVar("_T") |
22 | 26 |
|
23 | 27 |
|
| 28 | +class WorkerPoolResult(NamedTuple): |
| 29 | + worker_index: int |
| 30 | + elapsed: float |
| 31 | + result: object |
| 32 | + |
| 33 | + |
24 | 34 | def _set_pdeathsig() -> None: |
25 | 35 | """SIGTERM the child if the parent dies (Linux only, best-effort).""" |
26 | 36 | if sys.platform != "linux": |
@@ -146,3 +156,97 @@ def _kill(self) -> None: |
146 | 156 | connection.close() |
147 | 157 | self._process = None |
148 | 158 | self._parent_connection = None |
| 159 | + |
| 160 | + |
| 161 | +class BenchmarkWorkerPool: |
| 162 | + """Pool of long-lived ``BenchmarkWorker`` processes.""" |
| 163 | + |
| 164 | + def __init__(self, num_workers: int) -> None: |
| 165 | + if num_workers < 1: |
| 166 | + raise ValueError(f"num_workers must be >= 1, got {num_workers}") |
| 167 | + self.workers = [BenchmarkWorker(device=None) for _ in range(num_workers)] |
| 168 | + |
| 169 | + @property |
| 170 | + def num_workers(self) -> int: |
| 171 | + return len(self.workers) |
| 172 | + |
| 173 | + def run_job_on_worker( |
| 174 | + self, worker_index: int, job: Callable[[], _T], timeout: float |
| 175 | + ) -> _T: |
| 176 | + return self.workers[worker_index % self.num_workers].run(job, timeout=timeout) |
| 177 | + |
| 178 | + def run_jobs( |
| 179 | + self, jobs: list[Callable[[], object]], timeout: float |
| 180 | + ) -> list[WorkerPoolResult]: |
| 181 | + """Run jobs across the worker pool while preserving input order. |
| 182 | +
|
| 183 | + Each worker thread owns one worker and pulls job indices from a shared |
| 184 | + queue, so slow jobs do not block unrelated workers. Worker exceptions |
| 185 | + are captured in ``WorkerPoolResult.result`` for the corresponding job. |
| 186 | + """ |
| 187 | + if not jobs: |
| 188 | + return [] |
| 189 | + active_workers = min(self.num_workers, len(jobs)) |
| 190 | + result_slots: list[WorkerPoolResult | None] = [None] * len(jobs) |
| 191 | + work_queue: queue.Queue[int] = queue.Queue() |
| 192 | + for i in range(len(jobs)): |
| 193 | + work_queue.put(i) |
| 194 | + |
| 195 | + def process_queue(worker_idx: int) -> None: |
| 196 | + worker = self.workers[worker_idx] |
| 197 | + while True: |
| 198 | + try: |
| 199 | + i = work_queue.get_nowait() |
| 200 | + except queue.Empty: |
| 201 | + return |
| 202 | + start = time.perf_counter() |
| 203 | + job_result = _run_job_capture_error(worker, jobs[i], timeout) |
| 204 | + result_slots[i] = WorkerPoolResult( |
| 205 | + worker_index=worker_idx, |
| 206 | + elapsed=time.perf_counter() - start, |
| 207 | + result=job_result, |
| 208 | + ) |
| 209 | + |
| 210 | + _run_worker_threads(process_queue, active_workers) |
| 211 | + ordered_results: list[WorkerPoolResult] = [] |
| 212 | + for slot in result_slots: |
| 213 | + assert slot is not None |
| 214 | + ordered_results.append(slot) |
| 215 | + return ordered_results |
| 216 | + |
| 217 | + def start_all(self, limit: int | None = None) -> None: |
| 218 | + """Start workers before threaded dispatch so their lifetime is not |
| 219 | + tied to short-lived dispatch threads.""" |
| 220 | + if limit is None: |
| 221 | + limit = self.num_workers |
| 222 | + for worker in self.workers[:limit]: |
| 223 | + if not worker.alive(): |
| 224 | + worker._start() |
| 225 | + |
| 226 | + def shutdown(self) -> None: |
| 227 | + for w in self.workers: |
| 228 | + with contextlib.suppress(Exception): |
| 229 | + w.shutdown() |
| 230 | + |
| 231 | + |
| 232 | +def _run_job_capture_error( |
| 233 | + worker: BenchmarkWorker, job: Callable[[], object], timeout: float |
| 234 | +) -> object: |
| 235 | + try: |
| 236 | + return worker.run(job, timeout=timeout) |
| 237 | + except BaseException as e: |
| 238 | + e.__traceback__ = None |
| 239 | + return e |
| 240 | + |
| 241 | + |
| 242 | +def _run_worker_threads(target: Callable[[int], None], n: int) -> None: |
| 243 | + if n == 1: |
| 244 | + target(0) |
| 245 | + return |
| 246 | + threads = [ |
| 247 | + threading.Thread(target=target, args=(i,), daemon=True) for i in range(n) |
| 248 | + ] |
| 249 | + for t in threads: |
| 250 | + t.start() |
| 251 | + for t in threads: |
| 252 | + t.join() |
0 commit comments