I disagree with these answers: OP's question appears to be focused on how he should use a model trained in lightning to get predictions in general, rather than for a specific step in the training pipeline. In which case, a user shouldn't need to go anywhere near a Trainer object - those are not intended to be used for general prediction and the answers above are therefore encouraging an anti-pattern (carrying a trainer object around with us every time we want to do some prediction) to anyone who reads these answers in the future.

Instead of using trainer, we can get predictions straight from the Lightning module that has been defined: if I have my (trained) instance of the lightning module model = Net(...) then using that model to get predictions on inputs x is achieved simply by calling model(x) (so long as the forward method has been implemented/overriden on the Lightning module - which is required).

In contrast, Trainer.predict() is not the intended means of obtaining predictions using your trained model in general. The Trainer API provides methods to tune, fit and test your LightningModule as part of your training pipeline, and it looks to me that the predict method is provided for ad-hoc predictions on separate dataloaders as part of less 'standard' training steps.

The OP's question (Do I need a specific predict function or is there any already implemented way I don't see?) implies that they're not familiar with the way that the forward() method works in PyTorch, but asks whether there's already a method for prediction that they can't see. A full answer therefore requires a further explanation of where the forward() method fits into the prediction process:

The reason model(x) works is because Lightning Modules are subclasses of torch.nn.Module and these implement a magic method called __call__() which means that we can call the class instance as if it were a function. __call__() in turn calls forward(), which is why we need to override that method in our Lightning module.

NB. because forward is only one piece of the logic called when we use model(x), it is always recommended to use model(x) instead of model.forward(x) for prediction unless you have a specific reason to deviate.

Answer from UpstatePedro on Stack Overflow
🌐
Lightning AI
lightning.ai › docs › pytorch › stable › levels › core_level_6.html
Level 6: Predict with your model — PyTorch Lightning 2.6.1 documentation
Learn the basics of predicting with Lightning. ... Learn to use pure PyTorch without the Lightning dependencies for prediction.
Top answer
1 of 4
15

I disagree with these answers: OP's question appears to be focused on how he should use a model trained in lightning to get predictions in general, rather than for a specific step in the training pipeline. In which case, a user shouldn't need to go anywhere near a Trainer object - those are not intended to be used for general prediction and the answers above are therefore encouraging an anti-pattern (carrying a trainer object around with us every time we want to do some prediction) to anyone who reads these answers in the future.

Instead of using trainer, we can get predictions straight from the Lightning module that has been defined: if I have my (trained) instance of the lightning module model = Net(...) then using that model to get predictions on inputs x is achieved simply by calling model(x) (so long as the forward method has been implemented/overriden on the Lightning module - which is required).

In contrast, Trainer.predict() is not the intended means of obtaining predictions using your trained model in general. The Trainer API provides methods to tune, fit and test your LightningModule as part of your training pipeline, and it looks to me that the predict method is provided for ad-hoc predictions on separate dataloaders as part of less 'standard' training steps.

The OP's question (Do I need a specific predict function or is there any already implemented way I don't see?) implies that they're not familiar with the way that the forward() method works in PyTorch, but asks whether there's already a method for prediction that they can't see. A full answer therefore requires a further explanation of where the forward() method fits into the prediction process:

The reason model(x) works is because Lightning Modules are subclasses of torch.nn.Module and these implement a magic method called __call__() which means that we can call the class instance as if it were a function. __call__() in turn calls forward(), which is why we need to override that method in our Lightning module.

NB. because forward is only one piece of the logic called when we use model(x), it is always recommended to use model(x) instead of model.forward(x) for prediction unless you have a specific reason to deviate.

2 of 4
7

You can try prediction in two ways:

  1. Perform batched prediction as per normal.
test_dataset = Dataset(test_tensor)
test_generator = torch.utils.data.DataLoader(test_dataset, **test_params)

mynet.eval()
batch = next(iter(test_generator))
with torch.no_grad():
    predictions_single_batch = mynet(**unpacked_batch)
  1. Instantiate a new Trainer object. Trainer's predict API allows you to pass an arbitrary DataLoader.
test_dataset = Dataset(test_tensor)
test_generator = torch.utils.data.DataLoader(test_dataset, **test_params)

