Skip to content

loqs.tools.paralleltools

Shared program-level parallelism helpers.

Chunks a sequence of work items (e.g. edesign circuits, error-injected programs, noise-sweep points) and dispatches one worker call per chunk, either through any plain .submit()-based executor (loky, mpi4py.futures.MPIPoolExecutor) or through a submitit.Executor's bulk map_array (a single SLURM array-job submission for every chunk, rather than one per .submit() call). ParallelStrategy bundles this program-level dispatch together with optional nested shot-level parallelism into one reusable object; the lower-level chunk_*/ run_chunks_with_* functions it's built on are also exposed directly for callers that want finer control. Callers own building the actual per-chunk worker function; this module owns chunking, dispatch, and progress reporting, so it can be reused by every program-level call site rather than reimplemented per tool.

Classes

Attributes

Name Type Value Doc
T TypeVar TypeVar('T')
R TypeVar TypeVar('R')
Box tuple[float, float, float, float]

Functions

chunk_round_robin

chunk_round_robin(items: Sequence[T], n_chunks: int) -> list[list[T]]

Split items into n_chunks round-robin/striped chunks (item i goes to chunk i % n_chunks), rather than naive contiguous slicing.

This is deliberate insurance against workloads whose per-item cost drifts with position (e.g. GST circuits growing deeper with index, which naive contiguous chunking would concentrate almost entirely into the last few chunks). It's a placeholder for a real cost-weighted (longest-processing-time-first) chunker, meant to be swappable in behind this same call site without touching the surrounding dispatch code.


format_profile_table

format_profile_table(results: Mapping[str, ProfileResult]) -> str

Plain, fixed-width text summary of profile_strategies results: one row per strategy (in results' own order), wall time as mean +/- std, speedup vs. a fully-serial baseline when one was profiled (-- for the baseline itself, or every row, when there wasn't one), peak memory and mean CPU% when resource stats were collected (-- otherwise).


plot_profile_results

plot_profile_results(results: Mapping[str, ProfileResult]) -> list[matplotlib.axes.Axes]

Simple bar/box-plot summary of profile_strategies results: a wall-time bar chart (mean, with error bars when repeats > 1) plus, whenever resource stats were collected, a peak-memory box plot and a mean-CPU%-percent box plot -- one box per strategy, built directly from each result's raw chunk_stats (Axes.boxplot computes quartiles directly, no manual computation needed here).

Requires matplotlib (pip install loqs[visualization]); imported lazily like ParallelStrategy.plot.


profile_strategies

profile_strategies(work_fn: Callable[[ParallelStrategy], Any], strategies: Mapping[str, ParallelStrategy], repeats: int = 1, sample_interval: float = 0.2, warmup: bool = False, reuse_slurm_allocation: bool = False) -> dict[str, ProfileResult]

Measure real wall-clock time and resource usage for a caller-chosen set of ParallelStrategy configurations against a caller-chosen working example.

Calls work_fn(strategy) once per entry in strategies (repeats times each), returning one ProfileResult per entry in a dict keyed by the same labels -- work_fn is entirely the caller's, e.g. a closure like lambda strategy: FaultInjectionRunner(programs, ..., parallel_strategy=strategy).run(), so this function never needs any GST/fault-injection/noise-sweep-specific knowledge of what it's actually timing.

Peak memory and mean CPU utilization are measured via psutil (pip install loqs[parallel]/loqs[mpi]), summed across every tracked process each sample (so e.g. ~400% CPU means 4 cores fully busy, not normalized to total machine capacity) -- for a chunked strategy, each dispatched chunk self-reports its own worker process's usage from wherever it actually runs (see dispatch), which is what makes this work correctly for a genuinely multi-node strategy, not just a local one; for an unchunked/serial strategy, this process's own usage is sampled directly.

warmup=True runs work_fn(strategy) once per strategy, discarding its result/timing/stats, before the timed repeats loop -- a real pass through the same dispatch path a strategy's executor(s) are only actually built (or reused, per _resolve_program_executor) on first use, so an unwarmed first repeat otherwise pays for real worker-process startup/import cost that later repeats don't.

