Skip to content
API REFERENCEUsage guides →

Shared and distributed API ​

These interfaces share native output memory between processes on one host. Use the distributed guide for a two-rank example with expected batches. Output views obey the separate ring lease contract.

python
from pycellpack.loader import SharedRing, DistributedLoader, DistributedRun

Choose the orchestration layer

Collective startup ​

DistributedLoader(loader=None, *, transport="auto") stores a Loader or a zero-argument factory on group rank zero. Other ranks normally pass nothing. The factory runs on rank zero during start; the resulting Loader is pickled and rebuilt in the producer. The factory itself is not sent there. Matrix paths, ProcessFn libraries/configuration and access-function owners must be usable or reconstructible in that process.

start argumentDefaultContract
accessesNoneRank zero supplies a 1-D integer array/list or native Accesses; global cell IDs, one per schema per position
planNoneRank zero supplies a Plan, plan-file path, PlanOptions or cache byte budget; None disables planned caching
slots_per_rank2Positive output depth per rank; total slots are slots_per_rank × world
drop_lastFalseTrim an ordinary stored array to complete rounds of every rank's full batch
groupNoneInitialized torch.distributed group; None uses the default group

All members call start in matching collective order. It gathers hostnames, rejects a group spanning hosts, launches the producer on group rank zero, broadcasts descriptors and gathers attachment failures before returning a DistributedRun. Subgroup rank zero may differ from global rank zero. Only group rank zero's loader, accesses, plan and ring sizing are used. Peers should supply no loader, accesses or plan. The producer uses the launching Python interpreter and initializes neither CUDA nor a torch.distributed group.

Arrays normalize to contiguous uint32 IDs, retaining order and repeats. Access length must be divisible by schema count. With S schemas, drop_last=True keeps floor(length / (slot_rows × world × S)) × (slot_rows × world × S) accesses. It rejects native Accesses, including Accesses.array(...), because that object is not the ordinary array trimming path. A fixed plan must match the sequence actually executed, including trimming.

DistributedRun results and lifecycle ​

One host · one producer · per-rank consumers
  1. 01
    Rank zero configures

    Supply the Loader or factory, access sequence and optional plan.

  2. 02
    All ranks start

    Call start collectively on the initialized group.

  3. 03
    CPU producer fills

    A dedicated process writes outputs into a SharedRing; it initializes neither CUDA nor the training group.

  4. 04
    Ranks consume

    Batch b belongs to rank b % world. Each rank consumes and releases its leased batches.

Shared memory is local to one host. Drain before join; early exit or rank failure cancels the shared run.

InterfaceResult / behavior
rank, worldGroup rank and consumer count
producer_pidDedicated producer's process ID
len(run)Batches assigned to this rank, including a partial tail it owns
IterationNative Batches in this rank's order; advancing releases the preceding Batch reference
wait(b)Acquire global batch index b; require b % world == rank; caller releases/drops each returned Batch
finishedTrue only after producer success; False while pending; failure/cancellation raises RuntimeError
join()Wait without consuming and return the producer's complete RunStats; failure/cancellation raises RuntimeError
cancel()Cancel the active run for all ranks and abort its shared ring
close(cancel=True)Close consumer and local resources; default cancels, False waits for success/failure

For local step j, the manual wait index is rank + j × world, not j. Consume each assigned global batch once, in increasing order. wait past the end raises RuntimeError rather than returning None; bound manual loops with range(len(run)). For B total batches, a rank has max(0, ceil((B - rank) / world)) batches.

join neither drains output nor acts as a group barrier. It may wait for other ranks to release slots. Statistics describe the whole producer run: do not sum the same counts returned to every rank. finished differs from native Run.finished, which also counts failure and cancellation as completion.

Successful context exit after all assigned batches were taken calls close(cancel=False). Early exit or an exception cancels the run. close is idempotent; all ranks close mappings, and rank zero waits for or stops the producer. After close, iteration stops and join, wait and finished require an open run. Capture statistics before closing. Already exported arrays retain their mappings and their leases while production is active.

SharedRing and descriptor lifetime ​

InterfaceContract
create(layout, *, transport="auto", extra=None)Create and initialize a ring; derive layout from the intended Loader
extraAdditional named byte sizes, clamped to at least one; cannot replace control or data
descriptorPicklable layout/transport/region descriptors, not copied output bytes
attach(descriptor, *, fds=None)Map existing regions without reinitializing control; attaching process does not own/unlink names
inheritable()Return (descriptor, pass_fds) for child subprocess.Popen with memfd regions
sharing / stop_sharing()Whether peers can fetch memfd descriptors / stop serving after attachment
ring, layoutNative Ring and unchanged layout
consumer(rank=0, **kwargs)Open that rank's current/next ring consumer; kwargs follow Ring.consumer
region(name)Memoryview over a named region's bytes
region_fd(name)OS descriptor, valid while this SharedRing owns it
close() / context exitStop sharing, close FDs, unlink named regions only when this process created them

Keep the creator open until peers attach. memfd peers without inherited FDs receive duplicates over a same-user Unix socket. DistributedLoader.start manages this handshake and stops serving after every peer attached or failed. A saved descriptor does not preserve closed/unlinked regions as persistent data.

Close consumers and finish active runs before releasing resources. SharedRing close is memory cleanup, not cancellation or completion signaling. Existing NumPy arrays retain their mappings; names may already be unlinked and new attachment unavailable. Do not close region_fd yourself or retain it past the SharedRing's lifetime. See rings for slot leases and consumer cleanup.

