Sub topic 14
Caching decoded or resized data and sharded storage formats
This chapter assumes you can write a PyTorch Dataset and DataLoader, and that you know the earlier stages of the pipeline: decoding, resizing, and collation. It covers what to do when decoding and resizing are still the bottleneck after the optimisations in earlier chapters. The answer is to pay the cost once and store the result.
Why caching helps
During training you read every image once per epoch. If you train for 30 epochs, a JPEG is decoded and resized 30 times, and the result is the same each time unless a random augmentation changes it. Any step that does not depend on randomness can be done once and saved.
There are two separate costs to reduce:
- CPU work: decoding and resizing.
- I/O work: opening many small files, which is slow on network drives and spinning disks.
Different caching strategies attack different costs, so first look at your profile from the earlier chapter on measurement. If decoding dominates, cache decoded or resized data. If file opening dominates, pack files into shards.
What can safely be cached
The rule is simple: cache only what comes before the first random operation.
| Step | Deterministic? | Cache it? |
|---|---|---|
| JPEG decode | Yes | Yes |
| Resize to a fixed size | Yes | Yes, if the model always uses that size |
| Random crop, flip, colour jitter | No | No, apply after loading |
| Normalisation | Yes | Usually no, keep uint8 and normalise on the GPU |
If you cache a resized image and then apply random crops, you can only crop from the cached size. A common pattern is to cache at a slightly larger size than the model input, for example 256 pixels on the short side for a 224 pixel crop, and augment from there. This changes what augmentation sees compared with random-resized-crop on the full-resolution original, so treat it as a design decision and check accuracy.
Option 1: cache in memory
The simplest cache is a Python dictionary or a NumPy array that holds uint8 pixels. A uint8 image at 224 × 224 × 3 is 150,528 bytes. One million images need about 150 GB, which is too much for most machines, while 100,000 images need about 15 GB.
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
class InMemoryDataset(Dataset):
def __init__(self, paths, labels, size=(224, 224)):
self.labels = labels
self.images = np.empty((len(paths), size[1], size[0], 3), dtype=np.uint8)
for i, p in enumerate(paths):
with Image.open(p) as im:
im = im.convert("RGB").resize(size, Image.Resampling.BILINEAR)
self.images[i] = np.asarray(im)
def __len__(self):
return len(self.labels)
def __getitem__(self, i):
# The array is copied so the caller can modify the result safely.
return self.images[i].copy(), self.labels[i]Be aware of two gotchas with worker processes:
- On Linux, workers are created with
fork, so they share the parent's memory pages copy-on-write. A large NumPy array is shared without being duplicated. A list of Python objects is different: reference counting writes to each object, which gradually forces pages to be copied. Store pixels in one big array, not in a list of arrays. - On macOS and Windows, workers use
spawn, so the dataset is pickled and sent to each worker. Each worker then holds its own copy. Usenumpy.memmap(next section) instead.
Option 2: cache on disk as raw arrays
When the decoded dataset does not fit in RAM, write it to a file and let the operating system's page cache decide which parts stay in memory. A memory-mapped file looks like an array but reads from disk on demand.
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
def build_cache(paths, out_file, size=(224, 224)):
n = len(paths)
arr = np.lib.format.open_memmap(
out_file, mode="w+", dtype=np.uint8, shape=(n, size[1], size[0], 3)
)
for i, p in enumerate(paths):
with Image.open(p) as im:
im = im.convert("RGB").resize(size, Image.Resampling.BILINEAR)
arr[i] = np.asarray(im)
arr.flush()
class MemmapDataset(Dataset):
def __init__(self, cache_file, labels):
self.cache_file = cache_file
self.labels = labels
self.arr = None # opened lazily, once per worker process
def __len__(self):
return len(self.labels)
def __getitem__(self, i):
if self.arr is None:
self.arr = np.load(self.cache_file, mmap_mode="r")
return np.array(self.arr[i]), self.labels[i]Opening the memmap inside __getitem__ means each worker opens its own handle after it starts. This avoids sharing a file handle across a fork.
The trade-off is size. Raw pixels are much larger than JPEG. A JPEG at 224 × 224 is often 10 to 20 KB, against 150 KB raw, so the cache is roughly 8 to 15 times larger. You exchange disk space and read bandwidth for CPU time. On a fast NVMe drive this is usually a good trade. On a slow network drive it can be worse than decoding JPEGs, because you now read more bytes.
Option 3: re-encode at a smaller size
A middle path is to resize once and save the result as a JPEG. You keep the small file size and still skip the expensive full-resolution decode, because decoding a 256-pixel JPEG is far cheaper than decoding a 4000-pixel one.
from pathlib import Path
from PIL import Image
def make_small_copies(paths, out_dir, short_side=256, quality=95):
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
for p in paths:
with Image.open(p) as im:
im = im.convert("RGB")
w, h = im.size
scale = short_side / min(w, h)
new_size = (round(w * scale), round(h * scale))
im = im.resize(new_size, Image.Resampling.LANCZOS)
im.save(out_dir / (Path(p).stem + ".jpg"), quality=quality)This is lossy twice: once in the original JPEG and again in your copy. Use a high quality setting, and use a lossless format such as PNG if you want to avoid the second loss. The trade-off for PNG is a larger file and a slower decode.
Option 4: sharded storage formats
Reading a million small files is slow even when each decode is fast. Each file needs a directory lookup, an open call, and a separate read. On network storage this is often the real bottleneck. Sharding groups many samples into a small number of large files, typically 100 MB to 1 GB each, so reads become long and sequential.
Common formats work on this idea:
- WebDataset: plain TAR files where related files share a key, such as
0001.jpgand0001.cls. - TFRecord: a record-oriented format from TensorFlow, also readable from PyTorch.
- Parquet or Arrow: columnar formats that can store image bytes next to labels.
- LMDB or similar key-value stores: one file with random access by key.
- Streaming libraries: several libraries build on shards and add shuffling and resumption.
The code below writes a minimal sharded layout using only the standard library. It stores the original JPEG bytes, so no quality is lost and no decode is skipped, but file-open overhead disappears.
import tarfile
import io
from pathlib import Path
def write_shards(paths, labels, out_dir, samples_per_shard=1000):
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
for shard_id, start in enumerate(range(0, len(paths), samples_per_shard)):
shard_name = out_dir / f"shard-{shard_id:05d}.tar"
with tarfile.open(shard_name, "w") as tar:
for i in range(start, min(start + samples_per_shard, len(paths))):
key = f"{i:09d}"
data = Path(paths[i]).read_bytes()
info = tarfile.TarInfo(f"{key}.jpg")
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
label = str(labels[i]).encode()
info = tarfile.TarInfo(f"{key}.cls")
info.size = len(label)
tar.addfile(info, io.BytesIO(label))Shuffling with shards
Sequential reads make random shuffling harder. If you read a shard from start to finish, consecutive samples are always neighbours in the file, and they are often from the same class or the same folder. Use a two-level shuffle:
- Shuffle the order of the shards each epoch.
- Keep a buffer of a few thousand samples and draw from it at random.
A larger buffer gives better shuffling but uses more memory. Also write the shards from a randomly shuffled list of samples. If you write them in sorted-by-class order, a small buffer cannot undo that.
Choosing an approach
Keeping the cache correct
A cache is a copy of derived data, and a stale copy produces wrong results without any error message. Guard against these common problems:
- Changed preprocessing: if you change the resize size, interpolation method, or colour conversion, the cache no longer matches the reference pipeline. Put these settings in the cache file name or in a small metadata file, and refuse to load a cache whose settings differ.
- Changed source data: if images are added, removed, or reordered, the index of the cache no longer matches your labels. Store the list of source paths with the cache and compare it at load time.
- Partial writes: a build that crashes halfway leaves a file that looks valid. Write to a temporary name and rename it when complete.
- Augmentation baked in: never cache the output of a random transform.
import json, hashlib
def cache_key(paths, size, interp):
meta = {"size": list(size), "interp": interp, "n": len(paths),
"paths_hash": hashlib.sha256("\n".join(paths).encode()).hexdigest()}
return hashlib.sha256(json.dumps(meta, sort_keys=True).encode()).hexdigest()[:16]After building a cache, run the equivalence check from the final chapter. Compare a sample of cached images with the output of the reference pipeline. For a deterministic cache built with the same library and settings, the arrays should match exactly. If you re-encoded to JPEG, expect small differences and compare with a tolerance.
Summary of trade-offs
| Strategy | CPU saved | I/O effect | Disk use | Main risk |
|---|---|---|---|---|
| In-memory uint8 | Decode and resize | None after build | None | RAM limit |
| Memmap raw array | Decode and resize | More bytes read | Large | Slow disks |
| Smaller JPEG copies | Most of decode | Fewer bytes read | Small | Second lossy step |
| Sharded originals | None | Far fewer opens | Same as originals | Shuffling quality |
Exercise
You have 400,000 photos of about 12 megapixels each, stored on a network drive. Your model takes 224 × 224 input, and you train for 40 epochs with random flips only. The profile shows 70% of each step is spent decoding. Which strategy would you pick, and what would you check before committing to it?
Show answer
Resize once to a fixed size and cache it. Raw uint8 at 224 × 224 × 3 is about 150 KB per image, so 400,000 images take about 60 GB. That fits on a local NVMe disk and can be memory-mapped, but probably not in the RAM of a typical machine. Random flips are cheap and can be applied after loading, so nothing random needs to be baked in. Before committing, check that local disk read speed is enough for your batch rate, that you have 60 GB free, and that cached images match the reference pipeline on a sample. If local disk is not available, re-encode to 256-pixel JPEGs and shard them into TAR files instead.
Exercise
A teammate caches images after applying RandomResizedCrop to save time. Why does this hurt training, and how would you fix it?
Show answer
The crop is random, so every epoch would show the model the same crop of each image. This removes the augmentation and can cause overfitting. Cache only the deterministic part, such as the resize to a slightly larger fixed size, and apply the random crop after loading from the cache.