A conceptual four-stage pipeline links cube storage, CPU preparation, pinned transfer and GPU computation.
Original conceptual diagram using synthetic examples. It illustrates the article’s question, not experimental results.

Throughput belongs to the whole experiment

A fast neural network can spend most of its training time waiting for data. Hyperspectral cubes make that failure easy to create: patches are large across the spectral dimension, neighbouring samples overlap, storage layouts differ, and preprocessing can make several hidden copies. Increasing the GPU count will not fix every slow stage.

Start with a named performance question. Are you measuring training examples per second, full-scene inference latency, time to a validation result, or total experiment cost? Keep the model, sample sequence, precision and output checks fixed while tuning the input pipeline. A faster run that silently omits samples or changes their distribution is a different experiment.

This is a profiling workflow, not a benchmark report. The arithmetic below is illustrative. PyTorch interfaces should be checked against the version installed for the project; the linked documentation records the APIs and timing behaviour used here.

Calculate the payload before choosing workers

A batch of 64 float32 patches with 200 bands and a 15 × 15 spatial window contains 64 × 200 × 15 × 15 × 4 = 11,520,000 bytes, approximately 10.99 MiB. This excludes labels, Python objects, allocator overhead and every intermediate array.

PyTorch defines prefetch_factor as the number of batches prepared per worker. Four workers with a factor of two can therefore have up to eight prefetched batches in that queue model, corresponding to about 87.9 MiB of this example’s raw inputs. Actual process memory is larger and depends on the rest of the pipeline. [1]

Now consider an operation that materialises a second contiguous batch, a pinned transfer buffer and an augmentation result. Budgeting only the final tensor misses these simultaneous allocations. Inspect peak host memory and shared-memory usage under sustained iteration, not just immediately after constructing the loader.

Illustrative float32 input payload. MiB uses 1,048,576 bytes. These are not measured process-memory values.
ConfigurationInput payload
One 64 × 200 × 15 × 15 batch10.99 MiB
Eight prefetched batches87.89 MiB
One 64 × 200 × 31 × 31 batch46.92 MiB
Eight larger batches375.39 MiB

Use three baselines to locate the bottleneck

First measure data iteration without the model, including the real reader, transforms and collation. Then measure repeated computation on a representative batch already on the GPU. Finally measure the complete loop. These experiments answer different questions and should be labelled separately.

If the loader is slower than the model-only loop, investigate storage access and preprocessing before changing the network. If the full loop is much slower than both isolated measurements suggest, inspect transfers, synchronisation and overlap. Cold storage reads, filesystem cache and initial worker startup can change the apparent result, so record warm and cold conditions when they matter.

Use enough iterations to pass startup effects, but retain first-batch latency separately for interactive or short jobs. Summarise the median and spread of repeated timings. A single favourable batch does not describe a multi-hour training run, especially when samples span different files or compressed chunks.

Read the data you need, in a useful order

Choose storage access around the actual sampling pattern. A spectrum-at-a-time classifier and a spatial-patch network exercise a cube differently. Verify the source interleave, array strides and output axis order. Repeatedly reading a large block for one small patch can make a mathematically efficient model operationally expensive.

Memory mapping can avoid loading an entire file into a new in-memory array, but slices still trigger reads and later operations can allocate copies. Spectral Python exposes file-backed access and explicit interleave choices; inspect its returned shape rather than assuming bands-first data. [4]

A coordinate manifest is often easier to audit than millions of saved overlapping patch files. It can record scene, row, column, label and split while the reader obtains the requested window. If locality-aware sampling groups neighbouring windows, confirm that the changed ordering is acceptable for optimisation and does not mix held-out support into training. Preserve the spatial split contract before pursuing cache efficiency.

Increase parallelism only while it helps

Begin with num_workers=0 as a simple diagnostic baseline, then test a small sequence such as one, two and four workers under the same workload. The useful count depends on storage latency, CPU transforms and process overhead. More workers can saturate a disk, contend for CPU resources or increase memory pressure.