Transport selection and failures ​

TransportAllocation / attachment
shmNamed mmap files under /dev/shm, limited by mount capacity
memfdAnonymous memory files; FD inheritance or same-user transfer; subject to memory/cgroup limits
fileMapped files in PYCELLPACK_SHM_DIR or system temporary directory; dirty pages may be written back

transport="auto" consults PYCELLPACK_SHM, then tries shm → memfd → file if still automatic. Explicit transport names take precedence over the environment and try only that backend. Automatic selection leaves filesystem headroom; creation reserves regions before mapping. For file transport, PYCELLPACK_SHM_DIR must name an existing writable directory.

Unavailable/uninitialized process groups raise RuntimeError; cross-host groups raise ValueError. Rank-zero startup errors are broadcast as RuntimeError, and attachment failures are gathered before ranks leave startup. Producer exceptions or unexpected exits publish a cause through shared status. A departed consumer makes the producer fail rather than wait indefinitely. These mechanisms do not replace matching training collectives or correct lease release. Direct SharedRing calls can raise ValueError for invalid declarations/descriptors and OSError for allocation or attachment failures.

Declarations ​

Complete declarations and members

DistributedLoader ​

python
DistributedLoader(loader=None, *, transport='auto')

A Loader run by a dedicated producer process for every rank of a torch.distributed group on one host.

Group rank zero gives the loader (any data source, outputs, process functions and configuration; it is pickled to the producer, which rebuilds it), or a function returning it, called in start so that its failures reach every rank; the other ranks give nothing. start is collective: rank zero launches the producer over a SharedRing of slots_per_rank slots per rank, and each rank iterates its batches (b % world == rank) as typed Batches. No CUDA work runs in the producer. transport picks how the ring's memory is shared (see SharedRing).

DistributedLoader.start ​

python
DistributedLoader.start(accesses=None, *, plan=None, slots_per_rank=2, drop_last=False, group=None) -> DistributedRun

Starts the producer (on rank zero, which gives accesses: an array of cells or an Accesses; and plan: a Plan, a plan file path, PlanOptions or a cache budget in bytes, or None) and attaches every rank. drop_last trims an array to whole rounds of every rank's slot.

DistributedRun ​

This rank's share of a producer's run: iterate its batches (advancing releases the previous one; exported arrays keep their slot just as in the local loader), then join for the producer's RunStats. Successful context exit waits for the producer; early exit or an exception cancels it for every rank. rank and world are this rank and the ring's rank count; producer_pid is the producer's process id.

DistributedRun.wait ​

python
DistributedRun.wait(batch)

Batch batch of this rank.

DistributedRun.finished ​

finished: bool — property.

Whether the producer succeeded (a failure raises).

DistributedRun.join ​

python
DistributedRun.join()

Waits for the producer's outcome and returns its RunStats; polls the status region every ten milliseconds and raises its failure.

DistributedRun.cancel ​

python
DistributedRun.cancel()

Cancels the run for every rank: the status names this rank and the ring is aborted, so blocked consumers and the producer stop.

DistributedRun.close ​

python
DistributedRun.close(*, cancel=True)

Releases this rank's consumer and stops the producer: cancelled when cancel is true, otherwise waited for (a failed producer raises through join). Idempotent.

SharedRing ​

python
SharedRing(layout: RingLayout, regions: dict, descriptor: dict, *, owner: bool, server=None)

A ring in memory that processes of this host share: create it in one process, send its descriptor (a picklable dict) to others and attach there. A loader in any of them produces into ring (Loader.start(..., ring=shared.ring)); each consumer process takes its rank's batches through consumer(rank). Consumers and the producer register in the ring's control, so a blocked wait fails with the reason when a participant died or left early.

transport picks how the memory is shared: named files in /dev/shm, anonymous memfd files (handed to attaching processes of the same user over a Unix socket while sharing), or files in a directory; "auto" (or PYCELLPACK_SHM) takes the first that has room. extra adds named byte regions of the given sizes in the same memory (region(name)). The creating process unlinks named memory on close; memfd memory is freed with its last user. Arrays exported from batches keep their mappings alive after close.

SharedRing.create ​

python
SharedRing.create(layout: RingLayout, *, transport='auto', extra=None) -> SharedRing

A new shared ring of layout (and extra regions).

SharedRing.attach ​

python
SharedRing.attach(descriptor: dict, *, fds: dict | None=None) -> SharedRing

The shared ring a descriptor names. memfd memory arrives from the creator's socket, or as inherited fds (see inheritable).

SharedRing.inheritable ​

python
SharedRing.inheritable() -> tuple[dict, tuple[int, ...]]

A descriptor for a child process and the file descriptors it must inherit (subprocess.Popen(pass_fds=...)), for memfd memory.

SharedRing.sharing ​

sharing: bool — property.

Whether attaching processes can still fetch memfd descriptors.

SharedRing.stop_sharing ​

python
SharedRing.stop_sharing() -> None

Stops handing out memfd descriptors (every peer has attached).

SharedRing.region ​

python
SharedRing.region(name: str) -> memoryview

An extra region's bytes.

SharedRing.region_fd ​

python
SharedRing.region_fd(name: str) -> int

An extra region's descriptor (the status region is locked through it).

SharedRing.consumer ​

python
SharedRing.consumer(rank: int=0, **kwargs) -> Consumer

Rank rank's consumer of the ring's current (or next) run (see Ring.consumer).

SharedRing.close ​

python
SharedRing.close() -> None

Stops handing out descriptors and releases every region, unlinking named memory when this process created it.