Sub topic 6
Operation Order and Data Types: Keep `uint8` as Long as Possible
Assume you know basic Python, NumPy arrays, image tensors, and PyTorch Dataset and DataLoader. You should also know that an image tensor often has shape (channels, height, width).
An input pipeline reads compressed files, decodes pixels, changes their size, applies transformations, and sends batches to a model. The order of these operations affects both speed and model accuracy.
Keep image data compact
Most decoded images contain unsigned 8-bit integers, written as uint8. Each channel value is an integer from 0 to 255. A pixel with red value 255 has the greatest representable red intensity.
A float32 value uses four bytes. A uint8 value uses one byte. Converting a batch to float32 before transferring it to the GPU can therefore multiply transfer traffic by four.
A useful default order is:
- Read and decode the image as
uint8. - Resize or crop while it is still
uint8. - Assemble a batch of
uint8tensors. - Transfer the batch to the GPU.
- Convert to floating point.
- Normalise and apply suitable GPU transformations.
- Pass the result to the model.
Choose the operation order carefully
Resizing before conversion to float32 usually reduces CPU work and memory use. It also avoids performing interpolation on four times as many bytes. However, the exact order must match the reference pipeline closely enough to preserve accuracy.
For example, resizing before a random crop is different from cropping before resizing. Classification pipelines often resize the shorter side and then take a crop. Detection and segmentation pipelines must also update bounding boxes or masks when an image changes size.
The table shows common operations and a practical data type.
| Operation | Common location | Typical data type |
|---|---|---|
| Decode JPEG or PNG | CPU | `uint8` |
| Resize or deterministic crop | CPU | `uint8` |
| Batch and transfer | CPU to GPU | `uint8` |
| Divide by 255 or standardise | GPU | `float32` or lower precision |
| Neural augmentation | GPU | floating point |
Convert and normalise on the GPU
The following example keeps the batch compact during the host-to-device copy. The mean and standard deviation are scaled to the original 0–255 range, so subtraction can happen immediately after conversion.
import torch
def prepare_batch(batch_uint8, device="cuda"):
# batch_uint8 has shape (B, 3, H, W) and values from 0 to 255.
mean = torch.tensor(
[0.485, 0.456, 0.406], device=device
).view(1, 3, 1, 1) * 255.0
std = torch.tensor(
[0.229, 0.224, 0.225], device=device
).view(1, 3, 1, 1) * 255.0
batch = batch_uint8.to(device, non_blocking=True).float()
return (batch - mean) / std
if __name__ == "__main__":
batch = torch.randint(0, 256, (8, 3, 224, 224), dtype=torch.uint8)
output = prepare_batch(batch, device="cuda" if torch.cuda.is_available() else "cpu")
print(output.shape, output.dtype)The GPU still performs the floating-point conversion and normalisation. The CPU sends fewer bytes, which can help when the input pipeline or host-to-device link is the bottleneck.
Avoid accidental copies
Conversions can create new allocations. Check tensor shape, layout, and dtype at each boundary. A NumPy array is commonly arranged as (height, width, channels), while PyTorch models usually expect (channels, height, width). Move the channel dimension once, then avoid repeated permutations and conversions.
Exercise
A uint8 batch has shape (64, 3, 224, 224). Why is it usually better to transfer it before converting it to float32?
Show answer
Each element uses one byte as uint8 but about four bytes as float32, so transferring first reduces host-to-device traffic. Convert and normalise on the GPU afterward.