Build a Multi-GPU Test Harness in Python
System DesignModel answerLast updated
Design and implement a pytest-style test harness that runs graphics validation tests in parallel across multiple GPUs, handling fixtures, retries, and process isolation.
Build a Multi-GPU Test Harness in Python
You are building a validation framework that runs graphics tests across several GPUs on the same machine. Each test verifies rendered output — comparing pixel buffers, checking shader correctness, validating memory usage — and the suite can contain hundreds of cases with different parameter combinations.
Design and implement this harness from first principles. Your answer should cover:
Architecture
- How you split the two concerns: defining tests (registration, parametrization, fixtures) vs. executing them (process isolation, concurrency, device assignment).
- Why you choose processes over threads for GPU work, and how you coordinate them without blocking the parent.
Python mechanics — explain and use each of these
- Generators for lazy test collection
- Context managers and
ExitStackfor fixture lifecycle - Dependency injection via
inspect.signature - Type hints and frozen dataclasses for inter-process messages
asyncioin the parent process andProcessPoolExecutorfor workers- Retry logic that distinguishes transient device errors from real test failures
Framework choice
- Compare
unittestandpyteston style, fixtures, parametrization, and ecosystem. State which you would use in production and why.
Expected output
- A working code skeleton (registration decorators, collection generator, DI resolver, worker entry point, async orchestrator).
- Prose explaining every design decision and its trade-offs.
- A brief note on what you would not implement from scratch in production.
Hints
Hint 1
Start by separating concerns: test *definition* (fixtures, params, retries) is pure Python bookkeeping; test *execution* (one process per GPU, driver crash isolation) is a concurrency problem. Solve them independently before wiring them together.
Hint 2
The GIL is not your main enemy here — driver crashes and blocked CUDA calls are. A crashed GPU worker should not take down the orchestrator. Think about what `ProcessPoolExecutor` gives you and what `BrokenProcessPool` means for your retry strategy.
Hint 3
Fixtures have dependencies on other fixtures, forming a DAG. Use `inspect.signature` to read parameter names and recurse. Wrap each resolved fixture in an `ExitStack` so teardown always runs in LIFO order, even when setup partially fails mid-DAG.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The harness has two separate jobs that should never be tangled together.
Job 1 — defining tests. Decorators register test functions and fixtures into module-level dicts. Parametrization stores a mapping of parameter names to value lists; collection lazily yields the cartesian product as Job dataclasses. This is pure Python with no concurrency, and pytest is the obvious model.
Job 2 — running tests across GPUs. Each test needs an exclusive device context, may hang or crash the driver, and does CPU-heavy image diffing. The right tool is one OS process per GPU, pinned with CUDA_VISIBLE_DEVICES. A single asyncio event loop in the parent hands work to a ProcessPoolExecutor without blocking. This combination sidesteps the GIL and provides crash isolation — a segfault in a worker does not kill the parent.
unittest vs pytest
| unittest | pytest | |
|---|---|---|
| Style | TestCase subclasses, self.assertEqual | Plain functions, bare assert with rewriting |
| Fixtures | setUp/tearDown, inheritance-based | Named, composable, scoped, yield-style teardown |
| Parametrization | subTest loops (single test id in output) | @pytest.mark.parametrize, each case has its own id |
| Ecosystem | stdlib only | pytest-xdist, pytest-rerunfailures, pytest-timeout, hooks |
In production I would use pytest plus a custom plugin: a session-scoped gpu fixture reads worker_id from xdist, and pytest_collection_modifyitems shards tests by GPU index. The code below implements the mechanics from first principles because that is what this question is probing.
Design decisions
Generators for collection. itertools.product over parameter lists is a natural generator pipeline. It keeps memory flat even with thousands of combinations and lets the orchestrator start dispatching before collection finishes.
Context managers and ExitStack for fixtures. Each fixture is a yield-style generator wrapped with contextlib.contextmanager. An ExitStack per test attempt registers every fixture as it is resolved. LIFO teardown is then guaranteed even when setup fails halfway through a dependency chain — critical for releasing GPU memory and file handles.
Dependency injection. inspect.signature(fn).parameters gives the parameter names of a test or fixture. The resolver walks the name: is it a provided value (e.g. a param combo entry or the built-in gpu_id)? A cached fixture? A fixture that needs recursive resolution? This keeps test functions free of any harness import.
Typed messages between processes. Frozen dataclasses (Job, Result) are picklable by default and catch attribute typos at definition time rather than at runtime across a process boundary.
Retry policy. Only TransientGPUError (TDR, device-lost, fragmented OOM) is retried. Fixtures are rebuilt on every attempt so a poisoned context is never reused. An AssertionError is a real test failure and must never be swallowed. Exponential backoff caps at 2 s to avoid stalling the suite.
BrokenProcessPool handling. If a worker process is killed by the OS (driver crash, OOM killer), ProcessPoolExecutor raises BrokenProcessPool. The orchestrator catches this, logs the lost job as an error, and respawns a fresh executor for the remaining work.
Code
from __future__ import annotations
import asyncio, contextlib, inspect, itertools, logging
import multiprocessing as mp, os, time
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from dataclasses import dataclass, field
from typing import Any, Callable, Iterable, Iterator, Literal, Mapping, Sequence
log = logging.getLogger("harness")
class TransientGPUError(RuntimeError):
"""Device lost / TDR / OOM-after-fragmentation — safe to retry."""
# ── registration ──────────────────────────────────────────────────────────────
FIXTURES: dict[str, Callable[..., Iterator[Any]]] = {}
TESTS: dict[str, "TestSpec"] = {}
def fixture(fn: Callable[..., Iterator[Any]]) -> Callable[..., Iterator[Any]]:
FIXTURES[fn.__name__] = fn
return fn
@dataclass(frozen=True)
class TestSpec:
name: str
fn: Callable[..., None]
params: Mapping[str, Sequence[Any]] = field(default_factory=dict)
retries: int = 0
def test(*, params: Mapping[str, Sequence[Any]] | None = None, retries: int = 0):
def deco(fn: Callable[..., None]) -> Callable[..., None]:
TESTS[fn.__name__] = TestSpec(fn.__name__, fn, dict(params or {}), retries)
return fn
return deco
# ── collection (generator) ────────────────────────────────────────────────────
@dataclass(frozen=True)
class Job:
test: str
kwargs: tuple[tuple[str, Any], ...]
@property
def id(self) -> str:
return f"{self.test}[{'-'.join(str(v) for _, v in self.kwargs)}]"
def collect() -> Iterator[Job]:
for spec in TESTS.values():
keys = list(spec.params)
for combo in itertools.product(*(spec.params[k] for k in keys)):
yield Job(spec.name, tuple(zip(keys, combo)))
# ── dependency injection ───────────────────────────────────────────────────────
def _resolve(
name: str,
stack: contextlib.ExitStack,
cache: dict[str, Any],
provided: Mapping[str, Any],
resolving: set[str],
) -> Any:
if name in provided:
return provided[name]
if name in cache:
return cache[name]
if name not in FIXTURES:
raise LookupError(f"unknown fixture or parameter: {name!r}")
if name in resolving:
raise RecursionError(f"fixture dependency cycle at {name!r}")
resolving.add(name)
deps = {
p: _resolve(p, stack, cache, provided, resolving)
for p in inspect.signature(FIXTURES[name]).parameters
}
value = stack.enter_context(contextlib.contextmanager(FIXTURES[name])(**deps))
resolving.discard(name)
cache[name] = value
return value
# ── worker (one process per GPU) ──────────────────────────────────────────────
@dataclass(frozen=True)
class Result:
job_id: str
gpu: int
outcome: Literal["pass", "fail", "error"]
attempts: int
seconds: float
message: str = ""
_GPU: int = -1
def _init_worker(gpu: int) -> None:
global _GPU
_GPU = gpu
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu) # must precede any CUDA import
logging.basicConfig(
level=logging.INFO,
format=f"%(asctime)s gpu{gpu} %(levelname)s %(message)s",
)
def run_job(job: Job) -> Result:
spec = TESTS[job.test]
provided: dict[str, Any] = {"gpu_id": _GPU, **dict(job.kwargs)}
start = time.perf_counter()
def done(outcome: str, attempt: int, msg: str = "") -> Result:
return Result(job.id, _GPU, outcome, attempt, time.perf_counter() - start, msg) # type: ignore[arg-type]
for attempt in range(1, spec.retries + 2):
try:
with contextlib.ExitStack() as stack:
cache: dict[str, Any] = {}
args = {
p: _resolve(p, stack, cache, provided, set())
for p in inspect.signature(spec.fn).parameters
}
spec.fn(**args)
log.info("PASS %s", job.id)
return done("pass", attempt)
except TransientGPUError as exc:
log.warning("transient on %s attempt %d: %s", job.id, attempt, exc)
if attempt > spec.retries:
return done("error", attempt, repr(exc))
time.sleep(min(0.1 * 2 ** (attempt - 1), 2.0))
except AssertionError as exc:
log.error("FAIL %s: %s", job.id, exc)
return done("fail", attempt, str(exc))
except Exception as exc:
log.exception("ERROR %s", job.id)
return done("error", attempt, repr(exc))
raise AssertionError("unreachable")
# ── orchestrator (asyncio in parent) ─────────────────────────────────────────
async def run_all(gpus: Sequence[int], jobs: Iterable[Job]) -> list[Result]:
loop = asyncio.get_running_loop()
results: list[Result] = []
pending = list(jobs)
while pending:
# round-robin: one executor per GPU, workers=1 each so contexts don't share
executors = [
ProcessPoolExecutor(
max_workers=1,
mp_context=mp.get_context("spawn"),
initializer=_init_worker,
initargs=(gpu,),
)
for gpu in gpus
]
batch, pending = pending[: len(gpus)], pending[len(gpus):]
futures = [
loop.run_in_executor(executors[i % len(gpus)], run_job, job)
for i, job in enumerate(batch)
]
try:
batch_results = await asyncio.gather(*futures)
results.extend(batch_results)
except BrokenProcessPool as exc:
log.error("worker process died: %s — re-queuing lost jobs", exc)
# re-queue jobs whose futures didn't resolve
pending = [
batch[i] for i, f in enumerate(futures) if f.exception() is not None
] + pending
finally:
for ex in executors:
ex.shutdown(wait=False)
return results
Common mistakes
- Sharing a process pool across GPUs. If all workers share one pool, you cannot pin
CUDA_VISIBLE_DEVICESreliably because environment variables are inherited at spawn time, not per-submit. - Reusing fixtures across retry attempts. After a
TransientGPUErrorthe device context may be corrupted. Always reconstruct the fullExitStackon each retry. - Catching
AssertionErrorin the transient handler. A failed pixel comparison is a real failure, not a retry candidate. Keeping the two except branches separate is not optional. - Using threads instead of processes. The GIL does not protect against CUDA driver state being shared between threads; a driver crash in one thread can corrupt another. Processes give hard isolation.
What to skip in production
Don't reimplement collection, parametrization IDs, or plugin hooks. Use pytest with pytest-xdist (parallel workers), pytest-rerunfailures (retries), and pytest-timeout (hang detection). Write only the GPU-pinning fixture and a conftest.py hook to shard by device. The code above is useful for understanding the mechanics; it is not a production replacement for the pytest ecosystem.