Note
This page was generated from the docs/torchvision/dali_extensions.ipynb Jupyter notebook. You can run it locally or open it in Google Colab, see Running the Examples for more information. To prepare Colab for this exact documentation revision, run this cell before the tutorial:
setup_url = (
"https://raw.githubusercontent.com/NVIDIA/DALI/"
"4e6e70d/docs/examples/colab_setup.py"
)
!curl -sSL $setup_url -o colab_setup.py
%run colab_setup.py --ref 4e6e70d
DALI Extensions#
The DALI implementation extends the original TorchVision API with additional parameters that provide fine-grained control over pipeline execution:
Parameter |
Scope |
Default |
Description |
|---|---|---|---|
|
Each operator |
|
Target execution device: |
|
|
|
Maximum number of samples processed per pipeline call, at least 1. If not set, every call processes a single sample, as in TorchVision |
|
|
half of the CPU cores (1 on a single-core machine) |
Number of CPU threads used by the DALI pipeline. It directly affects the throughput of CPU operators, so tune it to the cores available to your process |
|
|
|
Layout of the input: |
Note
Operators inside a single Compose may switch from CPU to GPU (the data is copied to the GPU), but not back: once an operator runs on the GPU, all following operators must also use device="gpu".
Note
NCHW and NFCHW (batched input) are extensions to TorchVision, see Batch processing and Supported data.
Setup#
Import the DALI TorchVision API (object-oriented as dtv, functional as dtv_fn) alongside the standard TorchVision counterparts for comparison.
[1]:
import torch
import torchvision.transforms.v2 as tv
import torchvision.transforms.v2.functional as tv_fn
from PIL import Image
import numpy as np
# DALI TorchVision API — object-oriented
import nvidia.dali.experimental.torchvision as dtv
# DALI TorchVision API — functional
import nvidia.dali.experimental.torchvision.v2.functional as dtv_fn
print("DALI operators available:", dtv.__all__)
print("DALI functional ops available:", dtv_fn.__all__)
DALI operators available: ['CenterCrop', 'ColorJitter', 'Compose', 'GaussianBlur', 'Grayscale', 'InterpolationMode', 'Normalize', 'Pad', 'PILToTensor', 'RandomApply', 'RandomCrop', 'RandomGrayscale', 'RandomHorizontalFlip', 'RandomResizedCrop', 'RandomVerticalFlip', 'Resize', 'ToPILImage', 'ToPureTensor']
DALI functional ops available: ['center_crop', 'crop', 'gaussian_blur', 'get_dimensions', 'get_image_size', 'get_size', 'horizontal_flip', 'normalize', 'pad', 'pil_to_tensor', 'resize', 'resized_crop', 'rgb_to_grayscale', 'to_grayscale', 'to_pil_image', 'to_tensor', 'vertical_flip']
[2]:
# A sample image, as a CHW uint8 tensor and as a PIL Image
ramp = torch.linspace(0, 255, 64)
tensor_img = torch.stack(
[
ramp.expand(64, 64),
ramp[:, None].expand(64, 64),
(ramp + ramp[:, None]) / 2,
]
).to(torch.uint8)
pil_img = Image.fromarray(tensor_img.permute(1, 2, 0).numpy())
GPU pipeline#
Operators accept an additional device parameter, "cpu" (default) or "gpu". The output tensor resides on the device that the last operator was executed on. Pass device="gpu" to all operators to run the whole pipeline on the GPU. Switching from CPU to GPU within a Compose copies the data to the GPU and can degrade performance, see the Note at the top of this page for the restriction on switching back.
[3]:
if torch.cuda.is_available():
pipeline_gpu = dtv.Compose(
[
dtv.Resize(size=(32, 32), device="gpu"),
dtv.Pad(padding=4, padding_mode="reflect", device="gpu"),
]
)
# Input tensor on GPU
tensor_gpu = tensor_img.cuda()
out_gpu = pipeline_gpu(tensor_gpu)
print("Output device:", out_gpu.device)
print("Output shape :", out_gpu.shape)
# Compare to CPU reference
pipeline_cpu = dtv.Compose(
[
dtv.Resize(size=(32, 32), device="cpu"),
dtv.Pad(padding=4, padding_mode="reflect", device="cpu"),
]
)
out_cpu = pipeline_cpu(tensor_img)
print(
"Max absolute diff (cpu vs gpu):",
(out_cpu.int() - out_gpu.cpu().int()).abs().max().item(),
)
else:
print("CUDA not available — skipping GPU example.")
Output device: cuda:0
Output shape : torch.Size([3, 40, 40])
Max absolute diff (cpu vs gpu): 1
GPU functional API#
The functional API also accepts a device parameter.
[4]:
if torch.cuda.is_available():
tensor_gpu = tensor_img.cuda()
resized_gpu = dtv_fn.resize(tensor_gpu, size=[32, 32], device="gpu")
flipped_gpu = dtv_fn.horizontal_flip(tensor_gpu, device="gpu")
print("resize (gpu):", resized_gpu.shape, resized_gpu.device)
print("hflip (gpu):", flipped_gpu.shape, flipped_gpu.device)
else:
print("CUDA not available — skipping GPU functional example.")
resize (gpu): torch.Size([3, 32, 32]) cuda:0
hflip (gpu): torch.Size([3, 64, 64]) cuda:0
Batch processing#
Set batch_size on Compose to process multiple samples in a single pipeline run. The input must be a torch.Tensor of shape (N, C, H, W), or (N, F, C, H, W) for sequences, where N ≤ batch_size. Every sample in the batch gets its own random parameters (e.g. each image is flipped independently). This is an extension to TorchVision, where a tensor is always a single sample and a batch is a Python loop over samples.
[5]:
BATCH = 4
# Create a batch of N=4 images (NCHW)
batch = tensor_img.unsqueeze(0).repeat(BATCH, 1, 1, 1) # (4, 3, 64, 64)
print("Input batch shape:", batch.shape)
pipeline_batch = dtv.Compose(
[
dtv.Resize(size=(32, 32)),
dtv.RandomHorizontalFlip(p=0.5),
],
batch_size=BATCH,
)
out_batch = pipeline_batch(batch)
print("Output batch shape:", out_batch.shape) # (4, 3, 32, 32)
Input batch shape: torch.Size([4, 3, 64, 64])
Output batch shape: torch.Size([4, 3, 32, 32])