spdl.pipeline.SharedMemorySegmentPool¶
- class SharedMemorySegmentPool(segment_size: int, count: int, *, acquire_timeout: float = 60.0, pin_memory: bool = False, _mp_context: BaseContext | None = None)[source]¶
[Experimental] A rotating pool of shared-memory segments, one per unit.
Construct it in the parent process and pass it to
spdl.pipeline.iterate_in_subprocess()via thearenaargument; ownership transfers to the returned iterable, which closes and unlinks it at teardown. Restored NumPy/Torch payloads are zero-copy views over shared memory; the pool keeps each segment until its views are released.For caller-managed direct output, instead pass the parent-owned pool to an ordinary process executor initializer and use
reserve(),recover()anddiscard(). The caller retains ownership and must retain the owning pool until workers are reaped. Publicclose()first cancels further arena work; uncertain work, live aliases and claims defer physical retirement until a later safe retry. Unlink only after reap. These modes are exclusive. Constructor-created control metadata exists before spawn; native IO is needed only for actual storage exports and CUDA initializes only when the consumer uses pinning.Added in version 0.5.0.
Changed in version 0.6.0: Backpressure now uses a process-shared
multiprocessing.Conditioninstead of busy-polling the shared reclaim counter; idle producers no longer consume CPU while waiting.Changed in version 0.7.0: Restored zero-copy views remain valid across worker re-iterations. Making
SharedMemorySegmentPoolsafe to use with continuous source.Note
Performance. Because each unit is restored as a zero-copy view directly over shared memory, this backend avoids the per-item serialization and copy-out that a plain pickle/queue transfer pays on both sides of the process boundary. The consistent, measured benefit is substantially lower host CPU usage for moving large payloads across the boundary — the transfer stops being a serialize-then-copy operation.
Whether that converts into higher end-to-end throughput depends on where the bottleneck is. It helps most when the pipeline is CPU-bound or transfer/serialization-bound. When the consumer is the bottleneck (for example a GPU-starved, decode-bound stage), throughput can be unchanged and the gain instead shows up as freed CPU headroom — which still matters when many workers contend for host cores. Treat this as an opt-in optimization and measure your own pipeline before relying on it.
See also
benchmark_arena_transportBenchmarks this pool against a plain pickle/queue transfer and the ring buffer, across payload types and sizes.
benchmark_pinned_arenaMatched public pool/ring
pin_memory=False/Truecomparisons through subprocess iteration and synchronized H2D, with archival earlier results.- Shared-memory arena transport benchmark
Case study with the measured CPU, throughput, and memory numbers.
- Parameters:
segment_size – Size of each segment in bytes. Must be at least as large as the biggest single pipeline unit (the sum of its offloaded binaries).
count – Number of segments. With Mode B backpressure (the default) the producer waits for the consumer to reclaim a segment when the pool is full, so
countbounds memory and in-flight units rather than being a hard cap that errors. Size it to the working set that keeps the consumer fed (buffer_sizeplus concurrent consumer holds).acquire_timeout – Seconds
begin_unitwaits for a free segment before raisingBufferError. Guards against a stalled/dead consumer; set to0for non-blocking (Mode A) behavior.pin_memory – Register the consumer’s complete data mappings once on the CUDA device selected by
LOCAL_RANK. Supported restored CPU tensor/array/memoryview views then have page-locked backing. CUDA initializes lazily in the consumer, never the writer. Defaults toFalse. Budgetcount * segment_sizeper pool and local rank; retained aliases and synchronized H2D sources prevent reuse/unmap.
Changed in version 0.9.0: Public endpoint methods conform to
ArenaProtocol. Storage sizing, counters and lifecycle helpers used only by SPDL are private; constructor configuration remains public. Native exports retain storage independently of the reader anchor list.Added in version 0.9.0: The
pin_memoryargument.Changed in version 0.9.0: The constructor writes every segment page once, so a unit’s first copy takes no page faults. A unit is copied into its segment outside the cross-process control lock, and a pinned consumer registers its mappings outside it too. A unit transfer that waits longer than the control-lock timeout keeps waiting, with a warning, while every endpoint process is alive, instead of retiring the pool.
Methods
close()Close this handle, cancelling global work only for its original creator.
discard(ticket)Claim and discard an unread ticket exactly once, without restoring data.
Return the reader endpoint (call in the parent process).
Return the writer endpoint (call in the worker process).
recover(ticket)Claim one sealed allocation and borrow its lifetime-owned byte view.
reserve(*[, max_bytes])Reserve a producer-owned output segment for direct allocation.
Request shutdown and wake a producer blocked on arena capacity.
unlink()Remove creator names only after physical retirement completes.
Attributes
Stable pool identity for routing allocation tickets in the caller.
- property arena_id: str[source]¶
Stable pool identity for routing allocation tickets in the caller.
Use
pools = {pool.arena_id: pool}and recover each ticket withpools[ticket.arena_id].recover(ticket). This identifies the shared allocation control, not a pointer, worker index or initialization order.Added in version 0.9.0.
- close() → None[source]¶
Close this handle, cancelling global work only for its original creator.
The constructor-created handle owns names and terminal cancellation. Deserialized handles, including same-process copies, only retire their local mappings; closing a worker handle never consumes an in-transit allocation or cancels the creator. Only the creator may unlink names.
Call the creator’s
close()in itsfinallyblock before stopping a pipeline whose producer may be blocked. The terminal signal wakes reservations but never invalidates existing storage aliases or H2D source owners. A known-live or uncertain remote endpoint, native export or active claim keeps control and data mappings durably retained.After workers are actually reaped and local aliases/claims are gone, call
close()again to finish retirement, thenunlink(). Repeated calls do not reopen mappings, reset counters or permit future reuse. A normal return may mean deferred physical retirement;unlink()reportsBufferErroruntil all retained mappings are closed.- Raises:
RuntimeError – Control acquisition is unavailable or the handle was inherited across fork. Uncertain storage remains retained.
Changed in version 0.9.0: Creator close is terminal cancellation with deferred retirement; deserialized holder close only retires its process-local mappings.
- discard(ticket: _ArenaAllocationTicket) → None[source]¶
Claim and discard an unread ticket exactly once, without restoring data.
- Parameters:
ticket – Unread metadata from this pool. For example, discard outputs intentionally not consumed during a confirmed queue drain.
- Raises:
RuntimeError – The ticket is foreign, stale, already recovered or discarded. Replay and serialization retries do not create owners.
Producer aliases continue to gate reuse. A lost ticket remains occupied until terminal cleanup after workers are reaped; neither GC nor delivery failures imply it is safe to release.
Added in version 0.9.0.
- recover(ticket: _ArenaAllocationTicket) → _RecoveredAllocation[source]¶
Claim one sealed allocation and borrow its lifetime-owned byte view.
- Parameters:
ticket – Opaque ticket from
unit.seal()on this pool. Application metadata, offsets, dtype and shape travel beside it in ordinary IPC and are interpreted by the caller, not the arena.- Returns:
One-use context yielding a memoryview over the complete sealed extent, including alignment padding:
with pool.recover(ticket) as data: use(data)
Recovery claims immediately, before returning the context. Exit releases the logical caller hold, even on exceptions. Escaped native aliases, caller-created typed views and H2D source holds still prevent reuse; the name
dataalso remains bound after awithstatement. Drop final aliases before expecting capacity. An abandoned context requires terminal arena cleanup, not GC-based delivery inference. An empty extent yields an empty view without requiring native IO.- Raises:
RuntimeError – Identity/extent is invalid or the ticket was claimed.
ValueError – The ticket packet exceeds 64 KiB.
Added in version 0.9.0.
Changed in version 0.9.0: Yields bytes only; payload reconstruction belongs to the caller.
- reserve(*, max_bytes: int | None = None) → ArenaReservation[source]¶
Reserve a producer-owned output segment for direct allocation.
Construct one pool per producer in the parent and pass handles in ordinary
ProcessPoolExecutorConfiginitializerinitargs(spawn only, never through item queues). Its shared control already exists before spawn. Before stopping a continuous pipeline, callpool.close()to cancel new reservations and wake blocked producers without invalidating live storage. After workers are reaped and aliases/claims are released, retry close to finish retirement, then unlink. Retain owning handles if reap fails. A pool cannot mix direct and ordinary endpoints.- Parameters:
max_bytes – Positive limit within one segment; defaults to its size.
- Returns:
Writable
ArenaReservationcontext, e.g.with pool.reserve() as unit: .... Context exit aborts only unsealed work; native aliases still gate FIFO reuse.- Raises:
BufferError – Capacity is exhausted or the pool is shut down.
RuntimeError – Another process already owns this pool’s producer role.
ValueError – The byte limit is invalid.
Added in version 0.9.0.
- shutdown_arena() → None[source]¶
Request shutdown and wake a producer blocked on arena capacity.
Call before worker join; this requests shutdown without closing mappings, unregistering live storage or unlinking names. Existing exports remain valid. Complete physical retirement separately through
close()once actual worker and storage quiescence is established.- Raises:
RuntimeError – Control state is unavailable or retired. Owned backing remains retained; this failure is not proof of safe retirement.
- unlink() → None[source]¶
Remove creator names only after physical retirement completes.
- Raises:
BufferError – Mappings or registrations are retained. Release live owners, confirm worker reap and retry
close()before unlink.RuntimeError – This is not the original creator handle.