predictor = pl.Trainer(gpus=1)
predictions_all_batches = predictor.predict(mynet, dataloaders=test_generator)

 I've noticed that in the second case, Pytorch Lightning takes care of stuff like moving your tensors and model onto (not off of) GPU, aligned with its potential to perform distributed predictions. It also doesn't returns any gradient-attached loss values, which helps dispense of the need to write boilerplate code like with torch.no_grad().

Discussions

Train model with fastai, predict with Pytorch (Lightning) - fastai - fast.ai Course Forums
As transfer learning seems to be much simpler and faster with fastai, I would like to migrate the training component to fastai while keeping the old prediction code as it is for now (Pytorch Lightning). I already used a vision_learner to do that and exported the resulting model as .pkl (.pth) file. More on forums.fast.ai
🌐 forums.fast.ai
0
February 22, 2023
example of doing simple prediction with pytorch-lightning - Stack Overflow
I have an existing model where I load some pre-trained weights and then do prediction (one image at a time) in pytorch. I am trying to basically convert it to a pytorch lightning module and am conf... More on stackoverflow.com
🌐 stackoverflow.com
How to predict on the test dataset using trainer.predict()?
Hi I have trained the model using trainer and was trying to use trainer.predict() method to predict on the datamodule. But it throws the following error: MisconfigurationException Traceback (most r... More on github.com
🌐 github.com
1
2
Pytorch_lightning Trainer Predict execution time
Hi, I have a model and dataloader with 1 image. The main function is updating the image by looping then predicting the image. import time # load model and weight model = ... if __name__ == "__main__": while(True):… More on discuss.pytorch.org
🌐 discuss.pytorch.org
0
0
December 26, 2022
🌐
PyTorch Forums
discuss.pytorch.org › t › pytorch-lightning-for-prediction › 128403
Pytorch Lightning for prediction - PyTorch Forums
August 3, 2021 - Hi There, I am getting an error when i run the below code. The error says MisconfigurationException: No training_step() method defined. Lightning Trainer expects as minimum a training_step(), train_dataloader() and con…
🌐
PyTorch Lightning
pytorch-lightning.readthedocs.io › en › 1.6.5 › common › production_inference.html
Inference in Production — PyTorch Lightning 1.6.5 documentation
The following are some possible ... and using raw PyTorch might be advantageous. in your production environment. Lightning provides you with a prediction API that can be accessed using predict()....
🌐
GitHub
github.com › Lightning-AI › pytorch-lightning › discussions › 10509
How to obtain predictions from `LightningCLI` using the `predict` subcommand? · Lightning-AI/pytorch-lightning · Discussion #10509
# script.py from pytorch_lightning.utilities.cli import LightningCLI import ... if __name__ == "__main__": LightningCLI(MyLightingModule, MyDataModule) I was able to use it to .fit and .test my model, but I am not sure how to use .predict.
Author   Lightning-AI
🌐
Medium
medium.com › @asakisakamoto02 › how-to-make-predictions-with-pytorch-lightning-checkpoint-2f1ec20223c9
How to Make Predictions with PyTorch Lightning Checkpoint | by Asaki Sakamoto | Medium
November 16, 2024 - After training is complete, you can load the model from the saved checkpoint. PyTorch Lightning simplifies this process with its load_from_checkpoint method. model = SimpleModel.load_from_checkpoint('checkpoints/best_model.ckpt') Before making predictions, you need your data preprocessed and loaded into a suitable format.
🌐
Lightning AI
lightning.ai › docs › pytorch › stable › deploy › production_basic.html
Deploy models into production (basic) — PyTorch Lightning 2.6.1 documentation
The easiest way to use a model for predictions is to load the weights using load_from_checkpoint found in the LightningModule.
🌐
PyTorch Lightning
pytorch-lightning.readthedocs.io › en › 1.8.0 › levels › core_level_6.html
Level 6: Predict with your model — PyTorch Lightning 1.8.0 documentation
Learn the basics of predicting with Lightning. ... Learn to use pure PyTorch without the Lightning dependencies for prediction.
Find elsewhere
🌐
PyTorch Lightning
pytorch-lightning.readthedocs.io › en › latest › levels › core_level_6.html
Level 6: Predict with your model — PyTorch Lightning 2.6.0dev0 documentation
Learn the basics of predicting with Lightning. ... Learn to use pure PyTorch without the Lightning dependencies for prediction.
🌐
Fast.ai
forums.fast.ai › fastai
Train model with fastai, predict with Pytorch (Lightning) - fastai - fast.ai Course Forums
February 22, 2023 - As transfer learning seems to be much simpler and faster with fastai, I would like to migrate the training component to fastai while keeping the old prediction code as it is for now (Pytorch Lightning). I already used a vision_learner to do that and exported the resulting model as .pkl (.pth) file.
🌐
Kaggle
kaggle.com › code › hugoya › pytorch-lightning-feedback-prediction
[Pytorch-Lightning] Feedback prediction | Kaggle
July 21, 2022 - Explore and run AI code with Kaggle Notebooks | Using data from multiple data sources
🌐
Lightning AI
lightning.ai › docs › pytorch › stable › common › trainer.html
Trainer — PyTorch Lightning 2.6.1 documentation
Runs n if set to n (int) else 1 if set to True batch(es) to ensure your code will execute without errors. This applies to fitting, validating, testing, and predicting.
Top answer
1 of 2
10

LightningModule is a subclass of torch.nn.Module so the same model class will work for both inference and training. For that reason, you should probably call the cuda() and eval() methods outside of __init__.

Since it's just a nn.Module under the hood, once you've loaded your weights you don't need to override any methods to perform inference, simply call the model instance. Here's a toy example you can use:

Copyimport torchvision.models as models
from pytorch_lightning.core import LightningModule

class MyModel(LightningModule):
    def __init__(self):
        super().__init__()
        self.resnet = models.resnet18(pretrained=True, progress=False)
    
    def forward(self, x):
        return self.resnet(x)

model = MyModel().eval().cuda(device=0)

And then to actually run inference you don't need a method, just do something like:

Copyfor frame in video:
    img = transform(frame)
    img = torch.from_numpy(img).float().unsqueeze(0).cuda(0)
    output = model(img).data.cpu().numpy()
    # Do something with the output

The main benefit of PyTorchLighting is that you can also use the same class for training by implementing training_step(), configure_optimizers() and train_dataloader() on that class. You can find a simple example of that in the PyTorchLightning docs.

2 of 2
0

Even though above answer suffices, if one takes note of following line

Copyimg = torch.from_numpy(img).float().unsqueeze(0).cuda(0)

One has to put both the model as well as image to the right GPU. On multi-gpu inference machine, this becomes a hassle.

To solve this, .predict was also recently produced, see more at https://pytorch-lightning.readthedocs.io/en/stable/deploy/production_basic.html

🌐
GitHub
github.com › Lightning-AI › pytorch-lightning › discussions › 5788
How to gather predict on ddp · Lightning-AI/pytorch-lightning · Discussion #5788
seed_everything(seed, True) output_directory = pathlib.PurePath(paths["output_directory"]) strategy = DDPStrategy(find_unused_parameters=True) logger = CSVLogger(str(output_directory.parent), output_directory.name) stopper = EarlyStopping("val_loss", patience=config["patience"], verbose=True) prediction_writer = CustomWriter(data_config, str(output_directory), "epoch") trainer = Trainer( max_epochs=config["epochs"], logger=logger, callbacks=[stopper, prediction_writer], strategy=DDPStrategy(find_unused_parameters=True), sync_batchnorm=True, ) datamodule = CustomModule( data_config, hyperparame
Author   Lightning-AI
🌐
PyTorch Lightning
pytorch-lightning.readthedocs.io › en › 1.7.7 › levels › core_level_6.html
Level 6: Predict with your model — PyTorch Lightning 1.7.7 documentation
Learn the basics of predicting with Lightning. ... Learn to use pure PyTorch without the Lightning dependencies for prediction.
🌐
PyTorch Forums
discuss.pytorch.org › t › pytorch-lightning-trainer-predict-execution-time › 169000
Pytorch_lightning Trainer Predict execution time - PyTorch Forums
December 26, 2022 - Hi, I have a model and dataloader with 1 image. The main function is updating the image by looping then predicting the image. import time # load model and weight model = ... if __name__ == "__main__": while(True): # load image start_time = time.time() dataloader = process_image_to_dataloader trainer.predict(model=model, dataloaders=[dataloader], return_predictions=True) print("--- %s seconds ---" % (time.time() - start_time)) As my experiment, the ...