Parallel Execution¶
LoQS can parallelize both shots within a single
QuantumProgram and whole programs across a batch (e.g.
many error-injected variants, or many circuits in a GST experiment design).
This requires the parallel optional dependency group (pip install -e
".[parallel]"), which provides loky for
single-node parallelism and
submitit for SLURM-array
fan-out; the separate mpi extra (pip install -e ".[mpi]") adds mpi4py for
multi-node parallelism via an existing MPI installation. The diagrams below
also need matplotlib, via the visualization extra (pip install -e
".[visualization]").
Two axes of parallelism¶
There are two independent things that can be parallelized, and either, both, or neither can be active at once:
- Shots, within one
QuantumProgram. Controlled directly byQuantumProgram.run()'sshot_executorparameter -- shots of that one program are dispatched across the executor's workers instead of running one at a time in the calling process. - Programs, across a whole batch. Every program-level call site --
EdesignRunner(oneQuantumProgramper edesign circuit, configured via its ownparallel_strategyfield),FaultInjectionRunner(one per error-injected variant), andNoiseSweepRunner.run()(one per sweep point) -- accepts aParallelStrategyinstead of a single executor. The batch is split into chunks, and each chunk (a sub-list of programs) is built/run/collected as a unit by one worker.
These compose: a ParallelStrategy can dispatch chunks
of programs to outer workers (e.g. one per node), each of which then runs its
own chunk's shots through an inner shot-level executor (e.g. one per core) --
programs distributed across nodes, shots distributed across cores within a
node, exactly the hybrid shape a real HPC allocation usually wants. A single
flat shot_executor (no chunking) and a single flat program_executor (no
shot nesting) are just the two degenerate cases of this same design.
Three concrete backends fill these roles, but not interchangeably -- each
satisfies a different structural protocol (see
SubmitExecutor/MapArrayExecutor),
which determines where it can be plugged in:
| Backend | Protocol | Can be shot_executor? |
Can be program_executor? |
Multi-node? |
|---|---|---|---|---|
loky.get_reusable_executor() |
SubmitExecutor |
Yes | Yes | No (single node) |
mpi4py.futures.MPIPoolExecutor |
SubmitExecutor |
Yes | Yes | Yes |
submitit.AutoExecutor |
MapArrayExecutor (and SubmitExecutor) |
No | Yes | Yes (SLURM) |
submitit's whole value is its bulk map_array submission (one sbatch call
covering an entire batch of chunks);
QuantumProgram.run()'s shot_executor only ever
dispatches one .submit() call per shot, so a submitit.Executor is never
used as shot_executor in practice even though it technically satisfies
SubmitExecutor too.
ParallelStrategy in detail¶
ParallelStrategy (loqs.tools.paralleltools) is a
small dataclass, reused identically by every program-level call site:
program_executor: dispatches chunks, auto-selecting one.submit()call per chunk vs. a bulk.map_array()call depending on which protocol it satisfies. It also accepts anExecutorSpec(ExecutorSpec.submitit()orExecutorSpec.mpi4py()) or a zero-argument factory, called once and cached; a spec is stored as data and a factory as source (see thesubmititsection below for checkpointing with either).n_program_chunks: how many round-robin chunks to split the batch into.shot_executor: nested shot-level parallelism. A live executor can't normally cross the process boundary each dispatched chunk crosses onceprogram_executoris also set, but a recognized backend (currentlyloky) is auto-converted into a picklable factory built from its own parameters -- no factory function needs to be written by hand. An unrecognized backend still requiresExecutorSpec.mpi4py()(for MPI) or an explicit zero-argument factory callable instead.
ParallelStrategy.describe() prints a quick,
per-axis text summary of a configuration (backend, chunk/worker counts) before
running anything. ParallelStrategy.plot() draws
the same configuration as a worker/chunk/shot diagram instead. The examples
below show both before each run -- see their API reference entries (linked
above) for the exact fields/diagram elements each one produces.
See the ParallelStrategy API reference for the full
field-by-field details and validation rules.
Build a program¶
from loqs.codepacks import codepack_trivial_counter as trivial_codepack
from loqs.core import QuantumProgram
trivial_code = trivial_codepack.create_qec_code()
ideal_model = trivial_codepack.create_ideal_model(["Q0"])
# A trivial program: initialize a patch and a counter, then increment the
# counter once. Every shot should report a final counter value of 1.
stack = [
{"instruction": "Init Patch Trivial", "new_patch_label": "L0", "qubits": ["Q0"]},
{"instruction": "Init Counter", "patch_label": "L0", "initial_value": 0},
{"instruction": "Increment", "patch_label": "L0", "increment_by": 1},
]
program = QuantumProgram(
stack,
default_noise_model=ideal_model,
patch_types={"Trivial": trivial_code},
default_base_seed=0,
)
Single-node parallelism (loky)¶
loky is the right default choice for a single machine: it needs no
external services, and it falls back to cloudpickle whenever plain
pickle fails, which real LoQS Instruction objects need (many are
built as closures, which plain pickle cannot serialize at all).
Shot-level¶
Pass a loky.get_reusable_executor() instance as shot_executor to
QuantumProgram.run() directly -- no ParallelStrategy
needed here, since there's only one axis in play.
import loky
# 4 worker processes share this one program's 20 shots.
executor = loky.get_reusable_executor(max_workers=4)
results = program.run(num_shots=20, shot_executor=executor, verbose=False)
len(results.shot_histories)
Omitting shot_executor (the default) runs shots serially in the calling
process, exactly as before.
Program-level¶
Build several programs (here, just repeated copies of the same one for
illustration) and pass a ParallelStrategy instead of a
single executor. The batch is split into n_program_chunks round-robin chunks
(so cost drift across the batch, e.g. later GST circuits typically being
deeper, doesn't concentrate onto a few workers), and each chunk is processed as
a unit by one worker.
from loqs.tools import fttools
from loqs.tools.paralleltools import ParallelStrategy
programs = [program] * 6
strategy = ParallelStrategy(
program_executor=loky.get_reusable_executor(max_workers=2),
n_program_chunks=2,
)
print(strategy.describe(programs, num_shots=1))
strategy.plot(programs)
failed = fttools.FaultInjectionRunner(
programs,
collect_shot_data_args=[("counter", -1)],
expected_outcomes=[1],
num_shots=1,
parallel_strategy=strategy,
).run()
len(failed)
Hybrid (both axes)¶
ParallelStrategy.shot_executor nests shot-level parallelism inside
program-level parallelism. A plain live loky executor works directly here,
just like the shot-level example above -- ParallelStrategy auto-converts it
into a picklable factory built from its own parameters (see ParallelStrategy
in detail above), so no factory function needs to be written by hand.
strategy = ParallelStrategy(
program_executor=loky.get_reusable_executor(max_workers=2), # outer: programs
n_program_chunks=2,
shot_executor=loky.get_reusable_executor(max_workers=2), # inner: shots
)
print(strategy.describe(programs, num_shots=20))
strategy.plot(programs)
failed = fttools.FaultInjectionRunner(
programs,
collect_shot_data_args=[("counter", -1)],
expected_outcomes=[1],
num_shots=20,
parallel_strategy=strategy,
).run()
len(failed)
Multi-node and hybrid parallelism¶
The examples above all ran on a single machine. The sections below combine a
multi-node backend (submitit or mpi4py) with the single-node loky axis
from above, for the full node/core hybrid shape a real HPC allocation usually
wants.
Multi-node programs via submitit (for SLURM/HPC)¶
submitit targets a scheduler-based multi-node shape:
submitit.AutoExecutor's map_array submits a single sbatch job array
covering an entire batch of chunks at once (one sbatch call, not one per
chunk), and each array task runs as its own independent SLURM allocation.
submitit.Executor only ever plugs in as program_executor (see the backend
table above) -- never as shot_executor -- since its value is specifically
that bulk map_array submission.
cluster="local" below runs the exact same code path through ordinary
subprocesses rather than real sbatch calls, so it works without a real
scheduler; swap in real slurm_* parameters (via
executor.update_parameters(...)) to target an actual cluster.
submitit itself only supports Linux/macOS: it unconditionally registers a
SIGCONT handler for every job it runs, a POSIX-only signal that doesn't
exist in Windows's signal module at all (a real, unconditional upstream
limitation, unsurprising given submitit targets SLURM, a Linux-only
scheduler). The cells below still build and describe()/plot() a
submitit-backed ParallelStrategy on every platform,
but skip actually dispatching it on Windows.
import sys
import submitit
# cluster="local" runs each chunk as an ordinary subprocess instead of a
# real sbatch job, so this works without an actual SLURM allocation.
strategy = ParallelStrategy(
program_executor=submitit.AutoExecutor(
folder="submitit-logs", cluster="local"
),
n_program_chunks=2,
)
if sys.platform == "win32":
print("submitit does not support Windows -- skipping dispatch.")
else:
failed = fttools.FaultInjectionRunner(
programs,
collect_shot_data_args=[("counter", -1)],
expected_outcomes=[1],
num_shots=1,
parallel_strategy=strategy,
).run()
print(f"{len(failed)} failed")
The real hybrid shape a cluster allocation usually wants combines submitit
with the single-node loky axis above: submitit fans each chunk out to its
own node-level SLURM allocation, and each of those chunks then runs its own
shots across a loky pool local to that allocation -- programs distributed
across nodes, shots distributed across cores within a node, via the same
auto-converted shot_executor mechanism used in the one-node hybrid above.
# Same idea as the one-node hybrid above, but the outer (program) axis is
# now a SLURM array via submitit instead of a local loky pool.
strategy = ParallelStrategy(
program_executor=submitit.AutoExecutor(
folder="submitit-logs", cluster="local"
),
n_program_chunks=2,
shot_executor=loky.get_reusable_executor(max_workers=2),
)
print(strategy.describe(programs, num_shots=20))
strategy.plot(programs, program_workers=2)
if sys.platform == "win32":
print("submitit does not support Windows -- skipping dispatch.")
else:
failed = fttools.FaultInjectionRunner(
programs,
collect_shot_data_args=[("counter", -1)],
expected_outcomes=[1],
num_shots=20,
parallel_strategy=strategy,
).run()
print(f"{len(failed)} failed")
On a real cluster, submitit.Executor's own slurm_* parameters (e.g.
cpus_per_task) should be sized to match the inner loky pool's own
max_workers, so each array task actually gets the cores its own nested
executor tries to use.
To checkpoint a submitit run, pass program_executor an
ExecutorSpec.submitit() rather than a live
executor, since LoQS can't rebuild a submitit.AutoExecutor from its own
state:
from loqs.tools.paralleltools import ExecutorSpec
strategy = ParallelStrategy(
program_executor=ExecutorSpec.submitit(
"submitit-logs", timeout_min=30, slurm_partition="short"
),
n_program_chunks=8,
)
runner = fttools.FaultInjectionRunner(
programs,
parallel_strategy=strategy,
config=CheckpointConfig(item_checkpoint_dir="checkpoints"),
...,
)
The spec stores the folder (as an absolute path), cluster and parameters as
data, so it works from a notebook, a script's __main__ or a module, and a
resume from the runner file rebuilds the same executor.
For a backend LoQS doesn't know, pass a zero-argument factory instead. It is
stored as source in the runner file, so define it at module level in a .py
file, with its imports and settings in its body:
def make_executor():
from concurrent.futures import ProcessPoolExecutor
return ProcessPoolExecutor(max_workers=4)
strategy = ParallelStrategy(
program_executor=make_executor,
n_program_chunks=8,
)
Multi-node parallelism via MPI¶
mpi4py.futures.MPIPoolExecutor is a real concurrent.futures.Executor
subclass, so it's a drop-in SubmitExecutor -- it can be used exactly where a
loky executor was used above, as either shot_executor or
program_executor, with no LoQS-side code needing to know which backend is
actually running. A shared pool of MPI ranks (potentially spanning many nodes)
pulls submitted tasks from a queue as they finish, giving genuine dynamic load
balancing rather than a fixed upfront assignment.
This requires the mpi extra (pip install -e ".[mpi]") plus a working MPI
installation (e.g. OpenMPI/MPICH) already present in the environment -- pip
install alone does not provide one, and neither is available in this Binder/CI
environment, so none of the examples below are actually run here.
Shot-level, parallelizing across MPI ranks instead of loky workers:
from mpi4py.futures import MPIPoolExecutor
# Same call as the loky shot-level example above, just backed by MPI
# ranks (potentially spanning many nodes) instead of local processes.
with MPIPoolExecutor() as executor:
results = program.run(num_shots=20, shot_executor=executor)
Program-level, chunking the batch across MPI ranks the same way loky
did above:
with MPIPoolExecutor() as executor:
strategy = ParallelStrategy(program_executor=executor, n_program_chunks=3)
print(strategy.describe(programs, num_shots=1))
# program_workers is given explicitly since it depends on how many
# ranks mpiexec -n N actually launched with, not something knowable
# from the executor object alone ahead of time.
strategy.plot(programs, program_workers=3)
failed = fttools.FaultInjectionRunner(
programs,
collect_shot_data_args=[("counter", -1)],
expected_outcomes=[1],
num_shots=1,
parallel_strategy=strategy,
).run()
A live MPIPoolExecutor can't be stored in a runner file, so a checkpointed
MPI run passes ExecutorSpec.mpi4py() (the
MPIPoolExecutor keyword arguments, such as max_workers) as
program_executor. The pool is built once, on first use, and lasts until the
process exits.
MPIPoolExecutor is typically launched as one atomic multi-node allocation
(mpiexec -n N, one reservation covering every rank up front) -- a real
environment dependency beyond what loky needs, but normally already provided
via the module system on real HPC systems.
For completion, MPI can nest with loky the same way submitit did above:
program_executor chunks the batch across MPI ranks (potentially spanning many
nodes), and each rank's chunk then runs its own shots across a local loky
pool, auto-converted from a plain live executor the same way as above.
with MPIPoolExecutor() as executor:
# Outer axis: MPI ranks, potentially spanning many nodes. Inner axis:
# a local loky pool per rank's own chunk of programs.
strategy = ParallelStrategy(
program_executor=executor,
n_program_chunks=3,
shot_executor=loky.get_reusable_executor(max_workers=2),
)
print(strategy.describe(programs, num_shots=20))
strategy.plot(programs, program_workers=3)
failed = fttools.FaultInjectionRunner(
programs,
collect_shot_data_args=[("counter", -1)],
expected_outcomes=[1],
num_shots=20,
parallel_strategy=strategy,
).run()
Thread-oversubscription safety¶
Every worker (shot-level or program-level, on any backend above) pins its
own BLAS/OpenMP thread pools to one thread via threadpoolctl before
running, regardless of how many workers are active at either axis. This
avoids oversubscription -- N worker processes each independently trying
to use every available core for BLAS operations, which would otherwise
make a parallel run slower than serial rather than faster, and matters
more, not less, once both axes are combined (as in the hybrid examples
above).
Checkpointing under parallelism¶
The Basic Workflow tutorial introduces
QuantumProgram.run()'s checkpoint_batch_size/
checkpoint_dir for the serial case. With a shot_executor,
checkpoint_batch_size also sets how many shots are dispatched to one
worker per call: each worker computes its whole batch, writes all of it to
a new payload file of its own (named after that worker's own ID and the
batch's first shot, so concurrent workers never open the same file), marks
those shots done in its own progress ledger, and only then returns. The
ledger is an HDF5 single-writer/multiple-reader (SWMR) file, so
MultiProgramRunner can poll it for live shot progress while the worker
keeps writing. (MultiProgramRunner's Shots bar itself reads in-flight
shots from each worker's item ledger, so it needs item checkpointing only,
not shot checkpointing, and it counts each item's own shot count, a
num_shots in run_kwargs included.) Once every dispatched batch is confirmed done,
run() runs one race-free, driver-side pass that streams every payload into the same
canonical results.h5 a serial run would have written directly, then
deletes the payloads and ledgers -- callers never need to touch the
per-worker files themselves. Each payload references the parent program
stored once in results.h5 rather than embedding its own copy.
The progress ledgers' SWMR mode relies on the file system preserving POSIX
write ordering while a ledger is being written. Only live progress reads
depend on that ordering. Results, resume and consolidation read only each
ledger's root group, to tell it from a data file, and take every result from
the payload files, which each worker closes before marking its shots done.
So on an NFS or SMB (Windows network) share the risk is live progress that
stalls or shows wrong counts, not wrong results. For reliable live progress,
keep checkpoint directories, for both QuantumProgram.run() and
MultiProgramRunner, on a local disk or a parallel file system such as
Lustre or GPFS.
Checkpointing needs process-based executors: loky,
concurrent.futures.ProcessPoolExecutor, submitit or mpi4py.futures, and
refuses a concurrent.futures.ThreadPoolExecutor (or a subclass) with a
ValueError. That applies to shot_executor when shots are checkpointed,
and to a runner's program_executor when items or shots are, whether the
executor is given live or built by a factory. With a thread executor, a
worker thread's ledger open fails while the driver's poll holds a reader of
that ledger, and threads that share one held ledger race when they grow it.
Threads don't speed up shots anyway, since shots run under the GIL.
import tempfile
from loqs.core import ProgramResults
with tempfile.TemporaryDirectory() as checkpoint_dir:
results = program.run(
num_shots=20,
shot_executor=executor,
checkpoint=True,
checkpoint_batch_size=5,
checkpoint_dir=checkpoint_dir,
verbose=False,
)
print(f"in-memory shots right after run(): {len(results.shot_histories)}")
print(f"wall-clock times available: {len(results.shot_wall_clock_times)}")
# The consolidated checkpoint is an ordinary, single-writer checkpoint,
# readable the same way regardless of how many workers wrote it.
recovered = ProgramResults()
recovered.load_checkpoint(checkpoint_dir=checkpoint_dir)
print(f"shots recovered from disk: {len(recovered.shot_histories)}")
Since each worker computes its whole batch before writing anything, a
crash loses at most one worker's own in-flight batch (up to
checkpoint_batch_size shots from that one worker, not the whole run) --
set it to 1 to checkpoint every shot as soon as it's computed, trading
batching efficiency for the finest possible durability.
The 0 above isn't a bug: a checkpointed run evicts each shot from the
returned ProgramResults's own in-memory
shot_histories as soon as it's durably checkpointed, so run()'s return
value holds only the yet-unwritten tail. The shots read back through
get_shot_history, collect_shot_data or load_checkpoint() as above.
Note that shot_wall_clock_times is not evicted -- it stays fully
populated in memory.
Resuming after a crash¶
A checkpointing-enabled run() also supports genuine resume, regardless of whether the original call used a shot_executor: calling run() again with checkpoint=True, resume=True against the same checkpoint_dir only computes whatever wasn't already durably checkpointed, rather than starting over from shot 0.
- A race-free consolidation pass into
results.h5runs whenever any payload files exist, even if the resuming call itself dispatches serially, so a parallel run that crashed mid-batch can always be finished off with a plain serial call. It then deletes the merged payloads, the progress ledgers and any orphanedworker_*.h5.tmpfiles. A delete that fails (for example on a file another process still holds) warns and leaves that file in place, sorun()can return with a stray file left behind. - Checkpoint writes are crash-safe: payload files and the
results.h5snapshot are written to a temporary file and renamed into place, and a serial append toresults.h5counts only once it's committed, so a resume never reads a half-written shot. - A resume that finds a damaged checkpoint file raises
CheckpointReadError(aRuntimeError) naming it, rather than silently recomputing its shots. - If any shot is still missing at the end,
run()raises aRuntimeErrornaming the missing shots rather than returning an incomplete result.
with tempfile.TemporaryDirectory() as resume_checkpoint_dir:
partial = program.run(
num_shots=10,
shot_executor=executor,
checkpoint=True,
checkpoint_batch_size=5,
checkpoint_dir=resume_checkpoint_dir,
verbose=False,
)
print(f"shots after first call: {len(partial.collect_shot_data('counter', -1))}")
# Finishing off with more shots than originally planned: num_shots
# differs from the original call, so force_resume=True is needed to
# bypass the mismatch check -- the 10 already-checkpointed shots are
# kept as-is, and only the remaining 10 are actually computed.
finished = program.run(
num_shots=20,
shot_executor=executor,
checkpoint=True,
resume=True,
force_resume=True,
checkpoint_batch_size=5,
checkpoint_dir=resume_checkpoint_dir,
verbose=False,
)
print(f"shots after resuming call: {len(finished.collect_shot_data('counter', -1))}")
If a resuming call's own num_shots/max_frame_limit/RNG seed happen to exactly match the original call, no mismatch is detected and force_resume isn't needed at all.
This mechanism is scoped to QuantumProgram/ProgramResults's own
shot-level checkpointing. The program-level call sites (EdesignRunner,
FaultInjectionRunner, and
NoiseSweepRunner.run()) use a separate, unified item-level
checkpoint mechanism with per-worker HDF5 payload files, crash recovery, and per-item completion tracking.
Watching workers live with loqs-monitor¶
The loqs-monitor console script shows what each worker of a running program-level job is doing: its host and pid, its state, the item it is on, the items it has finished, its shot progress, and how long since it last reported. Install it with the parallel extra (pip install "loqs[parallel]"), which brings in rich for the live table. The plain-text --once snapshot needs no rich.
loqs-monitor /scratch/run/item_checkpoints # live table
loqs-monitor --once /scratch/run/item_checkpoints # one plain snapshot
Directory: /scratch/run/item_checkpoints
Workers: 1 starting, 1 running, 1 idle, 0 stale
Hosts: 2
Run items done/total (all items): 7/10
Run shots done/total (all items): 740/1000
host pid state current item items done shots done/total no update in
node01 41233 running 7 4 40/100 2s
node01 41234 idle - 3 - 5s
node02 9912 starting - 0 - -
The run-level items line counts the items finished out of all the run's items, including those done before a resume. The run-level shots line counts the shots of all the run's items, finished plus in flight, out of the run's total. Neither drops as a worker finishes an item and moves on in live mode, and --host doesn't narrow either. Both show "total unknown" when the run was started by an older LoQS or when no worker ledgers are present (not started yet, or finished). The shots line also shows it when the runner has no shot count (no num_shots) or its items run different counts (a per-item num_shots callable in run_kwargs). The rows' items done columns are separate: they count each worker's own done marks.
On a many-host run, --by-host collapses the table to one row per host (worker counts per state, items done, the active shots column, and the longest time since a running or stale worker reported). The active shots column covers only that host's in-flight items. --host PATTERN limits the view to hosts matching a shell-style glob. --host can be repeated, and both flags work in live and --once modes and combine. Matching is case-sensitive, so --host 'NODE*' does not match node01. With --host, the summary adds a Showing N of M hosts line.
loqs-monitor --once --by-host --host 'node0*' --host gpu01 /scratch/run/item_checkpoints
The monitor needs item checkpointing, turned on by CheckpointConfig(item_checkpoint_dir=...), and must run where that directory is visible, e.g. on a login node of the shared file system. It may be started before the run creates the directory; live mode then shows a note and keeps polling.
Each worker writes one SWMR ledger, worker_<host>_<pid>_<suffix>_runner.h5, in item_checkpoint_dir (the name is the worker identity, hostname_pid_suffix). It holds the current item index, the done item indices, item_shots_done/item_shots_total and last_heartbeat, written at most once per second. The ledgers are consolidated away when the run ends, so a finished run shows no workers.
The run also writes a small run_progress.json in the same directory at dispatch start (the number of items already done, the items it will compute and the shots per item), and removes it after a successful run. It is for display only, and it is what gives both run-level lines their totals.
A worker is starting before it has begun an item, running while it works on one, idle between items, and stale when it is running but has made no progress for longer than --stale-after (default 120 seconds; stale rows are shown in red in the live table). The options are:
--interval: seconds between polls in live mode (default 2.0).--stale-after: seconds without a change before a running worker counts as stale. Idle and starting workers never go stale.--once: print one snapshot and exit. It returns 0 if the directory exists and 2 if it doesn't.
Some caveats on reading the output:
- The heartbeat advances only at item start and when shots complete (once per completed batch under a
shot_executor, and at most once per second). A healthy worker therefore shows a growing "no update in" without being dead while it is inside one very long shot or batch, and also while it builds the program, loads a resumed checkpoint, consolidates after its last shot, reduces, and writes its payload.--stale-aftermust exceed the longest of these gaps, not only the longest gap between shot or batch completions. --oncehas no poll history, so its ages come from heartbeats and can be off by the clock difference between the worker's node and the monitor's. Live mode measures age on the monitor's own clock once it has seen a change.- Shot counts are shots computed, not shots durably checkpointed.
- Worker ledgers are consolidated and deleted only after a dispatch succeeds. When you resume an interrupted run, the interrupted run's ledgers stay in the directory for the whole resumed run. The monitor shows those workers as stale (if they were killed mid-item) or idle, with hours-old ages, counts them in the worker totals, and
--by-hosthighlights their hosts. Their pids and ages tell them apart from the resumed run's workers. A killed worker's done items count once in the run-level shots line, and the item it was on shows its last shot count until a live worker passes it. - With item checkpointing on, a user
progress_callbackinrun_kwargsmust be a module-leveldef, not a builtin such asprint, afunctools.partialor a callable instance. Those are rejected before dispatch. A locallambdapasses that check, but it is serialized as its call-site source line, so it may not surviveRunner.read(), and under parallel dispatch the callback runs in the item worker, so driver-side side effects are lost.
Performance profiling¶
profile_strategies measures real wall-clock time -- and, whenever psutil
is installed, peak memory and CPU utilization -- for a caller-chosen set of
ParallelStrategy configurations against a
caller-chosen working example. Deciding between candidate configurations (how
many outer/inner workers, which backend, how to split workers between the two
axes) is a real, workload-dependent question -- this measures it directly on
real hardware rather than guessing.
The trivial toy program used elsewhere in this tutorial does too little real
work per shot to show a meaningful difference between configurations. The
cells below build a small, real workload instead: single-Pauli error
injection into the [[5,1,3]] code's FT Minus Prep stage, the same one used
in the Testing Fault Tolerance tutorial.
from loqs.backends import QSimQuantumState
from loqs.codepacks import codepack_5_1_3_quantinuum2022 as codepack_5_1_3
code_5q = codepack_5_1_3.create_qec_code()
ft_qubits = ["A0", "A1"] + [f"D{i + 2}" for i in range(5)]
ft_ideal_model = codepack_5_1_3.create_ideal_model(ft_qubits)
stack_ft = [
{"instruction": "Init State", "state": len(ft_qubits), "qubit_labels": ft_qubits},
{"instruction": "Init Patch 5Q", "new_patch_label": "L0", "qubits": ft_qubits},
("FT Minus Prep", "L0"),
("Flagged QEC", "L0"),
("FT Logical X Measure", "L0"),
]
ft_program = QuantumProgram(
stack_ft,
default_noise_model=ft_ideal_model,
state_type=QSimQuantumState,
patch_types={"5Q": code_5q},
name="FT Prep -, Flagged QEC, FT measure X",
)
# 8 of the 171 possible single-Pauli-error variants of "FT Minus Prep",
# enough to give a program-level pool real, evenly-splittable work.
ft_programs = fttools.build_discrete_error_injection_programs(
base_program=ft_program,
instruction_to_analyze=code_5q.instructions["Non-FT Minus Prep + Checks"],
stack_idx_to_modify=2,
error_circuit_labels=["Gxpi", "Gypi", "Gzpi"],
)[:8]
len(ft_programs)
Comparing worker shapes¶
The same total workers can be split between the two axes in different ways --
all program workers, all shot workers, or some balance of both -- dispatching
the exact same computation with a different shape. describe()/plot()
sanity-check a shape before running anything, without needing to actually
dispatch it:
ParallelStrategy(program_executor=..., shot_executor=...) normally takes a
live executor directly for either axis (see above) -- but
loky.get_reusable_executor() is a process-wide singleton, not one pool
per max_workers value: calling it again with a different max_workers
resizes the same underlying pool in place, silently changing what any
earlier reference to it now points to. Building executors of genuinely
different sizes side by side (as the shapes below do) hits this directly;
passing an explicit ExecutorSpec instead sidesteps it
entirely, since it doesn't touch a live pool at all until it's actually
called (inside a worker subprocess, where no such collision can occur).
from loqs.tools.paralleltools import ExecutorSpec
for program_workers, shot_workers in [(4, 1), (2, 2), (1, 4)]:
shape_strategy = ParallelStrategy(
program_executor=ExecutorSpec("loky", {"max_workers": program_workers}),
n_program_chunks=program_workers,
shot_executor=ExecutorSpec("loky", {"max_workers": shot_workers}),
)
print(shape_strategy.describe(ft_programs, num_shots=20))
shape_strategy.plot(ft_programs)
Whether splitting workers onto the shot axis actually helps is workload
dependent, not automatic: QuantumProgram.run()
dispatches one .submit() call per shot, unbatched, so each shot pays a real
serialization/IPC cost to cross into a worker process. For a workload whose
per-shot compute is itself fast (like this one), that per-shot cost can
outweigh the benefit -- the program axis, which amortizes one dispatch over
an entire chunk of programs, is usually the more reliable one to reach for
first. The measurement below sticks to program-axis splits for this reason.
import os
from loqs.tools.paralleltools import (
format_profile_table,
plot_profile_results,
profile_strategies,
)
def profile_work(strategy):
return fttools.FaultInjectionRunner(
ft_programs,
collect_shot_data_args=[("logical_measurement", -1)],
expected_outcomes=[1],
num_shots=20,
parallel_strategy=strategy,
).run()
strategies = {
"serial": ParallelStrategy(),
"program-2x": ParallelStrategy(
program_executor=ExecutorSpec("loky", {"max_workers": 2}),
n_program_chunks=2,
),
"program-4x": ParallelStrategy(
program_executor=ExecutorSpec("loky", {"max_workers": 4}),
n_program_chunks=4,
),
}
# Timing-sensitive on a small/shared CI runner (which sets CI=true) --
# skip the live measurement there and just show how it's called.
if os.environ.get("CI"):
print("Skipping the live profiling sweep in CI -- run interactively instead.")
results = None
else:
results = profile_strategies(
profile_work, strategies, repeats=2, sample_interval=0.05, warmup=True
)
print(format_profile_table(results))
warmup=True runs one throwaway pass through each strategy's dispatch path
before the timed repeats loop, so real worker-process startup/import cost
doesn't land on whichever repeat happens to run first. Since "serial" is
fully serial, every other row also reports a speedup relative to it. On
real hardware, splitting this same workload across worker counts like this
typically shows real, if sub-linear, speedup (e.g. roughly 1.6x-1.9x at 2
workers, 2.1x-2.8x at 4 workers, relative to the serial baseline) -- workers
beyond the first pay real, if smaller, marginal overhead of their own, so
returns diminish rather than scaling linearly.
Every result's raw per-chunk data (peak memory, mean CPU%, sample count) is
kept, not just the summary numbers above -- plot_profile_results draws a
wall-time bar chart plus box plots of that per-chunk resource data directly.
if results is not None:
plot_profile_results(results);
Profiling a submitit sweep on a real SLURM allocation¶
Comparing several submitit-backed configurations the way profile_strategies
does above would normally mean each candidate strategy's own dispatch
independently submits (and queues for) its own sbatch job -- exactly the
"stuck behind someone else's job" risk a real profiling sweep wants to avoid.
reuse_slurm_allocation=True sidesteps this: it installs a small wrapper
script that intercepts every sbatch call submitit makes during the sweep,
running it directly against whatever real SLURM allocation the current
process is already inside (obtained separately first, e.g. via salloc or an
enclosing sbatch job) instead of requesting a new one each time. Requires
already running inside a real allocation (SLURM_JOB_ID set); not runnable in
this Binder/CI environment, so not executed here.
# Obtain one allocation sized for the largest candidate strategy first, e.g.
# salloc --nodes=4 --ntasks-per-node=1 --cpus-per-task=8
# then, from inside that shell:
results = profile_strategies(
profile_work, strategies, reuse_slurm_allocation=True
)