distribute-inversion
Distribute an existing single-process PyLops workflow over MPI with PyLops-MPI - choose what to split (blocks, sources, frequencies, a spatial axis), map operators to MPIBlockDiag / MPIVStack / MPIHStack / stacked and derivative operators, build DistributedArrays with the right partition (SCATTER vs BROADCAST) and local shapes, dot-test, solve with pylops_mpi solvers (cgls, cg, ista, fista), and run with mpiexec, optionally on GPUs with CuPy/NCCL. Use when the user says "my PyLops inversion does not fit in memory / is too slow on one node", "parallelise this over shots / frequencies with MPI", "port this to pylops-mpi".
- License 许可
- LGPL-2.1
- 最近更新
- 2026-11-02
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- distribute-inversion
- description
- Distribute an existing single-process PyLops workflow over MPI with PyLops-MPI - choose what to split (blocks, sources, frequencies, a spatial axis), map operators to MPIBlockDiag / MPIVStack / MPIHStack / stacked and derivative operators, build DistributedArrays with the right partition (SCATTER vs BROADCAST) and local shapes, dot-test, solve with pylops_mpi solvers (cgls, cg, ista, fista), and run with mpiexec, optionally on GPUs with CuPy/NCCL. Use when the user says "my PyLops inversion does not fit in memory / is too slow on one node", "parallelise this over shots / frequencies with MPI", "port this to pylops-mpi".
02 资源文件 1
- 脚本reference/mpi_template.py4.2 KB
03 SKILL.md 正文
Goal: an MPI version of the user's PyLops script that gives the same result as
the serial one on a small case, scales to their real size, and is launched with
mpiexec. Do not modify the installed pylops / pylops_mpi packages.
0. Check the environment
- Use the project's Python runner. Check versions:
python -c "import pylops, pylops_mpi, mpi4py; print(pylops.__version__, pylops_mpi.__version__, mpi4py.__version__)"and that an MPI implementation is available (mpiexec --version). - PyLops-MPI changes quickly (new operators and solvers every release): inspect
the installed API (
help(pylops_mpi.MPIBlockDiag),dir(pylops_mpi)) rather than relying on memory. Keeppylops,pylops_mpiandpyproximalversions mutually compatible (released versions from the same period); mixing a development checkout of one with a release of another can break imports or solvers. - Installing: MPI itself first (conda
openmpi/mpichrecommended), thenpip install pylops-mpi;mpi4py-fftfor the distributed FFTs. Ask before installing, and ask before launching MPI jobs on the user's machine (they may prefer to run them on a cluster/CI).
1. Decide what to distribute
Read the serial script and find the natural split:
| Structure of the serial problem | Pattern | PyLops-MPI |
|---|---|---|
independent sub-problems yᵢ = Aᵢ xᵢ (e.g. post-stack inversion per inline, per frequency with no coupling) |
block diagonal | MPIBlockDiag(ops=[Aᵢ]) – model and data SCATTER |
one model, data in blocks yᵢ = Aᵢ x (shots in LSM/FWI-like, receivers, time windows) |
vertical stack | MPIVStack(ops=[Aᵢ]) – model BROADCAST, data SCATTER |
several models summed into one data y = Σ Aᵢ xᵢ (e.g. blended sources) |
horizontal stack | MPIHStack(ops=[Aᵢ]) – model SCATTER, data BROADCAST |
| large dense matrix | distributed matmul | MPIMatrixMult(A_local, M, kind="summa" or "block") |
| operator already written for full arrays, identical on all ranks | replicated | asmpilinearoperator(Op) / MPILinearOperator(Op) – BROADCAST |
| regularisation coupling the split axis | derivatives with halo exchange | MPIFirstDerivative, MPISecondDerivative, MPILaplacian, MPIGradient, MPIHalo |
| data + regularisation terms | stacking MPI operators | MPIStackedVStack([Op, eps * Reg]) with StackedDistributedArray([y, zeros]) |
| MDC / Fredholm over frequencies, FFTs | specialised | pylops_mpi.waveeqprocessing.MPIMDC, pylops_mpi.signalprocessing.MPIFredholm1, MPIFFT2D, MPIFFTND, MPINonStationaryConvolve1D |
Each rank builds only its own blocks (its shots, frequencies, slices):
split the index range with from pylops_mpi.DistributedArray import local_split
(local_split(global_shape, comm, Partition.SCATTER, axis)) or explicit
rank * n : (rank + 1) * n slicing, and load only the corresponding data.
2. Build arrays with the right partition
DistributedArray(global_shape, partition=Partition.SCATTER|BROADCAST, axis=0, local_shapes=..., dtype=...), fill each rank's part withx[:] = local_values; orDistributedArray.to_dist(full_array, partition=...)when the full array exists (small cases).- Match the partition to the operator (table above); a mismatch raises
ValueErroror silently re-distributes data. - For SCATTER arrays, pass
local_shapes=Op.local_shapes_m(model) /Op.local_shapes_n(data) fromMPIBlockDiag/MPIVStackso each rank's local size matches its blocks; the default even split only matches when blocks have equal size. - Writing to a BROADCAST array broadcasts rank 0's values to all ranks.
x0is required bypylops_mpisolvers and must have the model partition (x0 = x.zeros_like()or a DistributedArray filled with the starting model).
3. Write the script
Adapt reference/mpi_template.py (both the block-diagonal and the stacked
patterns are there):
- one script run by every rank;
rank = MPI.COMM_WORLD.Get_rank(); - dot-test with
pylops_mpi.utils.dottest(Op, u, v, nr, nc)whereu,vare DistributedArrays with the model/data partitions; - solvers:
pylops_mpi.cgls(Op, y, x0, niter, damp, tol)→(x, istop, iiter, r1norm, r2norm, cost),pylops_mpi.cg(Op, y, x0, niter, tol)→(x, iiter, cost); sparsitypylops_mpi.ista/pylops_mpi.fista(recent versions) withpylops_mpi.optimization.eigs.power_iterationfor the step; proximal solvers inpylops_mpi.proximal(recent versions); - collective calls (
asarray(),norm(),dot(), solvers, operator applications) must be executed by all ranks; guard only printing, plotting and file writing withif rank == 0:; - gather to rank 0 (
x.asarray()) only for final output and small cases; for large models write per-rank files or use parallel I/O; - keep the serial script: compare results on a small case (template's
serial_check).
4. GPUs (optional)
- CuPy: create the local operators with CuPy arrays,
DistributedArray(..., engine="cupy"), and bind one GPU per rank (cp.cuda.Device(rank % ndev).use()). - NCCL for GPU-to-GPU communication: create the communicator with
pylops_mpi.utils._nccl.initialize_nccl_comm()(private module – check the installed docs/examples for the current entry point) and passbase_comm_nccl=...to DistributedArrays;NCCL_PYLOPS_MPI=0disables it. Check the PyLops-MPI GPU page for which operators support NCCL.
5. Run and verify
- Run with
mpiexec -n <N> python script.py(on a cluster, the scheduler's launcher, e.g.srun). Start with-n 2on a small case, compare with the serial run, then scale. If the user asked not to run MPI jobs locally, do only static checks (python -m py_compile, API inspection) and give them the command to run. - Timing:
from pylops_mpi.utils.benchmark import benchmark, mark(decorator@benchmark,mark("label")inside it) in recent versions, orMPI.Wtime()around the solve with a barrier.
6. Hand off
Report: the split chosen and why, the operator/partition mapping, the files created, the dot-test and serial-vs-MPI comparison, the exact launch command, and any version constraints discovered.
04 同仓库更多 Skills
solve-nonsmooth-problem
Use this skill whenever the user wants to solve an inverse problem on PyLops operators with a non-smooth, constrained or non-convex term - load it before writing the objective, choosing a solver or writing optimisation code, even when a SciPy bounded solver or a hand-written FISTA/ADMM loop would also work. Covers total variation, L1/sparsity in a transform, joint sparsity across signals sharing the same components, bounds/positivity/ball/affine constraints, low-rank matrix completion (nuclear norm) and plug-and-play priors with a denoiser (median filter, BM3D), solved with PyProximal (ProximalGradient, ADMM, PrimalDual, ...), step sizes from operator norms. E.g. "add TV regularisation", "keep the model within physical bounds", "recover several signals that share their components", "fill in missing entries of a low-rank matrix", "use PyProximal". Not for purely quadratic regularisation (Tikhonov, damping, derivative smoothing), which is plain least squares - use the pylops skill solve-inverse-problem.
wrap-operator
Wrap a user's own forward model as a PyLops linear operator inside their project (not inside the PyLops library), with a verified adjoint, a dot-test and a small test suite. Use when the user wants to turn existing forward/adjoint code, a script at a URL, or a mathematical description into a PyLops operator they can pass to PyLops solvers (e.g. "make my blurring function a PyLops operator", "wrap this forward model so I can invert it with lsqr", "I have a forward and adjoint, plug them into PyLops").
tune-regularization
Choose regularisation weights and thresholds for a PyLops inversion (epsRs in regularized_inversion, damp in cgls/lsqr, eps in ista/fista, epsRL1s in splitbregman, sigma/tau in spgl1, niter as implicit regularisation) with a principled, reproducible sweep - L-curve, discrepancy principle, GCV for small problems, or a synthetic test with a known model. Use when the user asks "how do I choose epsilon / lambda / damping", "my inversion is too smooth / too noisy", "make an L-curve", or after solve-inverse-problem produced a working but untuned inversion.
solve-inverse-problem
Use this skill whenever the user has (or can build) a PyLops operator and data and wants to invert it - load it before choosing a solver or writing any inversion code, even when the right solver or regularisation seems obvious. It sets up and runs the inversion in the user's project - choose the solver (lsqr, cgls, cg, regularized_inversion, preconditioned_inversion, fista, spgl1, omp, irls, splitbregman), the regularisation and the stopping parameters, and write a runnable script that reports convergence. E.g. "invert my data with this operator", "which PyLops solver should I use", "add Tikhonov / smoothness / sparsity regularisation to my inversion", "solve y = Op x". Not for an inversion that already misbehaves (use debug-inversion) or for choosing regularisation weights with an L-curve or sweep (use tune-regularization).
sliding-patch-processing
Set up PyLops windowed operators - Sliding1D, Sliding2D, Sliding3D, Patch2D, Patch3D - to apply a local transform or operator over overlapping windows of 1-D/2-D/3-D data, choosing window size, overlap, taper and model size with the *_design and *_pad_to_next helpers, checking coverage and the dot-test, and using them for local denoising, interpolation or inversion. Use when the user asks "apply FFT/Radon/any operator in overlapping windows", "local transform / patching with PyLops", "Patch2D gives artefacts at the edges", "how do I pick nwin, nover, nop".
pick-sparsifying-transform
Choose a sparsifying transform for a signal or image in a PyLops sparsity-promoting inversion (FFT/FFT2D/FFTND, DCT, DWT/DWT2D/DWTND, DTCWT, Seislet, curvelets via UDCT, Radon/FourierRadon/ChirpRadon, windowed versions with Sliding/Patch), check its optional dependencies and frame properties, compare candidates quantitatively with a best-k-term compressibility test, and wire the winner into fista/spgl1 in synthesis or analysis form. Use when the user asks "which transform should I use for sparsity", "wavelets or curvelets for my data", "make my model sparse for fista/spgl1", "compressive sensing / interpolation with PyLops".