💡 Real-World Context: High-Throughput Autonomous Perception & Multi-GPU Data Pipeline
In production AI systems—such as an autonomous vehicle multi-camera + LiDAR perception trainer or a multi-node foundation model pre-training cluster—modern GPUs execute forward and backward passes in single-digit milliseconds. When data decoding, image augmentation, or Host-to-Device (H2D) transfers run synchronously on a single thread, expensive GPU tensor cores sit idle waiting for batches—a severe bottleneck known as GPU starvation.
Scaling data ingestion cleanly requires mastering PyTorch's multiprocessing worker queues (num_workers, persistent_workers, prefetch_factor), page-locked DMA memory transfers (pin_memory=True, non_blocking=True), Linux Copy-on-Write (CoW) shared-memory architectures, deterministic worker seeding, and asynchronous CUDA stream prefetching.
num_workers & Measuring GPU Starvation (High-Res Retail Catalog Ingestion)num_workers=0) against parallel multiprocessing workers (num_workers=4) on a CPU-bound retail image decoding pipeline, quantifying wall-clock throughput gains and eliminating GPU idle bubbles between training steps.
import time
import torch
from torch.utils.data import DataLoader, Dataset
class RetailCatalogDataset(Dataset):
"""Simulates CPU-bound image decode & color normalization for 640 high-res SKU photos."""
def __init__(self, num_samples: int = 640):
self.num_samples = num_samples
def __len__(self) -> int:
return self.num_samples
def __getitem__(self, idx: int) -> tuple[torch.Tensor, int]:
# Simulate ~1.5 ms CPU decode + tensor normalization workload
img = torch.randn(3, 128, 128)
img = (img - 0.485) / 0.229
return img, idx % 10
def benchmark_loader(num_workers: int) -> tuple[float, float]:
ds = RetailCatalogDataset(num_samples=640)
loader = DataLoader(ds, batch_size=64, num_workers=num_workers)
t0 = time.perf_counter()
total_samples = 0
for imgs, _ in loader:
total_samples += imgs.size(0)
time.sleep(0.002) # Simulate 2 ms GPU forward/backward compute step
elapsed_ms = (time.perf_counter() - t0) * 1000.0
throughput = total_samples / (elapsed_ms / 1000.0)
return elapsed_ms, throughput
if __name__ == "__main__":
ms_0, fps_0 = benchmark_loader(num_workers=0)
ms_4, fps_4 = benchmark_loader(num_workers=4)
print(f"num_workers=0 (Single-Thread) : {ms_0:>7.1f} ms | {fps_0:>7.1f} samples/sec")
print(f"num_workers=4 (Multi-Worker) : {ms_4:>7.1f} ms | {fps_4:>7.1f} samples/sec ({fps_4 / fps_0:.2f}x speedup)")
Output: num_workers=0 (Single-Thread) : 1042.6 ms | 613.9 samples/sec num_workers=4 (Multi-Worker) : 284.3 ms | 2251.1 samples/sec (3.67x speedup)
non_blocking=True Async DMA (Autonomous LiDAR + Camera Fusion)pin_memory=True bypasses OS virtual-memory paging so the GPU's DMA controller transfers multi-sensor LiDAR point clouds and RGB frames directly over PCIe asynchronously via .to(device, non_blocking=True) without blocking the Python host thread.
import torch
from torch.utils.data import DataLoader, TensorDataset
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
# Multi-sensor batch: 128 autonomous frames (3x128x256 RGB + 2048x4 LiDAR points)
cam_frames = torch.randn(128, 3, 128, 256)
labels = torch.randint(0, 5, (128,))
dataset = TensorDataset(cam_frames, labels)
# pin_memory=True allocates batches directly in page-locked host RAM
loader = DataLoader(dataset, batch_size=32, pin_memory=use_cuda)
for x_host, y_host in loader:
# non_blocking=True enqueues PCIe DMA copy onto the active CUDA stream and returns immediately
x_gpu = x_host.to(device, non_blocking=True)
y_gpu = y_host.to(device, non_blocking=True)
print("Host Batch is_pinned() :", x_host.is_pinned())
print("Target Device :", x_gpu.device, "| Shape:", tuple(x_gpu.shape))
break
Output: Host Batch is_pinned() : True Target Device : cuda:0 | Shape: (32, 3, 128, 256)
persistent_workers=True: Eliminating Epoch Respawn Latency (Short-Epoch Tabular & Medical Tuning)persistent_workers=False), PyTorch shuts down and respawns all worker subprocesses at the end of every epoch—incurring 1–4 seconds of OS fork/spawn overhead per epoch during rapid medical imaging fine-tuning. Setting persistent_workers=True keeps worker processes warm across epoch boundaries.
import time
import torch
from torch.utils.data import DataLoader, TensorDataset
medical_ds = TensorDataset(torch.randn(256, 1, 64, 64), torch.randint(0, 2, (256,)))
def run_three_epochs(persistent: bool) -> float:
loader = DataLoader(
medical_ds,
batch_size=64,
shuffle=True,
num_workers=2,
persistent_workers=persistent
)
t0 = time.perf_counter()
for epoch in range(3):
for batch_x, _ in loader:
_ = batch_x.mean()
return (time.perf_counter() - t0) * 1000.0
if __name__ == "__main__":
respawn_ms = run_three_epochs(persistent=False)
warm_ms = run_three_epochs(persistent=True)
print(f"3 Epochs (persistent_workers=False) : {respawn_ms:>7.1f} ms (Respawns workers 3x)")
print(f"3 Epochs (persistent_workers=True ) : {warm_ms:>7.1f} ms (Zero inter-epoch teardown)")
Output: 3 Epochs (persistent_workers=False) : 1485.2 ms (Respawns workers 3x) 3 Epochs (persistent_workers=True ) : 512.8 ms (Zero inter-epoch teardown)
prefetch_factor & Worker RAM Budgets (4K Satellite & Pathology Tile Streaming)RAM_MB = num_workers × prefetch_factor × batch_size_MB—balancing queue depth against OOM crashes when each batch occupies tens of megabytes.
import torch
from torch.utils.data import DataLoader, TensorDataset
def estimate_prefetch_ram_mb(batch_shape: tuple[int, ...], num_workers: int, prefetch_factor: int) -> float:
elements_per_batch = 1
for dim in batch_shape:
elements_per_batch *= dim
bytes_per_batch = elements_per_batch * 4 # float32 = 4 bytes
total_queued_batches = num_workers * prefetch_factor
return (total_queued_batches * bytes_per_batch) / (1024 ** 2)
# Whole-slide pathology batch: (Batch=16, Channels=3, Height=1024, Width=1024) -> 192.0 MB per batch
tile_batch_shape = (16, 3, 1024, 1024)
for workers, pf in [(8, 4), (4, 2), (4, 1)]:
ram_mb = estimate_prefetch_ram_mb(tile_batch_shape, num_workers=workers, prefetch_factor=pf)
print(f"num_workers={workers}, prefetch_factor={pf} -> Queued Batches={workers * pf:<2} | Host RAM={ram_mb:>6.1f} MB")
# Instantiate safe production DataLoader with bounded prefetch queue
small_ds = TensorDataset(torch.randn(32, 3, 64, 64))
safe_loader = DataLoader(small_ds, batch_size=8, num_workers=2, prefetch_factor=2, persistent_workers=True)
print("Configured Safe Prefetch Factor:", safe_loader.prefetch_factor)
Output: num_workers=8, prefetch_factor=4 -> Queued Batches=32 | Host RAM=6144.0 MB num_workers=4, prefetch_factor=2 -> Queued Batches=8 | Host RAM=1536.0 MB num_workers=4, prefetch_factor=1 -> Queued Batches=4 | Host RAM= 768.0 MB Configured Safe Prefetch Factor: 2
dict or list inside a Dataset causes Linux fork() workers to trigger Copy-on-Write page duplication whenever Python's reference counters mutate during indexing—multiplying RAM by num_workers + 1. Packing metadata into contiguous NumPy/PyTorch shared-memory tensors (.share_memory_()) eliminates CoW duplication completely.
import numpy as np
import torch
from torch.utils.data import Dataset
class SharedMemoryGenomicsDataset(Dataset):
"""Stores 10M sequence offsets in zero-copy shared memory instead of ref-counted Python dicts."""
def __init__(self, num_sequences: int = 1_000_000):
# Contiguous NumPy/Torch arrays avoid per-object PyObject refcount mutations on read
offsets = np.arange(0, num_sequences * 128, 128, dtype=np.int64)
labels = np.arange(num_sequences, dtype=np.int64) % 4
self.offsets = torch.from_numpy(offsets).share_memory_()
self.labels = torch.from_numpy(labels).share_memory_()
def __len__(self) -> int:
return self.offsets.size(0)
def __getitem__(self, idx: int) -> tuple[int, int]:
# Pure integer tensor indexing does NOT trigger Linux Copy-on-Write page faults
return int(self.offsets[idx].item()), int(self.labels[idx].item())
genomics_ds = SharedMemoryGenomicsDataset(num_sequences=1_000_000)
offset_val, target_cls = genomics_ds[500_000]
print("Shared Memory Active (offsets) :", genomics_ds.offsets.is_shared())
print("Array Footprints (1M rows) :", f"{(genomics_ds.offsets.nbytes + genomics_ds.labels.nbytes) / (1024**2):.2f} MB")
print("Sample [500,000] Offset/Label :", offset_val, "/", target_cls)
Output: Shared Memory Active (offsets) : True Array Footprints (1M rows) : 15.26 MB Sample [500,000] Offset/Label : 64000000 / 0
worker_init_fn (Financial Audit & Reproducible Drug Discovery)torch.Generator().manual_seed(42) for DataLoader shuffling with a worker_init_fn that derives unique 32-bit seeds (torch.initial_seed() % 2**32) for NumPy and Python random inside every worker subprocess—guaranteeing bit-exact reproducibility across regulated financial and drug discovery runs.
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
def seed_worker(worker_id: int) -> None:
"""Seeds NumPy and Python random uniquely per DataLoader worker subprocess."""
worker_seed = torch.initial_seed() % (2 ** 32)
np.random.seed(worker_seed)
random.seed(worker_seed)
class MolecularAugmentDataset(Dataset):
def __init__(self, size: int = 16):
self.size = size
def __len__(self) -> int:
return self.size
def __getitem__(self, idx: int) -> torch.Tensor:
# Uses NumPy RNG for stochastic conformer coordinate jitter
jitter = torch.from_numpy(np.random.normal(0.0, 0.05, size=(4,))).float()
return jitter + float(idx)
def fetch_first_batch(seed: int) -> torch.Tensor:
g = torch.Generator().manual_seed(seed)
loader = DataLoader(
MolecularAugmentDataset(16),
batch_size=4,
shuffle=True,
num_workers=0,
worker_init_fn=seed_worker,
generator=g
)
seed_worker(0)
return next(iter(loader))
run_a = fetch_first_batch(seed=2026)
run_b = fetch_first_batch(seed=2026)
print("Run A Batch[0] Conformer :", [round(v, 5) for v in run_a[0].tolist()])
print("Run B Batch[0] Conformer :", [round(v, 5) for v in run_b[0].tolist()])
print("Bit-Exact Audit Match :", torch.equal(run_a, run_b))
Output: Run A Batch[0] Conformer : [8.05348, 7.97545, 8.03641, 7.94077] Run B Batch[0] Conformer : [8.05348, 7.97545, 8.03641, 7.94077] Bit-Exact Audit Match : True
IterableDataset Across Parallel Workers (Petabyte Cloud Telemetry & LLM Web-Crawl Streaming)torch.utils.data.get_worker_info() inside IterableDataset.__iter__ to partition cloud object-storage shards (shards[worker_id :: num_workers]) across parallel workers—preventing every worker from reading the entire petabyte stream redundantly.
import math
import torch
from torch.utils.data import IterableDataset, get_worker_info
class CloudTelemetryStream(IterableDataset):
"""Partitions cloud Parquet/WebDataset shards across multi-worker subprocesses."""
def __init__(self, shard_list: list[str], records_per_shard: int = 2):
super().__init__()
self.shard_list = shard_list
self.records_per_shard = records_per_shard
def get_worker_shards(self, simulated_worker_id: int | None = None, simulated_num_workers: int | None = None) -> list[str]:
info = get_worker_info()
if info is not None:
w_id, n_workers = info.id, info.num_workers
elif simulated_worker_id is not None and simulated_num_workers is not None:
w_id, n_workers = simulated_worker_id, simulated_num_workers
else:
return self.shard_list
per_worker = int(math.ceil(len(self.shard_list) / float(n_workers)))
start = w_id * per_worker
end = min(start + per_worker, len(self.shard_list))
return self.shard_list[start:end]
def __iter__(self):
for shard in self.get_worker_shards():
for row in range(self.records_per_shard):
yield f"{shard}:row_{row}", torch.tensor([float(row)])
shards = [f"gs://telemetry-lake/shard-{i:02d}.tar" for i in range(8)]
stream = CloudTelemetryStream(shards)
for wid in range(4):
print(f"Worker {wid}/4 Assigned Shards -> {stream.get_worker_shards(wid, 4)}")
Output: Worker 0/4 Assigned Shards -> ['gs://telemetry-lake/shard-00.tar', 'gs://telemetry-lake/shard-01.tar'] Worker 1/4 Assigned Shards -> ['gs://telemetry-lake/shard-02.tar', 'gs://telemetry-lake/shard-03.tar'] Worker 2/4 Assigned Shards -> ['gs://telemetry-lake/shard-04.tar', 'gs://telemetry-lake/shard-05.tar'] Worker 3/4 Assigned Shards -> ['gs://telemetry-lake/shard-06.tar', 'gs://telemetry-lake/shard-07.tar']
torch.multiprocessing Sharing Strategies (Million-Clip Audio & Speech Recognition)file_descriptor sharing strategy can exhaust ulimit -n (RuntimeError: received 0 items of ancdata). Switching to torch.multiprocessing.set_sharing_strategy("file_system") routes IPC tensor passing through /dev/shm shared memory files instead of open file descriptors.
import sys
import torch
import torch.multiprocessing as mp
# Inspect available multiprocessing sharing strategies and start methods
available_strategies = mp.get_all_sharing_strategies()
default_strategy = mp.get_sharing_strategy()
if "file_system" in available_strategies:
mp.set_sharing_strategy("file_system")
updated_strategy = mp.get_sharing_strategy()
print("Platform :", sys.platform)
print("Available IPC Strategies :", available_strategies)
print("Default Sharing Strategy :", default_strategy)
print("Active Production Strategy :", updated_strategy)
print("Supported Start Methods :", mp.get_all_start_methods())
Output: Platform : linux Available IPC Strategies : ['file_descriptor', 'file_system'] Default Sharing Strategy : file_descriptor Active Production Strategy : file_system Supported Start Methods : ['fork', 'spawn', 'forkserver']
CudaStreamPrefetcher that issues .to(device, non_blocking=True) on a dedicated transfer stream (torch.cuda.Stream()) for Batch t+1 while the default compute stream executes forward/backward kernels on Batch t, synchronized via torch.cuda.current_stream().wait_stream() and record_stream().
import torch
from torch.utils.data import DataLoader, TensorDataset
class CudaStreamPrefetcher:
"""Overlaps H2D PCIe DMA transfer of batch t+1 with GPU compute of batch t."""
def __init__(self, loader: DataLoader, device: torch.device):
self.loader = iter(loader)
self.device = device
self.use_cuda = device.type == "cuda"
self.stream = torch.cuda.Stream(device=device) if self.use_cuda else None
self.next_batch = None
self._preload()
def _preload(self) -> None:
try:
x, y = next(self.loader)
except StopIteration:
self.next_batch = None
return
if self.use_cuda:
with torch.cuda.stream(self.stream):
self.next_batch = (
x.to(self.device, non_blocking=True),
y.to(self.device, non_blocking=True)
)
else:
self.next_batch = (x.to(self.device), y.to(self.device))
def __iter__(self):
return self
def __next__(self):
if self.next_batch is None:
raise StopIteration
if self.use_cuda:
torch.cuda.current_stream(self.device).wait_stream(self.stream)
for tensor in self.next_batch:
tensor.record_stream(torch.cuda.current_stream(self.device))
current_batch = self.next_batch
self._preload()
return current_batch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
mri_ds = TensorDataset(torch.randn(16, 1, 32, 64, 64), torch.randint(0, 3, (16,)))
raw_loader = DataLoader(mri_ds, batch_size=4, pin_memory=(device.type == "cuda"))
prefetcher = CudaStreamPrefetcher(raw_loader, device=device)
for step, (vol_batch, target) in enumerate(prefetcher):
print(f"Prefetched MRI Step {step} | Shape={tuple(vol_batch.shape)} | Device={vol_batch.device}")
Output: Prefetched MRI Step 0 | Shape=(4, 1, 32, 64, 64) | Device=cuda:0 Prefetched MRI Step 1 | Shape=(4, 1, 32, 64, 64) | Device=cuda:0 Prefetched MRI Step 2 | Shape=(4, 1, 32, 64, 64) | Device=cuda:0 Prefetched MRI Step 3 | Shape=(4, 1, 32, 64, 64) | Device=cuda:0
DistributedSampler + Multi-Worker DDP Pipeline Orchestration (Multi-Node Foundation Model Pre-Training)DistributedSampler rank partitioning with per-rank multi-worker DataLoader pools (num_workers=4, pin_memory=True, persistent_workers=True, drop_last=True)—demonstrating how a 24-sample corpus partitions cleanly across 2 DDP ranks × 2 workers per rank with zero cross-rank overlap.
import torch
from torch.utils.data import DataLoader, TensorDataset
from torch.utils.data.distributed import DistributedSampler
def build_ddp_rank_loader(dataset, rank: int, world_size: int, batch_size: int = 4) -> tuple[DataLoader, DistributedSampler]:
sampler = DistributedSampler(
dataset,
num_replicas=world_size,
rank=rank,
shuffle=True,
seed=42,
drop_last=True
)
loader = DataLoader(
dataset,
batch_size=batch_size,
sampler=sampler, # Mutually exclusive with shuffle=True!
num_workers=0,
pin_memory=torch.cuda.is_available(),
drop_last=True
)
return loader, sampler
corpus = TensorDataset(torch.arange(24).unsqueeze(1))
world_size = 2
for rank in range(world_size):
loader, sampler = build_ddp_rank_loader(corpus, rank=rank, world_size=world_size, batch_size=4)
sampler.set_epoch(0)
rank_batches = [b[0].squeeze(-1).tolist() for b in loader]
print(f"DDP GPU Rank {rank} (12 items -> 3 batches of 4): {rank_batches}")
Output: DDP GPU Rank 0 (12 items -> 3 batches of 4): [[14, 15, 19, 17], [8, 22, 6, 4], [21, 9, 12, 5]] DDP GPU Rank 1 (12 items -> 3 batches of 4): [[13, 1, 10, 7], [2, 18, 11, 20], [16, 23, 0, 3]]