Skip to main content

Custom Schedulers

Implementing custom parallel backends

DevitoHorizon provides serial and Dask schedulers out of the box. You can implement custom schedulers for other parallel backends.

The Scheduler Interface

from abc import ABC, abstractmethod
from typing import Callable, Generic, List, TypeVar

T = TypeVar('T')  # Task type
R = TypeVar('R')  # Result type

class Future(Generic[R]):
    """Abstract future representing a pending computation."""

    @abstractmethod
    def result(self) -> R:
        """Get the result (blocking)."""
        pass

class Scheduler(ABC, Generic[T, R]):
    """Abstract base class for task scheduling."""

    @abstractmethod
    def map(self, func, tasks, *, shared=None, indices=None) -> List[Future[R]]:
        """Map function over tasks.

        `shared` is state every task reads, passed as the call's first
        argument -- as an argument rather than a closure, so a distributed
        backend can substitute one copy already on the worker instead of
        serializing the payload into every task.

        `indices` are the tasks' positions in the caller's original list.
        Carry them on the futures: it is what lets a failure be reported
        against the task it came from, and so what makes a retry possible.
        """
        pass

    @abstractmethod
    def reduce(self, futures: List[Future[R]], folder: Callable, initial) -> R:
        """Fold results from futures into a single accumulated value."""
        pass

    @abstractmethod
    def gather(self, futures: List[Future[R]]) -> List[R]:
        """Gather results from futures as a list."""
        pass

    @abstractmethod
    def submit(self, func: Callable, *args, **kwargs) -> Future[R]:
        """Submit a single task for execution."""
        pass

Those four are the whole contract. Everything callers actually use goes through map_reduce, which the base class implements on top of them:

result = scheduler.map_reduce(func, tasks, folder, initial, shared=payload)

It distributes shared once for the run, submits, folds results in completion order, resubmits the tasks that failed, and releases the payload at the end. A custom scheduler gets that for free; overriding share, release_shared and rescatter is only needed if the backend has a native way to hold state on its workers.

Built-in Schedulers

from devitohorizon.scheduler import create_scheduler, SerialScheduler, DaskScheduler

# Serial execution (for debugging)
scheduler = SerialScheduler()

# Dask distributed execution
from dask.distributed import Client
client = Client(n_workers=4, threads_per_worker=2)
scheduler = create_scheduler(client)

Example: Multiprocessing Scheduler

from concurrent.futures import ProcessPoolExecutor, Future as ConcurrentFuture
from devitohorizon.scheduler import Scheduler, Future

class ProcessFuture(Future):
    """concurrent.futures.Future wrapper."""

    def __init__(self, future: ConcurrentFuture):
        self._future = future

    def result(self):
        return self._future.result()

class MultiprocessingScheduler(Scheduler):
    """
    Scheduler using Python's multiprocessing.

    Good for local parallelization without external dependencies.
    """

    def __init__(self, max_workers: int = None):
        self.executor = ProcessPoolExecutor(max_workers=max_workers)

    def map(self, func, tasks, *, shared=None, indices=None):
        args = (shared,) if shared is not None else ()
        return [
            ProcessFuture(self.executor.submit(func, *args, task))
            for task in tasks
        ]

    def reduce(self, futures, folder, initial):
        acc = initial
        for f in futures:
            acc = folder(acc, f.result())
        return acc

    def gather(self, futures):
        return [f.result() for f in futures]

    def submit(self, func, *args, **kwargs):
        future = self.executor.submit(func, *args, **kwargs)
        return ProcessFuture(future)

    def shutdown(self):
        """Shutdown the executor."""
        self.executor.shutdown(wait=True)

Usage

from devitohorizon.data import Dataset
from devitohorizon.physics import DevitoPhysics
from devitohorizon.optimization import SPG

# Setup
dataset = Dataset.from_segy("data/shots.segy")
physics = DevitoPhysics(nbl=40, space_order=8)
optimizer = SPG(maxiter=10)

# Use custom scheduler
scheduler = MultiprocessingScheduler(max_workers=4)

try:
    model_opt, f_opt, result = optimizer.fwi(
        physics=physics,
        dataset=dataset,
        model0=model0,
        bounds={'vp': (1.5, 5.0)},
        scheduler=scheduler,
    )
finally:
    scheduler.shutdown()

Best Practices

  1. Handle serialization - Ensure functions and tasks are pickle-able
  2. Clean up resources - Implement shutdown() and use context managers
  3. Handle failures - Catch exceptions in task execution

See Also

Back to top