mednet.models.model

Classes

Model(name[, loss_type, loss_arguments, ...])

Base class for models.

class mednet.models.model.Model(name, loss_type=None, loss_arguments=None, optimizer_type=<class 'torch.optim.adam.Adam'>, optimizer_arguments=None, scheduler_type=None, scheduler_arguments=None, model_transforms=None, augmentation_transforms=None, num_classes=1)[source]

Bases: LightningModule

Base class for models.

Parameters:
  • name (str) – Common name to give to models of this type.

  • loss_type (type[Module] | None) –

    The loss to be used for training and evaluation.

    Warning

    The loss should be set to always return batch averages (as opposed to the batch sum), as our logging system expects it so.

  • loss_arguments (dict[str, Any] | None) – Arguments to the loss.

  • optimizer_type (type[Optimizer]) – The type of optimizer to use for training.

  • optimizer_arguments (dict[str, Any] | None) – Arguments to the optimizer after params.

  • scheduler_type (type[LRScheduler] | None) – The type of scheduler to use for training.

  • scheduler_arguments (dict[str, Any] | None) – Arguments to the scheduler after params.

  • model_transforms (Optional[Sequence[Callable[[Tensor], Tensor]]]) – An optional sequence of torch modules containing transforms to be applied on the input before it is fed into the network.

  • augmentation_transforms (Optional[Sequence[Callable[[Tensor], Tensor]]]) – An optional sequence of torch modules containing transforms to be applied on the input before it is fed into the network.

  • num_classes (int) – Number of outputs (classes) for this model.

property augmentation_transforms: Compose
property num_classes: int

Number of outputs (classes) for this model.

Returns:

The number of outputs supported by this model.

Return type:

int

property normalizer: Callable[[Tensor], Tensor]

Normalizer for input images.

Returns:

  • Callable (typically a torch.nn.Module) that takes the input

  • tensor to be normalized and returns its normalized version.

normalizer_is_set()[source]

Tell if a normalizer different than the default (NOOP) was set.

Return type:

bool

Returns:

True if a normalizer different than the default (NOOP) was set. Else, returns False.

set_normalizer_from_dataloader(dataloader)[source]

Initialize the input normalizer for the current model.

Sets-up a z-normalization scheme based on the input dataloader samples.

Parameters:

dataloader (DataLoader) – A torch Dataloader from which to compute the mean and std.

Return type:

None

on_save_checkpoint(checkpoint)[source]

Perform actions during checkpoint saving (called by lightning).

Called by Lightning when saving a checkpoint to give you a chance to store anything else you might want to save. Use on_load_checkpoint() to restore what additional data is saved here.

Parameters:

checkpoint (MutableMapping[str, Any]) – The checkpoint to save.

Return type:

None

on_load_checkpoint(checkpoint)[source]

Perform actions during model loading (called by lightning).

If you saved something with on_save_checkpoint() this is your chance to restore this.

Parameters:

checkpoint (MutableMapping[str, Any]) – The loaded checkpoint.

Return type:

None

balance_losses(datamodule)[source]

Balance the loss based on the distribution of positives.

This function will balance the loss with considering the targets in the datamodule. Only works if the loss supports it (i.e. contains a pos_weight attribute).

Parameters:

datamodule (ConcatDataModule) – Instance of a datamodule from where targets will be loaded.

Return type:

None

configure_losses()[source]

Create loss objects for train and validation.

Return type:

None

configure_optimizers()[source]

Configure optimizers.

Returns:

The configured optimizer, or a tuple containing the optimizer and a scheduler, in case one is present.

to(*args, **kwargs)[source]

Move model, augmentations and losses to specified device.

Refer to the method torch.nn.Module.to() for details.

Parameters:
  • *args (Any) – Parameter forwarded to the underlying implementations.

  • **kwargs (Any) – Parameter forwarded to the underlying implementations.

Return type:

Self

Returns:

Self.

forward(*args, **kwargs)[source]

Same as torch.nn.Module.forward().

Parameters:
  • *args – Whatever you decide to pass into the forward method.

  • **kwargs – Keyword arguments are also possible.

Returns:

Your model’s output

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.

Parameters:
  • 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)

Returns:

  • Tensor - The loss tensor

  • dict - 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 by accumulate_grad_batches internally.

validation_step(batch, batch_idx, dataloader_idx=0)[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.

Parameters:
  • 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)

Returns:

  • Tensor - The loss tensor

  • dict - 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.
    ...

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.

predict_step(batch, batch_idx, dataloader_idx=0)[source]

Step function called during predict(). By default, it calls forward(). Override to add any processing logic.

The predict_step() is used to scale inference on multi-devices.

To prevent an OOM error, it is possible to use BasePredictionWriter callback to write the predictions to disk or database after each batch or on epoch end.

The BasePredictionWriter should be used while using a spawn based accelerator. This happens for Trainer(strategy="ddp_spawn") or training on 8 TPU cores with Trainer(accelerator="tpu", devices=8) as predictions won’t be returned.

Parameters:
  • 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)

Returns:

Predicted output (optional).

Example

class MyModel(LightningModule):

    def predict_step(self, batch, batch_idx, dataloader_idx=0):
        return self(batch)

dm = ...
model = MyModel()
trainer = Trainer(accelerator="gpu", devices=2)
predictions = trainer.predict(model, dm)