Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 3: Training and data systems

Chapter 11Data pipelines and storage

28 min read, 1 lab, Intermediate

Eight modern GPUs training an image model can consume tens of thousands of images per second, which is several gigabytes per second of reads plus the CPU work to decode them. If storage or decoding cannot keep up, you pay full price for GPUs that sit idle waiting, and nothing in the training code looks wrong.

After this chapter you can

  • Calculate the read bandwidth and decode rate a training job needs
  • Choose a dataset format (Parquet, Arrow, tar shards, tokenized binaries) for a workload
  • Explain object storage semantics and how to get throughput from them
  • Design a caching hierarchy from object store to local NVMe
  • Build streaming, shard-based input pipelines that shuffle and resume correctly
  • Size checkpoint storage and version datasets with lineage

Why the data loader is often the bottleneck

The input pipeline is a chain: read bytes from storage, decode them (JPEG, Parquet, text), transform them (augment, tokenize), collate a batch, and copy it to the GPU. The slowest stage sets the training speed, and every stage runs on CPUs and disks you probably did not size as carefully as the GPUs.

Do the sum before blaming anything:

8 GPUs x 3,000 images/s each      = 24,000 images/s
24,000 x 110 KB average JPEG      = ~2.6 GB/s sustained reads
JPEG decode at ~500 images/s/core = ~48 CPU cores just for decoding

Text training looks easier because tokens are small, but the same logic applies to tokenization if you do it on the fly, and to multimodal data where each sample may be a video clip.

PyTorch's DataLoader parallelises the CPU stages across worker processes. The knobs that matter:

SettingWhat it doesTypical value
num_workersWorker processes that load and decode in parallel4 to 16 per GPU, bounded by cores
pin_memory=TruePage-locked host buffers so the GPU copy is asynchronousOn for GPU training
prefetch_factorBatches each worker prepares ahead2 to 4
persistent_workers=TrueKeep workers alive between epochsOn, avoids re-forking every epoch

Dataset formats

Storing a dataset as millions of individual files is the most common mistake. Every file costs a metadata lookup and an open, and on network storage each one is a separate request with tens of milliseconds of latency.

FormatLayoutStrengthWeakness
Individual filesOne file per sampleEasy to inspectMetadata and per-request overhead dominate
ParquetColumnar, compressed row groupsTabular and text data, column pruning, Spark and Ray nativeRandom access to one row is costly
Arrow (IPC / Feather)Columnar, uncompressed, memory-mappableZero-copy reads; Hugging Face datasets cache formatLarge on disk
Tar shards (WebDataset)Samples grouped into tar files of 100 MB to 1 GBSequential reads, streams from anywhereOnly shard-level random access
MDS (MosaicML Streaming)Binary shards plus an indexDeterministic shuffle and mid-epoch resumeLibrary-specific
Tokenized binaryOne flat array of token idsFastest for LLM pre-training, np.memmapFixed tokenizer; re-tokenize to change it

The tokenized binary approach is worth seeing because it is so simple. Tokenize once offline, write uint16 or uint32 ids to one file, and sample random windows at training time with no decoding at all.

tokens_memmap.py
import numpy as np, torch
data = np.memmap("train.bin", dtype=np.uint16, mode="r")   # OS pages it in on demand
def get_batch(batch=32, ctx=2048):
    ix = np.random.randint(0, len(data) - ctx - 1, batch)
    x = torch.from_numpy(np.stack([data[i:i + ctx] for i in ix]).astype(np.int64))
    y = torch.from_numpy(np.stack([data[i + 1:i + 1 + ctx] for i in ix]).astype(np.int64))
    return x, y

A WebDataset shard is just a tar file where files sharing a key form one sample: 000123.jpg, 000123.cls, 000123.json. Any tool can create it, and a reader only ever does large sequential reads.

Object storage semantics and throughput

Object stores such as Amazon S3, Google Cloud Storage and Azure Blob hold most training data because they are cheap, durable and effectively unlimited. They are not file systems, and pipelines that treat them like one are slow.

  • Keys, not directories. train/shard-0001.tar is one flat key; "folders" are a listing convention.
  • Whole-object writes. No appends or in-place edits. Rename is a copy plus a delete.
  • LIST is slow and paginated. Listing millions of keys takes minutes, so ship a manifest file of keys instead.
  • High latency, high parallelism. First-byte latency is typically tens of milliseconds, but aggregate throughput scales with concurrent requests.
  • Request limits per prefix. AWS documents at least 5,500 GET and 3,500 PUT requests per second per partitioned prefix. Small objects hit that limit long before bandwidth runs out.
  • Strong consistency. S3 has offered strong read-after-write consistency since December 2020, so a new checkpoint is visible as soon as the PUT succeeds.

