Skip to main content

1. What is Inference?

Inference means using a trained model to make predictions on new data.
Example:
When the number of inputs becomes large, processing them one by one can be slow.

2. What is Batch Inference?

Instead of processing one sample at a time:
multiple samples are processed together:
This is called batch inference.

3. Why Use Batching?

Batching can:
  • Improve GPU utilization
  • Reduce inference overhead
  • Process large datasets efficiently
  • Make better use of available hardware
Example:

4. PyTorch DataLoader

DataLoader makes it easy to load data in batches.
Example:
This means:

5. Batch Size

Batch size determines how many samples are processed together. Example:
Processes one sample at a time.
Processes 32 samples at a time.
Processes 128 samples at a time. Larger batch sizes can improve throughput, but they require more memory.

6. GPU Inference

A GPU can perform many mathematical operations in parallel.
PyTorch can select the available device:
Then the model can be moved to the GPU:

7. Multi-GPU Inference

If multiple GPUs are available, inference can be distributed across them. Example:
This can increase inference throughput for large workloads. For simple learning, DataParallel can distribute a batch across multiple GPUs.

8. Simple Scaling Example

The following example creates a large dataset and performs inference in batches.

scale_demo.py


9. Install Dependencies

Run:
output on CPU:
On a CUDA-enabled system:

10. Understanding the Important Parts

Create dataset

Creates 10,000 samples, with 100 features each.

Create batches

The dataset is divided into batches of 64. Approximately:

Move input to GPU

Moves the batch to CPU or GPU depending on the selected device.

Disable gradients

Gradients are not required during inference, so this reduces memory usage and computation.

Generate predictions

The model processes an entire batch instead of one sample.

Store predictions

The results are moved back to CPU memory and stored.

Combine results

Combines all batch predictions into one tensor.

11. Multi-GPU Part

This section enables simple multi-GPU processing:
For example, with two GPUs:
If only one GPU or CPU is available, the code continues normally.

12. CPU vs GPU

For large neural network inference, GPUs can provide much higher throughput.

13. Scaling Inference Flow

With multiple GPUs:

14. Main Learning

The key concepts are:
Main takeaway: Batch inference processes multiple inputs together, while GPU and multi-GPU execution can increase the number of predictions processed per unit of time.