PyTorch warns that workers can consume additional memory associated with parent-process Python objects they access. Keep large metadata structures compact and avoid constructing a Python object for every possible patch. persistent_workers retains worker dataset instances between iterations over the dataset; that can reduce repeated startup but also preserves worker-local state. [1]

Open process-local resources according to the reader’s documented multiprocessing behaviour. Do not assume an inherited file handle is safe. For an IterableDataset, verify explicitly that worker partitions do not yield duplicate samples. Count emitted sample identifiers during a representative pass and compare them with the intended manifest.

Treat pinned memory and asynchronous copies as a hypothesis

Pinned host memory can support faster host-to-device transfers, and PyTorch provides pin_memory in DataLoader. non_blocking transfers allow the caller to avoid some host synchronisation. Their benefit depends on the actual pipeline; they do not guarantee that transfer and computation overlap. Stream dependencies and buffer lifetime still matter. [2]

Compare a small controlled set of configurations and measure complete iterations. A setting that improves transfer microbenchmarks can still lose overall if preparing pinned copies costs more than it saves. Keep host memory bounded and do not modify or reuse a transfer source before the asynchronous operation has safely consumed it.

When a trace shows meaningful transfer cost, investigate overlap deliberately. Record the ownership and lifetime of each buffer and the dependency between copy and compute. Start with correctness and one device; adding custom streams to an unverified reader multiplies the number of states that can fail.

Time completed work and inspect a short trace

CUDA execution is asynchronous, so a CPU timer around a launch can measure queueing rather than completed GPU work. Use appropriately synchronised wall-clock boundaries for end-to-end measurements or CUDA events for device intervals. Synchronising after every tiny operation changes the execution pattern and should not become the default throughput benchmark. [2]

PyTorch Profiler can collect CPU and accelerator activity and export traces. Its scheduled profiling supports a short warm-up and active window; tracing an entire long job adds overhead and can produce an unnecessarily large trace. Mark reader, transform, transfer, forward, backward and optimiser regions so the trace answers a concrete question. [3]

Look for long host gaps, repeated allocations, unexpected device synchronisation and expensive shape conversions. Profile a representative batch size and spectral width. An artificial tiny input may move the bottleneck and produce advice that does not apply to the real cube.

Keep the faster pipeline scientifically equivalent

After each change, check sample identifiers, label alignment, valid-band masks and numerical ranges. Compare a deterministic subset before and after the change. A channels-last conversion, dtype cast or augmentation cache should have an explicit expected effect rather than merely producing a tensor of the required size.

Record software, operating system, storage location, worker count, prefetch setting, batch shape, transfer policy and timing boundaries. Also record random seeds and determinism settings. PyTorch cautions that identical seeds do not guarantee reproducibility across releases, devices and platforms. Performance and reproducibility are therefore conditions to report together. [5]

Save the measured configuration with the run rather than copying a “fast” loader recipe into every project. For inference on scenes larger than memory, continue with out-of-core processing; for run lineage, use experiment tracking.

Frequently asked questions

Is the largest possible worker count fastest?

No. Workers compete for storage, CPU time and memory. Measure several bounded configurations using the same samples and complete training loop.

Does a memory map mean zero memory use?

No. File pages occupy memory when accessed, and transforms, collation or contiguous conversions can allocate new arrays. Measure peak usage during real iteration.

Can I benchmark GPU work with an ordinary timer?

Yes, when the timing boundaries account for asynchronous execution. Otherwise the interval may measure queued launches instead of completed work; use synchronised boundaries or appropriate device events.

References and further reading

  1. PyTorch: torch.utils.data and DataLoader
  2. PyTorch: CUDA semantics, asynchronous execution and memory
  3. PyTorch Tutorials: PyTorch Profiler
  4. Spectral Python: File I/O and memory maps
  5. PyTorch: Reproducibility

Reader feedback

— reads— comments

Reads since 1 October 2026: at least 15 seconds with the article visible, counted once per browser per day. Reactions are anonymous and can be changed.

Discuss this article

Ask a technical question, challenge an assumption or share evidence from your own work.

Your name and comment will be public after approval. New comments wait for approval. No email required. Keep it respectful and relevant; no personal information or spam. Plain text, up to 2,000 characters.

Owner: manage comments