Little's law explains why object size matters so much:

throughput = concurrent_requests * object_size / latency
 
64 requests x 100 KB / 0.03 s  = ~213 MB/s     (small files)
64 requests x 256 MB / 2.5 s   = ~6.5 GB/s     (shards, transfer-time bound)

Large shards turn a latency-bound workload into a bandwidth-bound one. For very large objects, issue parallel ranged GETs (HTTP Range headers) to use more connections per object.

Parallel file systems, caching tiers and local NVMe

Parallel file systems such as Lustre, IBM Storage Scale (GPFS), WEKA and VAST give many clients POSIX file access at hundreds of gigabytes per second aggregate. They stripe each file across many storage servers and keep metadata on dedicated servers, so they handle random access and in-place writes that object stores cannot. They cost far more per terabyte, and the metadata servers become a bottleneck under millions of small files.

Object storeParallel file system
InterfaceHTTP API (GET, PUT, LIST)POSIX (open, read, seek, write)
Cost per TBLowHigh
Small random readsPoorGood
ScaleEffectively unlimitedSized and provisioned up front
Typical roleSource of truth, archive, checkpointsHot training data, shared scratch

Most clusters combine both with caches in between. Each tier is roughly an order of magnitude faster and smaller than the one below it.

Managed bridges exist too: Amazon FSx for Lustre can link a file system to an S3 bucket, and tools such as Mountpoint for Amazon S3 or gcsfuse expose a bucket through a file interface with caching. They help, but they do not change the underlying request economics of small objects.

Streaming datasets, shuffling and resume

When the dataset is larger than local disk, you stream it: workers fetch shards from the object store as training runs, decode them in memory and discard them. Streaming makes shuffling and resuming harder, because you can no longer pick any sample at random.

The standard design uses two-level shuffling:

  • Shard-level shuffle. Each epoch, shuffle the shard list with a seed derived from the epoch, then split shards across ranks and workers so none read the same shard.
  • Buffer shuffle. Each worker keeps a buffer of a few thousand samples and yields random elements from it, mixing samples across shards.
  • Deterministic resume. Record how many samples each rank consumed in the checkpoint. With seeded shuffles, the loader can skip to the same position after a restart.

Libraries handle this so you do not have to: WebDataset, MosaicML Streaming (MDS format), Lightning's LitData and Hugging Face datasets with streaming=True. MosaicML Streaming and LitData put deterministic mid-epoch resume at the centre of their design; check that property for whichever you pick.

Preprocessing at scale and data lineage

Raw data rarely goes straight to training. It is filtered, deduplicated, tokenized and sharded first, often across hundreds of machines. Ray Data and Apache Spark are the common engines: Spark for SQL-shaped tabular work, Ray Data when the steps are Python-heavy or need GPUs (running an embedding model or a quality classifier over every sample).

preprocess_ray.py
import ray
ds = ray.data.read_parquet("s3://raw-corpus/2026-11/")             # distributed read
ds = ds.filter(lambda r: len(r["text"]) > 200)                     # drop tiny docs
ds = ds.map_batches(tokenize_batch, batch_size=1024)               # runs on many workers
ds.write_parquet("s3://tokenized/corpus-v7/")                      # sharded output

At this scale you must be able to answer "exactly which data trained this model?" That is lineage, and it needs versioning:

  • Immutable outputs. Write every processed dataset to a new path (corpus-v7), never overwrite in place.
  • Manifests with hashes. A file listing every shard and its checksum identifies the dataset exactly.
  • Version tools. DVC versions files alongside Git; lakeFS adds Git-like branches over an object store; Apache Iceberg and Delta Lake keep table snapshots you can query as of a version.
  • Record it with the run. The experiment tracker stores the dataset version and manifest hash next to the model, as Fine-tuning systems showed.

Checkpoint storage sizing

Checkpoints are the other big storage workload, and they are write-heavy and bursty. A full checkpoint holds weights plus optimizer state, roughly 12 to 16 bytes per parameter for mixed-precision Adam.

