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 › data › datamodule.html
LightningDataModule — PyTorch Lightning 2.6.1 documentation
The LightningDataModule is a convenient way to manage data in PyTorch Lightning. It encapsulates training, validation, testing, and prediction dataloaders, as well as any necessary steps for data processing, downloads, and transformations.
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().

🌐
PyTorch Lightning
pytorch-lightning.readthedocs.io › en › 1.5.10 › extensions › datamodules.html
LightningDataModule — PyTorch Lightning 1.5.10 documentation
import pytorch_lightning as pl class MNISTDataModule(pl.LightningDataModule): def predict_dataloader(self): return DataLoader(self.mnist_test, batch_size=64) Override to define how you want to move an arbitrary batch to a device. To check the current state of execution of this hook you can use self.trainer.training/testing/validating/predicting/sanity_checking so that you can add different logic as per your requirement.
🌐
Lightning AI
lightning.ai › docs › pytorch › LTS › _modules › pytorch_lightning › loops › epoch › prediction_epoch_loop.html
pytorch_lightning.loops.epoch.prediction_epoch_loop — PyTorch Lightning 1.9.6 documentation
Args: dataloader_iter: the iterator over the current dataloader dataloader_idx: the index of the current dataloader dl_max_batches: the maximum number of batches the current loader can produce num_dataloaders: the total number of dataloaders """ action_name = f"[{self.__class__.__name__}].predict_dataloader_idx_{dataloader_idx}_next" with self.trainer.profiler.profile(action_name): batch_idx, batch = next(dataloader_iter) self._seen_batch_indices = self._get_batch_indices(dataloader_idx) if self.should_store_predictions else [] # we need to truncate the list of batch indices due to prefetching
🌐
Lightning AI
lightning.ai › docs › pytorch › stable › data › access.html
Accessing DataLoaders — PyTorch Lightning 2.6.1 documentation
dataloaders = trainer.train_dataloader ... trainer.predict_dataloaders · These properties will match exactly what was returned in your *_dataloader hooks or passed to the Trainer, meaning that if you returned a dictionary of dataloaders, these will return a dictionary of dataloaders. If you are using a CombinedLoader. A flattened list of DataLoaders can be accessed by doing: from lightning.pytorch.utilities ...
🌐
Deep Graph Library
discuss.dgl.ai › questions
Dataloader issue for link prediction task with pytorch lightning and dgl - Questions - Deep Graph Library
March 30, 2022 - I made this from mix of dgl examples and recent github commit of graphsage lightning for GAT link prediction. But the overfit with single batch is not working, I can’t figure out where exactly the issue is from error. The usual lightning fit loop with training and validation worked fine, ...
🌐
Lightning AI
lightning.ai › docs › pytorch › stable › deploy › production_basic.html
Deploy models into production (basic) — PyTorch Lightning 2.6.1 documentation
data_loader = DataLoader(...) model = MyModel() trainer = Trainer() predictions = trainer.predict(model, data_loader)
🌐
PyTorch Lightning
pytorch-lightning.readthedocs.io › en › 1.5.10 › guides › data.html
Managing Data — PyTorch Lightning 1.5.10 documentation
You can run inference on a test set even if the test_dataloader() method hasn’t been defined within your LightningModule instance. For example, this would be the case if your test data set is not available at the time your model was declared. Simply pass the test set to the test() method: # setup your data loader test = DataLoader(...) # test (pass in the loader) trainer.test(test_dataloaders=test)
Find elsewhere
🌐
Lightning AI
lightning.ai › docs › pytorch › stable › common › lightning_module.html
LightningModule — PyTorch Lightning 2.6.1 documentation
class MyModel(LightningModule): def predict_step(self, batch, batch_idx, dataloader_idx=0): return self(batch) dm = ...
🌐
GitHub
github.com › PyTorchLightning › pytorch-lightning › issues › 1853
Predict method to label new data · Issue #1853 · Lightning-AI/pytorch-lightning
May 17, 2020 - model = myLightning_model.load_from_checkpoint(path/to/checkpoint ) predicted_labels = model.predict(newdata_dataloader) The standard PyTorch way to do it, with the usual issues with managing devices and parallel processing: prediction_list = [] for i, batch in enumerate(dataloader): output = model(batch) output = model.proba(output) # if not part of forward already prediction_list.append(output)
Author   Lightning-AI
🌐
Lightning AI
lightning.ai › docs › pytorch › stable › common › trainer.html
Trainer — PyTorch Lightning 2.6.1 documentation
This will call the model forward function to compute predictions. Useful to perform distributed and batched predictions. Logging is disabled in the predict hooks. ... dataloaders¶ (Union[Any, LightningDataModule, None]) – An iterable or collection of iterables specifying predict samples.
🌐
Lightning AI
lightning.ai › docs › pytorch › LTS › guides › data.html
Managing Data — PyTorch Lightning 1.9.6 documentation
In the training loop, you can pass multiple DataLoaders as a dict or list/tuple, and Lightning will automatically combine the batches from different DataLoaders. In the validation, test, or prediction, you have the option to return multiple DataLoaders as list/tuple, which Lightning will call sequentially or combine the DataLoaders using CombinedLoader, which Lightning will automatically combine the batches from different DataLoaders.
🌐
GitHub
github.com › Lightning-AI › pytorch-lightning › discussions › 19388
How to predict with 1000s of dataloaders? · Lightning-AI/pytorch-lightning · Discussion #19388
I have a case where I have 2K + dataloaders that each hold a dataset with a dataframe. The model is a pretrained Bert model, and I want to create a trainer that can take all these dataloaders and c...
Author   Lightning-AI
🌐
PyTorch Lightning
pytorch-lightning.readthedocs.io › en › 1.4.9 › guides › data.html
Managing Data — PyTorch Lightning 1.4.9 documentation
You can run inference on a test set even if the test_dataloader() method hasn’t been defined within your LightningModule instance. For example, this would be the case if your test data set is not available at the time your model was declared. Simply pass the test set to the test() method: # setup your data loader test = DataLoader(...) # test (pass in the loader) trainer.test(test_dataloaders=test)
🌐
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…
🌐
GitHub
github.com › Lightning-AI › pytorch-lightning › discussions › 18274
`test_dataloader` must be implemented to be used with the Lightning Trainer · Lightning-AI/pytorch-lightning · Discussion #18274
import lightning.pytorch as pl from torch.utils.data import random_split, DataLoader # Note - you must have torchvision installed for this example from torchvision.datasets import MNIST from torchvision import transforms class MNISTDataModule(pl.LightningDataModule): def __init__(self, data_dir: str = "./"): super().__init__() self.data_dir = data_dir self.transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) def prepare_data(self): # download MNIST(self.data_dir, train=True, download=True) MNIST(self.data_dir, train=False, download=True) def setup
Author   Lightning-AI
🌐
GitHub
github.com › PyTorchLightning › pytorch-lightning › issues › 11636
Mentioning the predict_dataloader in the LightningDataModule · Issue #11636 · Lightning-AI/pytorch-lightning
January 26, 2022 - 📚 Documentation On the following page (On the following page (https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html#predict-dataloader) I stumbled upon the predict_dataloader() method. Should we reference is as a...
Author   Lightning-AI
🌐
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.