Sub topic 14
Caching Decoded or Resized Data and Sharded Storage Formats
This chapter assumes basic Python, NumPy, image tensors, and PyTorch Dataset and DataLoader. It also assumes you can identify the resize and normalization steps your model expects.
Why cache image preprocessing?
JPEG and PNG files save disk space, but every training epoch must decode them. Resizing also repeats work when the resize policy does not change. A cache stores an intermediate result, such as a decoded image or a resized uint8 array, so later epochs skip those operations.
Caching helps most when:
- The same images are read for many epochs.
- The dataset fits on local SSD or a fast shared filesystem.
- CPU decoding or resizing is the input bottleneck.
- The resize size and interpolation method stay fixed.
A resized RGB image of shape 224 × 224 uses about 150 KB as uint8 data:
224 × 224 × 3 × 1 byte = 150,528 bytesA cache can therefore be much larger than the original JPEG dataset. Measure the storage cost before caching the entire corpus.
Choose what to cache
Caching decoded full-resolution images uses the most space and may still leave resizing work. Caching the final resized pixels usually gives a better balance for classification, where every sample has the same input size.
Do not cache random training augmentations such as crop position or color jitter unless you deliberately want fixed augmentation. Cache deterministic work first, then apply random augmentation during loading.
| Cache item | Benefit | Main cost |
|---|---|---|
| Decoded full-resolution pixels | Avoids image decoding | Large storage and later resize work |
| Resized `uint8` pixels | Avoids decoding and resizing | Tied to one size and interpolation policy |
| Normalized `float32` tensors | Minimal model-side work | Four times the pixel storage of `uint8` |
Design a valid cache
A cache key must include every input that changes the result. Include the source identity, source modification time or content hash, output size, interpolation method, color policy, and preprocessing version. If any of these changes, create a new cache entry.
The following example stores resized RGB arrays as .npy files. The source path and preprocessing settings form the cache key.
from pathlib import Path
import hashlib
import numpy as np
from PIL import Image
def cache_key(path, size=(224, 224), version="resize-v1"):
source = Path(path)
text = f"{source.resolve()}|{source.stat().st_mtime_ns}|{size}|{version}"
return hashlib.sha256(text.encode()).hexdigest()
def load_resized(path, cache_dir, size=(224, 224)):
cache_dir = Path(cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
target = cache_dir / f"{cache_key(path, size)}.npy"
if target.exists():
return np.load(target, mmap_mode="r")
with Image.open(path) as image:
image = image.convert("RGB")
image = image.resize(size, Image.Resampling.BILINEAR)
array = np.asarray(image, dtype=np.uint8).copy()
temporary = target.with_suffix(".tmp.npy")
np.save(temporary, array)
temporary.replace(target)
return arrayThe temporary filename and atomic replacement prevent a worker from observing a partly written file. For multiple machines, use a coordinated writer or write caches separately on each machine.
Shard many samples into fewer files
A directory containing millions of small cache files can become slow because each lookup requires filesystem metadata operations. A sharded format groups many samples into larger files. Common choices include tar-based datasets, LMDB, SQLite, and record formats provided by training frameworks.
Shards improve sequential reading and reduce directory overhead. They make individual samples less convenient to replace, however. They also require a shard index or key-to-location mapping for efficient random access.
For distributed training, consider shard size and worker assignment. Very large shards reduce metadata overhead but can cause workers to contend for the same file. Moderate shards allow each worker or rank to read different files. Store shards on local NVMe when possible, and profile network storage separately.
Verify the cache
Compare cached output with the reference pipeline on a sample of images. Check shape, data type, channel order, and pixel differences. A small difference caused by a changed interpolation method may be acceptable only if validation confirms it does not affect accuracy.
Exercise
Your JPEG dataset is read for 50 epochs, and profiling shows resizing consumes most CPU time. Should you cache normalized float32 tensors or resized uint8 arrays first, and why?
Show answer
Cache resized uint8 arrays first. They skip decoding and resizing while using less storage and leaving normalization flexible. Measure again before deciding whether to cache later stages.