Sub topic 6
Operation order and data types: keep uint8 as long as possible
This chapter assumes you can write basic PyTorch and NumPy code, know that a decoded image is an array of shape height × width × channels, and have used a Dataset with a DataLoader. It covers the order of preprocessing steps and the data type each step works on. Both affect CPU time, memory traffic, and whether the model sees the inputs you intended.
The working model: bytes moved and values touched
A decoded RGB image from a JPEG holds integers from 0 to 255, so it fits in uint8, one byte per value. Normalisation turns those into floating-point numbers. A float32 value takes four bytes, so the same image becomes four times larger.
Every later stage pays for that size: copies between processes, the pinned-memory copy, the bus transfer, and any arithmetic. Two rules follow.
- Do work that shrinks the image (crop, resize) before work that grows it (float conversion).
- Do work that needs floating point (normalisation, blending) as late as possible, ideally on the GPU.
Here is the memory for a batch of 64 images at 224 × 224 × 3.
| Data type | Bytes per image | Batch of 64 |
|---|---|---|
| uint8 | 150,528 | 9.2 MiB |
| float16 | 301,056 | 18.4 MiB |
| float32 | 602,112 | 36.8 MiB |
| float64 | 1,204,224 | 73.5 MiB |
The float64 row is not a typo you can ignore. NumPy creates float64 arrays by default, so careless arithmetic quietly doubles your float32 cost.
Why resize before converting to float
Suppose a source image is 1920 × 1080 and the model takes 224 × 224. Converting to float32 first processes 6,220,800 values and allocates about 23.7 MiB. Resizing first means the conversion touches only 150,528 values. The following script compares both orders on a synthetic image.
import time
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
rng = np.random.default_rng(0)
src = rng.integers(0, 256, size=(1080, 1920, 3), dtype=np.uint8)
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32) * 255
std = np.array([0.229, 0.224, 0.225], dtype=np.float32) * 255
def normalise_then_resize(arr):
x = (arr.astype(np.float32) - mean) / std # full-size float32
t = torch.from_numpy(x).permute(2, 0, 1).unsqueeze(0)
out = F.interpolate(t, size=(224, 224), mode="bilinear",
antialias=True, align_corners=False)
return out[0]
def resize_then_normalise(arr):
im = Image.fromarray(arr).resize((224, 224), Image.Resampling.BILINEAR)
x = (np.asarray(im).astype(np.float32) - mean) / std # small float32
return torch.from_numpy(x).permute(2, 0, 1)
def bench(fn, repeats=5):
fn(src) # warm-up
t0 = time.perf_counter()
for _ in range(repeats):
fn(src)
return (time.perf_counter() - t0) / repeats * 1e3
a = normalise_then_resize(src)
b = resize_then_normalise(src)
print(f"normalise first: {bench(normalise_then_resize):.1f} ms")
print(f"resize first: {bench(resize_then_normalise):.1f} ms")
print(f"max abs difference: {(a - b).abs().max().item():.4f}")Resize-first is usually much faster. The two outputs are not bit-identical. The resize-first path rounds to integers after resampling, and PIL and PyTorch implement the resampling filter differently. The difference is small, but it is real. The last chapter of this tutorial shows how to decide whether such a difference matters.
The standard order
A typical training pipeline runs in this order.
- Decode to RGB
uint8. Convert palette, grayscale, and RGBA images withconvert("RGB")so every image has three channels. - Crop. Random crops cut the pixel count before any resampling.
- Resize with a
uint8-capable library such as PIL. - Flip or rotate by 90 degrees. These are pure memory rearrangements and exact on
uint8. - Collate into a
uint8batch and copy it to the GPU. - Convert to float and normalise on the GPU.
- Apply operations that need floats, such as mixup (blending two images) or Gaussian noise.
Colour jitter can run either side of the float conversion. On uint8, each operation rounds and clamps to 0–255. On float, you can chain several operations and clamp once. Pick one place and use it the same way in training and inference.
Combine crop and resize into one resampling pass
Each uint8 resize rounds its output. Resizing twice, for example a resize followed by a random resized crop, accumulates rounding and blurs the image more than needed. PIL's resize accepts a box argument that crops and resamples in one step.
from PIL import Image
def crop_resize(im, box, size=(224, 224)):
# box = (left, upper, right, lower) in source pixel coordinates
return im.resize(size, Image.Resampling.BILINEAR, box=box)This is both faster and sharper than cropping into a new image and then resizing it.
Fold normalisation into one multiply and subtract
Many pipelines divide by 255 and then subtract the mean and divide by the standard deviation. You can do this in one step by expressing the mean and standard deviation on the 0–255 scale. The next script shows the two forms agree and picks the GPU if one is present.
import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
mean01 = torch.tensor([0.485, 0.456, 0.406], device=device).view(1, 3, 1, 1)
std01 = torch.tensor([0.229, 0.224, 0.225], device=device).view(1, 3, 1, 1)
mean255, std255 = mean01 * 255, std01 * 255
batch = torch.randint(0, 256, (8, 3, 224, 224), dtype=torch.uint8, device=device)
two_step = (batch.float() / 255 - mean01) / std01
one_step = (batch.float() - mean255) / std255
print(torch.allclose(two_step, one_step, atol=1e-5))The .float() call here makes a float32 copy, then each arithmetic operation makes another. For very large batches you can use in-place operations (sub_, div_) on the converted tensor to avoid extra allocations.
Common errors
Silent wrap-around in uint8 arithmetic
Integer types do not saturate. Values wrap modulo 256.
import numpy as np
a = np.array([250], dtype=np.uint8)
print(a + 10) # [4], not 260 and not 255
print(a - 251) # [255], not -1If you subtract a mean while still in uint8, the result is garbage with no error. Convert to float before arithmetic, or use a library function that clamps.
Hidden float64
arr / 255 in NumPy returns float64. Writing arr.astype(np.float32) / 255 keeps float32. Passing a float64 array to torch.from_numpy gives a float64 tensor, and the model will fail with a dtype mismatch or run slowly if you cast it. Check .dtype at the boundary.
Scaling the values twice, or not at all
Mean and standard deviation values such as 0.485 assume pixel values in the 0–1 range. If you subtract 0.485 from values in 0–255, the model sees inputs about 255 times too large. If you divide by 255 and also use mean values multiplied by 255, the inputs collapse to near zero. Decide the scale once and write it in one place.
Non-contiguous tensors after permute
torch.from_numpy(arr).permute(2, 0, 1) returns a view with unusual strides, not a rearranged copy. Collation copies it into a contiguous batch, so this is usually harmless. It matters if you call .view() on the tensor (which fails) or pass it to code that expects contiguous memory. Call .contiguous() when you need that guarantee.
Read-only arrays
np.asarray(im) on a PIL image can give an array you cannot write to, and torch.from_numpy warns about it. np.array(im, dtype=np.uint8), as used in the Dataset earlier in this tutorial, makes a writable copy.
Reduced-precision storage
Integers up to 2048 are exact in float16, so raw 0–255 pixels survive. Normalised values lose precision in float16 and more in bfloat16. Normalise in float32, then cast to the model's precision.
Other bit depths
16-bit PNG images (common in medical and satellite data) do not fit in uint8. Rescaling them to 8 bits throws away information that may matter. Keep them as uint16 through decoding, then convert to float32 before arithmetic, because PyTorch support for unsigned 16-bit operations is limited.
Decision criteria
- If the CPU is the bottleneck, move conversion and normalisation to the GPU, so workers return
uint8. - If the model must see exactly the same pixels as a reference pipeline, keep the same resize library and the same order, even if another order is faster.
- If augmentations need float (mixup, blur with float kernels), apply them on the GPU after normalisation.
- If a step can run on
uint8without a rounding or clamping problem, leave it there.
Exercise
A 3840 × 2160 RGB image is decoded and the model needs 224 × 224. How many bytes does the float32 data take if you convert before resizing, and how many if you convert after? Which order is better, and what is the size ratio?
Show answer
Before resizing, there are 3840 × 2160 × 3 = 24,883,200 values, so 99,532,800 bytes (about 95 MiB) in float32. After resizing, there are 224 × 224 × 3 = 150,528 values, so 602,112 bytes. Resizing first is better, because the float data is about 165 times smaller (8,294,400 / 50,176 pixels). Resizing in uint8 also means the resize reads 1 byte per value instead of 4.
Exercise
Your pipeline runs arr = np.array(im); x = (arr - 123.7) / 58.4 and then torch.from_numpy(x). The model raises a dtype error because it expects float32. What went wrong, and how do you fix it without adding an extra copy?
Show answer
Subtracting a Python float from a uint8 array gives float64 in NumPy, so the tensor is float64. Fix it by converting once with arr.astype(np.float32) before the arithmetic and using float32 constants (or, better, return the uint8 tensor from the worker and convert to float32 on the GPU).