reuse_slurm_allocation=True (only meaningful for submitit-backed strategies) installs a fake sbatch on PATH for the whole sweep, so every candidate strategy dispatches against one already-held SLURM allocation instead of each independently queueing -- see reused_slurm_allocation for the mechanism and its accepted limitations. Requires already running inside a real allocation.

If one entry in strategies is fully serial (program_executor and shot_executor both None), every other entry's ProfileResult gets a speedup (that strategy's wall_time_mean divided into the serial one's) once every result is in -- the baseline entry's own speedup stays None. Nothing is computed when no entry is fully serial, or (using whichever is found first in strategies' own order) when more than one is.

repeats must be at least 1, else a ValueError is raised before anything runs.


resolve_shot_executor

resolve_shot_executor(shot_executor: SubmitExecutor | Callable[[], SubmitExecutor] | None) -> SubmitExecutor | None

Resolve shot_executor into an actual executor instance (or None), accepting either a live executor or a zero-argument factory callable that builds one, disambiguated via callable() -- executors don't implement __call__ in practice, so this is unambiguous.

A live executor (e.g. a loky.get_reusable_executor() instance) holds real OS resources (pipes/locks) that cannot be pickled across a process boundary, so it can only be used as-is when nothing needs to pickle it (no program-level chunking in play). A factory -- a plain, picklable, zero-argument callable that builds and returns a fresh executor -- sidesteps this: it crosses the process boundary instead of the executor itself, and each worker calls it once to get an executor native to its own process, nesting shot-level parallelism inside program-level parallelism. ParallelStrategy is what actually enforces that a factory (not a live executor) is used whenever program-level chunking is also in play; this function just resolves whichever form it's given. Callers should invoke this once per chunk (not once per item within a chunk), so a factory that spins up new subprocesses doesn't pay that cost more than once per chunk.


reused_slurm_allocation

reused_slurm_allocation()

Temporarily installs the fake sbatch script (see _FAKE_SBATCH_SCRIPT) on PATH, so every submitit-driven SlurmExecutor call made inside this context runs against whatever real SLURM allocation this process is already inside, instead of each independently requesting a new one from the scheduler -- usable directly around any submitit-driven dispatch, not just through profile_strategies's own reuse_slurm_allocation parameter, which is built on top of this same context manager.

Requires actually running inside a real SLURM allocation already (checked via SLURM_JOB_ID); raises otherwise, since faking sbatch outside one has no real allocation to dispatch against. Restores the original PATH and removes the temporary script afterward, regardless of how the with block exits.


run_chunks_with_map_array_executor

run_chunks_with_map_array_executor(executor: MapArrayExecutor, worker_fn: Callable[[list[T]], R], chunks: Sequence[list[T]], desc: str = 'Processing chunks', poll_interval: float = 1.0, on_poll: Callable[[], None] | None = None) -> list[R]

Dispatch worker_fn over chunks via a single MapArrayExecutor. map_array call (e.g. one sbatch submission covering every chunk for a submitit.Executor, rather than one per .submit() -- the whole reason to prefer a MapArrayExecutor for scheduler fan-out), returning one result per chunk in the same order as chunks.

A submitit.Job isn't a concurrent.futures.Future, so progress can't use as_completed; instead this polls each job's cheap .done() check (which only occasionally falls back to an actual cluster status call, throttled internally by submitit itself) every poll_interval seconds. An optional on_poll() callback is invoked once per iteration of the polling loop (whether or not any jobs completed that iteration).


run_chunks_with_submit_executor

run_chunks_with_submit_executor(executor: SubmitExecutor, worker_fn: Callable[[list[T]], R], chunks: Sequence[list[T]], desc: str = 'Processing chunks', on_poll: Callable[[], None] | None = None, poll_interval: float = 1.0) -> list[R]

Dispatch worker_fn over each of chunks via any SubmitExecutor (e.g. loky or mpi4py.futures.MPIPoolExecutor), returning one result per chunk in the same order as chunks (not completion order).

Progress is reported per completed chunk via wait() with FIRST_COMPLETED, allowing an optional on_poll() callback to be invoked periodically (every poll_interval seconds) even before chunks complete. If on_poll is None, uses the original as_completed pattern for efficient blocking (no polling overhead).