PyTorch predict single example
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Predicting a single example in PyTorch uses the same model as batch prediction, but you still have to respect the model’s expected tensor shape, device, and evaluation mode. The most common mistakes are forgetting the batch dimension or leaving the model in training mode. Once those are handled, single-example inference is straightforward.
Put the Model in Evaluation Mode
Before inference, switch the model to evaluation mode.
model.eval() matters because layers such as dropout and batch normalization behave differently during training and inference.
If you loaded trained weights, do that first:
Add a Batch Dimension
PyTorch models usually expect input with a batch dimension, even if you only want one sample.
Without unsqueeze(0), the tensor shape is just [4], which often does not match what the network expects.
Run Inference with torch.no_grad()
Wrap prediction in torch.no_grad() so PyTorch does not build a gradient graph unnecessarily.
This is the standard pattern for inference:
- prepare the tensor
- switch the model to eval mode
- call the model inside
torch.no_grad() - post-process the output
Convert Raw Output into Probabilities
For classification, model outputs are often logits rather than human-readable probabilities.
Use softmax only if you actually want probabilities for reporting or thresholding. If you only need the top class, argmax on logits is enough.
Example with an Image Tensor
For image models, the same rules apply but the shape is usually [batch, channels, height, width].
The extra batch dimension is still required even for one image.
In real code, do not forget the same preprocessing used during training, such as resize, normalization, and channel order.
Match Device and Dtype
If the model is on GPU, the input must also be on GPU.
The same applies to data types. A model trained on float32 inputs should usually receive float32 tensors at inference time.
If you loaded label names separately, this is also the stage where you map the predicted class index back to a human-readable label before returning or displaying the result.
Common Pitfalls
The most common mistake is forgetting the batch dimension. A single sample still usually needs shape [1, features] or [1, channels, height, width].
Another issue is skipping model.eval(), which can make predictions unstable when dropout or batch normalization is involved.
Some developers also run inference without torch.no_grad(). The code still works, but it wastes memory and computation by tracking gradients that are never used.
Finally, make sure preprocessing at prediction time matches training. If the model was trained on normalized inputs and you feed raw values, the prediction can be wrong even though the code runs.
Summary
- Call
model.eval()before single-example inference. - Add a batch dimension with
unsqueeze(0). - Use
torch.no_grad()during prediction. - Apply
argmaxorsoftmaxdepending on how you want to interpret the output. - Keep tensor shape, device, dtype, and preprocessing consistent with training.
Related reading
- Pytorch RuntimeError CUDA out of memory with a huge amount of free memory
- Pytorch RuntimeError reduce failed to synchronize cudaErrorAssert device-side assert triggered
- PyTorch torch.no_grad vs torch.inference_mode
- PyTorch using LR-Scheduler with param groups of different LR's
- Pytorch RuntimeError expected scalar type Float but found Byte
- PyTorch torch.no_grad versus requires_gradFalse
- Pytorch ValueError optimizer got an empty parameter list
- PyTorch What's the difference between state_dict and parameters?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.