minerva.engines.engine¶
Classes¶
Main interface for Engine classes. Engines are used to alter the behavior of a model's prediction. |
|
This class acts as a normal L.LightningModule that wraps a |
Module Contents¶
- class minerva.engines.engine._Engine[source]¶
Main interface for Engine classes. Engines are used to alter the behavior of a model’s prediction. An engine should be able to take a model and input data x and return a prediction. An use case for Engines is patched inference, where the model’s default input size is smaller them the desired input size. The engine can be used to make predictions in patches and combine this predictions in to a single output.
- class minerva.engines.engine._Inferencer[source]¶
Bases:
lightning.pytorch.LightningModuleThis class acts as a normal L.LightningModule that wraps a SimpleSupervisedModel model allowing it to perform inference with a custom engine (e.g., PatchInferencerEngine, SlidingWindowInferencerEngine). This is useful when the model’s default input size is smaller than the desired input size (sample size). In this case, the engine split the input tensor into patches, perform inference in each patch, and combine them into a single output of the desired size. The combination of patches can be parametrized by a weight_function allowing a customizable combination of patches (e.g, combining using weighted average). It is important to note that only model’s forward are wrapped, and, thus, any method that requires the forward method (e.g., training_step, predict_step) will be performed in patches, transparently to the user.
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- _single_step(batch, batch_idx, step_name)[source]¶
Perform a single step of the training/validation loop.
Parameters¶
- batchtorch.Tensor
The input data.
- batch_idxint
The index of the batch.
- step_namestr
The name of the step, either “train” or “val”.
Returns¶
- torch.Tensor
The loss value.
- Parameters:
batch (torch.Tensor)
batch_idx (int)
step_name (str)
- Return type:
torch.Tensor
- forward(x)[source]¶
Perform inference using the inference engine.
Parameters¶
- xtorch.Tensor
Batch of input data.
- Parameters:
x (torch.Tensor)
- Return type:
torch.Tensor
- test_step(batch, batch_idx)[source]¶
Operates on a single batch of data from the test set. In this step you’d normally generate examples or calculate anything of interest such as accuracy.
- Args:
batch: The output of your data iterable, normally a
DataLoader. batch_idx: The index of this batch. dataloader_idx: The index of the dataloader that produced this batch.(only if multiple dataloaders used)
- Return:
Tensor- The loss tensordict- A dictionary. Can include any keys, but must include the key'loss'.None- Skip to the next batch.
# if you have one test dataloader: def test_step(self, batch, batch_idx): ... # if you have multiple test dataloaders: def test_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single test dataset def test_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) test_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'test_loss': loss, 'test_acc': test_acc})
If you pass in multiple test dataloaders,
test_step()will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple test dataloaders def test_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. x, y = batch # implement your own out = self(x) if dataloader_idx == 0: loss = self.loss0(out, y) else: loss = self.loss1(out, y) # calculate acc labels_hat = torch.argmax(out, dim=1) acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs separately for each dataloader self.log_dict({f"test_loss_{dataloader_idx}": loss, f"test_acc_{dataloader_idx}": acc})
- Note:
If you don’t need to test you don’t need to implement this method.
- Note:
When the
test_step()is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of the test epoch, the model goes back to training mode and gradients are enabled.
- Parameters:
batch (torch.Tensor)
batch_idx (int)
- training_step(batch, batch_idx)[source]¶
Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.
- Args:
batch: The output of your data iterable, normally a
DataLoader. batch_idx: The index of this batch. dataloader_idx: The index of the dataloader that produced this batch.(only if multiple dataloaders used)
- Return:
Tensor- The loss tensordict- A dictionary which can include any keys, but must include the key'loss'in the case of automatic optimization.None- In automatic optimization, this will skip to the next batch (but is not supported for multi-GPU, TPU, or DeepSpeed). For manual optimization, this has no special meaning, as returning the loss is not required.
In this step you’d normally do the forward pass and calculate the loss for a batch. You can also do fancier things like multiple forward passes or something model specific.
Example:
def training_step(self, batch, batch_idx): x, y, z = batch out = self.encoder(x) loss = self.loss(out, x) return loss
To use multiple optimizers, you can switch to ‘manual optimization’ and control their stepping:
def __init__(self): super().__init__() self.automatic_optimization = False # Multiple optimizers (e.g.: GANs) def training_step(self, batch, batch_idx): opt1, opt2 = self.optimizers() # do training_step with encoder ... opt1.step() # do training_step with decoder ... opt2.step()
- Note:
When
accumulate_grad_batches> 1, the loss returned here will be automatically normalized byaccumulate_grad_batchesinternally.
- Parameters:
batch (torch.Tensor)
batch_idx (int)
- validation_step(batch, batch_idx)[source]¶
Operates on a single batch of data from the validation set. In this step you’d might generate examples or calculate anything of interest like accuracy.
- Args:
batch: The output of your data iterable, normally a
DataLoader. batch_idx: The index of this batch. dataloader_idx: The index of the dataloader that produced this batch.(only if multiple dataloaders used)
- Return:
Tensor- The loss tensordict- A dictionary. Can include any keys, but must include the key'loss'.None- Skip to the next batch.
# if you have one val dataloader: def validation_step(self, batch, batch_idx): ... # if you have multiple val dataloaders: def validation_step(self, batch, batch_idx, dataloader_idx=0): ...
Examples:
# CASE 1: A single validation dataset def validation_step(self, batch, batch_idx): x, y = batch # implement your own out = self(x) loss = self.loss(out, y) # log 6 example images # or generated text... or whatever sample_imgs = x[:6] grid = torchvision.utils.make_grid(sample_imgs) self.logger.experiment.add_image('example_images', grid, 0) # calculate acc labels_hat = torch.argmax(out, dim=1) val_acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs! self.log_dict({'val_loss': loss, 'val_acc': val_acc})
If you pass in multiple val dataloaders,
validation_step()will have an additional argument. We recommend setting the default value of 0 so that you can quickly switch between single and multiple dataloaders.# CASE 2: multiple validation dataloaders def validation_step(self, batch, batch_idx, dataloader_idx=0): # dataloader_idx tells you which dataset this is. x, y = batch # implement your own out = self(x) if dataloader_idx == 0: loss = self.loss0(out, y) else: loss = self.loss1(out, y) # calculate acc labels_hat = torch.argmax(out, dim=1) acc = torch.sum(y == labels_hat).item() / (len(y) * 1.0) # log the outputs separately for each dataloader self.log_dict({f"val_loss_{dataloader_idx}": loss, f"val_acc_{dataloader_idx}": acc})
- Note:
If you don’t need to validate you don’t need to implement this method.
- Note:
When the
validation_step()is called, the model has been put in eval mode and PyTorch gradients have been disabled. At the end of validation, the model goes back to training mode and gradients are enabled.
- Parameters:
batch (torch.Tensor)
batch_idx (int)