70B parameters x ~14 bytes          = ~1 TB per checkpoint
write it in 60 s                    = ~16 GB/s aggregate write bandwidth
every 30 min for 30 days            = 1,440 checkpoints = ~1.4 PB if all kept
retention: last 5 + one per day     = ~35 TB

The rules that keep checkpoint storage sane:

  • Every rank writes its own shard in parallel (as PyTorch DCP does), so bandwidth scales with the job.
  • Write to fast local storage first, then upload to the object store asynchronously, so training resumes sooner.
  • Set a retention policy on day one: keep the last few, keep milestones, delete the rest automatically.

Key terms

Data loader
The component that reads, decodes, transforms and batches samples for the training loop, usually in parallel worker processes.
Shard
A large file grouping many samples, read sequentially to avoid per-sample overhead.
WebDataset
A convention for storing samples as groups of same-keyed files inside tar archives, plus a library that streams them.
Parquet
A compressed columnar file format organised in row groups, standard for tabular and text datasets.
Object store
Storage accessed by key over an HTTP API with whole-object writes, such as S3, GCS or Azure Blob.
Parallel file system
A POSIX file system that stripes data across many servers for high aggregate bandwidth, such as Lustre.
Shuffle buffer
A pool of samples a streaming loader draws from at random to mix data without random access to storage.
Lineage
The recorded chain from raw sources through processing steps to the exact dataset version a model trained on.
Lab

Benchmark three ways to feed a dataset and find the bottleneck

Intermediate, 75 min

Goal: feed the same 10,000-image dataset as many small files, as local tar shards and streamed from a local S3-compatible store, measure samples per second for each, and use a profiler to show what limits each one.

You need: Python 3.10 or newer, Docker, and about 1 GB of disk. The S3 store is SeaweedFS running in Docker. MinIO was the usual choice for this, but its community edition moved to source-only releases and maintenance mode in late 2025, so this lab uses SeaweedFS; any S3-compatible store works with the same code.

setup
python -m venv .venv && source .venv/bin/activate
pip install torch numpy pillow boto3
mkdir loader-lab && cd loader-lab
docker run -d --name s3 -p 8333:8333 chrislusf/seaweedfs server -s3 -dir=/data

With no identities configured, this SeaweedFS gateway accepts any access key. That is fine on your laptop and unacceptable anywhere else.

  1. Generate the dataset as individual JPEGs and as WebDataset-style tar shards of 1,000 samples each.
make_data.py
import io, os, tarfile, numpy as np
from PIL import Image
os.makedirs("files", exist_ok=True); os.makedirs("shards", exist_ok=True)
rng, N, PER = np.random.default_rng(0), 10000, 1000
tar = None
for i in range(N):
    img = Image.fromarray(rng.integers(0, 255, (128, 128, 3), dtype=np.uint8))
    buf = io.BytesIO(); img.save(buf, "JPEG", quality=90); b = buf.getvalue()
    open(f"files/{i:06d}.jpg", "wb").write(b)
    if i % PER == 0:
        if tar: tar.close()
        tar = tarfile.open(f"shards/shard-{i // PER:05d}.tar", "w")
    info = tarfile.TarInfo(f"{i:06d}.jpg"); info.size = len(b)
    tar.addfile(info, io.BytesIO(b))
tar.close()
generate
python make_data.py && du -sh files shards && ls shards | head -3

Expect two directories of a few hundred MB each and ten shard files.

  1. Upload both layouts to the S3 store.
upload.py
import glob, os, boto3
s3 = boto3.client("s3", endpoint_url="http://localhost:8333", region_name="us-east-1",
                  aws_access_key_id="lab", aws_secret_access_key="lab")
s3.create_bucket(Bucket="bench")
for p in glob.glob("shards/*.tar") + glob.glob("files/*.jpg"):
    s3.upload_file(p, "bench", p)
print("uploaded", len(s3.list_objects_v2(Bucket="bench", Prefix="shards/")["Contents"]), "shards")
  1. Write one benchmark script with four modes: local files, local shards, S3 shards and S3 small objects.
bench.py
import glob, io, sys, tarfile, time, boto3, numpy as np, torch
from PIL import Image
from torch.utils.data import Dataset, IterableDataset, DataLoader, get_worker_info
S3 = dict(endpoint_url="http://localhost:8333", region_name="us-east-1",
          aws_access_key_id="lab", aws_secret_access_key="lab")
 
def decode(b):
    a = np.asarray(Image.open(io.BytesIO(b)).convert("RGB"), dtype=np.uint8)
    return torch.from_numpy(a.copy()).permute(2, 0, 1)
 
class Files(Dataset):                                # one open() or GET per sample
    def __init__(s, remote): s.paths, s.remote = sorted(glob.glob("files/*.jpg")), remote
    def __len__(s): return len(s.paths)
    def __getitem__(s, i):
        if not s.remote: return decode(open(s.paths[i], "rb").read())
        if not hasattr(s, "c"): s.c = boto3.client("s3", **S3)   # one client per worker
        return decode(s.c.get_object(Bucket="bench", Key=s.paths[i])["Body"].read())
 
class Shards(IterableDataset):                       # sequential reads of big files
    def __init__(s, remote): s.urls, s.remote = sorted(glob.glob("shards/*.tar")), remote
    def __iter__(s):
        w = get_worker_info()
        mine = s.urls[w.id::w.num_workers] if w else s.urls     # split shards across workers
        c = boto3.client("s3", **S3) if s.remote else None
        for u in mine:
            f = c.get_object(Bucket="bench", Key=u)["Body"] if s.remote else open(u, "rb")
            with tarfile.open(fileobj=f, mode="r|") as tar:     # stream, no seeking
                for m in tar: yield decode(tar.extractfile(m).read())
 
if __name__ == "__main__":
    mode, workers = sys.argv[1], int(sys.argv[2])
    ds = {"files": Files(False), "s3files": Files(True),
          "shards": Shards(False), "s3shards": Shards(True)}[mode]
    loader = DataLoader(ds, batch_size=64, num_workers=workers)
    t, n = time.time(), 0
    for batch in loader: n += batch.shape[0]
    print(f"{mode:9s} workers={workers} samples={n} {n / (time.time() - t):7.0f} samples/s")
  1. Run the matrix. Use 4 workers (fewer if your machine has fewer than 4 cores), then repeat with 0 workers.
benchmark
for m in files shards s3shards s3files; do python bench.py $m 4; done
for m in files shards s3shards s3files; do python bench.py $m 0; done

Record every line in a table. Expect local files and local shards to be close, because your laptop's SSD and page cache hide per-file cost; S3 shards somewhat slower; and S3 small objects clearly the slowest, often by several times, because every sample pays a full HTTP round trip.

  1. Find the bottleneck with a profiler. Run each mode in a single process so the profile captures everything.
profile
python -m cProfile -s cumtime bench.py s3files 0 2>&1 | head -25
python -m cProfile -s cumtime bench.py shards 0 2>&1 | head -25

In the s3files profile, look for botocore, http.client and socket receive calls near the top of cumulative time: the loader is waiting on the network. In the shards profile, PIL's JPEG decode dominates: the loader is CPU bound, and the fix is more workers or cheaper decoding, not faster storage. For a flame graph, py-spy record -o flame.svg -- python bench.py s3files 0 works too (pip install py-spy; it needs sudo on macOS).

  1. Clean up with docker rm -f s3.

Check your work: you have a table of samples per second for four modes at two worker counts, and for at least two modes you can name the dominant cost from the profile (network wait versus decode) and the fix that follows from it.

Stretch: add a time.sleep(0.02) per batch in the loop to simulate a GPU step and find the smallest num_workers at which throughput stops improving: that is the point where the loader keeps up with the "GPU". Then rewrite the shards as Parquet with the image bytes in a column and compare.

Check yourself

Training reads 50 KB images from an object store with 32 concurrent requests and about 40 ms latency per request. Roughly what throughput can you expect, and what is the best fix?

A profile of the data loader shows most time inside JPEG decoding, with storage reads near zero. Which change helps most?

Why do streaming loaders shuffle the shard list per epoch and also keep a shuffle buffer?

A team keeps every hourly checkpoint of a 30B model at about 14 bytes per parameter for a 60-day run. Roughly how much storage does that consume?

Recap

  • The slowest stage of read, decode, transform and copy sets training speed; check with a loader-only loop and a bandwidth sum.
  • Pack samples into large shards or columnar files; millions of small files cost metadata lookups and per-request latency.
  • Object stores give throughput through concurrency and large objects, not low latency; ship manifests instead of listing.
  • Combine an object store as source of truth with parallel file systems, local NVMe and page cache as tiers.
  • Streaming needs shard-level plus buffer shuffling and recorded positions for deterministic resume.
  • Version datasets immutably with manifests, and size checkpoint storage with a retention policy from day one.

Go deeper