tiramisu_brulee.experiment package

Subpackages

Submodules

tiramisu_brulee.experiment.data module

Data handling classes for training/prediction

load and process data for training/prediction for segmentation tasks

Author: Jacob Reinhold (jcreinhold@gmail.com) Created on: May 17, 2021

class tiramisu_brulee.experiment.data.LesionSegDataModulePredictBase(*args: Any, **kwargs: Any)[source]

Bases: tiramisu_brulee.experiment.data.LesionSegDataModuleBase

static add_arguments(parent_parser: jsonargparse.ArgumentParser, add_csv: bool = True) jsonargparse.ArgumentParser[source]
predict_dataloader() torch.utils.data.DataLoader[source]

Implement one or multiple PyTorch DataLoaders for prediction.

It’s recommended that all data downloads and preparation happen in prepare_data().

  • fit()

  • prepare_data()

  • train_dataloader()

  • val_dataloader()

  • test_dataloader()

Note

Lightning adds the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.

Returns

A torch.utils.data.DataLoader or a sequence of them specifying prediction samples.

Note

In the case where you return multiple prediction dataloaders, the predict() will have an argument dataloader_idx which matches the order here.

setup(stage: Optional[str] = None) None[source]

Called at the beginning of fit (train + validate), validate, test, and predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.

Parameters

stage – either 'fit', 'validate', 'test', or 'predict'

Example:

class LitModel(...):
    def __init__(self):
        self.l1 = None

    def prepare_data(self):
        download_data()
        tokenize()

        # don't do this
        self.something = else

    def setup(stage):
        data = Load_data(...)
        self.l1 = nn.Linear(28, data.num_classes)
class tiramisu_brulee.experiment.data.LesionSegDataModulePredictPatches(*args: Any, **kwargs: Any)[source]

Bases: tiramisu_brulee.experiment.data.LesionSegDataModulePredictBase

Data module for patch-based prediction for lesion segmentation

Parameters
  • subject (tio.Subject) – a torchio.Subject for prediction

  • batch_size (int) – number of patches to predict at a time

  • patch_size (PatchShapeOption) – patch size for training/validation if any element is None, use the corresponding image dim

  • patch_overlap (Optional[PatchShape]) – overlap of each patch, if None then patch_size // 2

  • num_workers (int) – number of subprocesses to use for data loading

  • pseudo3d_dim (Optional[int]) – concatenate images along this axis and swap it for channel dimension

  • pseudo3d_size (Optional[int]) – number of slices to concatenate if pseudo3d_dim provided, must be an odd (usually small) integer

class tiramisu_brulee.experiment.data.LesionSegDataModulePredictWhole(*args: Any, **kwargs: Any)[source]

Bases: tiramisu_brulee.experiment.data.LesionSegDataModulePredictBase

Data module for whole-image prediction for lesion segmentation

Parameters
  • subjects (List[tio.Subject]) – list of torchio.Subject for prediction

  • batch_size (int) – number of images to predict at a time

  • num_workers (int) – number of subprocesses to use for data loading

classmethod from_csv(predict_csv: str, **kwargs) tiramisu_brulee.experiment.data.PredictDataModule[source]
setup(stage: Optional[str] = None) None[source]

Called at the beginning of fit (train + validate), validate, test, and predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.

Parameters

stage – either 'fit', 'validate', 'test', or 'predict'

Example:

class LitModel(...):
    def __init__(self):
        self.l1 = None

    def prepare_data(self):
        download_data()
        tokenize()

        # don't do this
        self.something = else

    def setup(stage):
        data = Load_data(...)
        self.l1 = nn.Linear(28, data.num_classes)
class tiramisu_brulee.experiment.data.LesionSegDataModuleTrain(*args: Any, **kwargs: Any)[source]

Bases: tiramisu_brulee.experiment.data.LesionSegDataModuleBase

Data module for training and validation for lesion segmentation

Parameters
  • train_subject_list (List[tio.Subject]) – list of torchio.Subject for training

  • val_subject_list (List[tio.Subject]) – list of torchio.Subject for validation

  • batch_size (int) – batch size for training/validation

  • patch_size (PatchShape) – patch size for training/validation

  • queue_length (int) – Maximum number of patches that can be stored in the queue. Using a large number means that the queue needs to be filled less often, but more CPU memory is needed to store the patches.

  • samples_per_volume (int) – Number of patches to extract from each volume. A small number of patches ensures a large variability in the queue, but training will be slower.

  • num_workers (int) – number of subprocesses for data loading

  • label_sampler (bool) – sample patches centered on positive labels

  • spatial_augmentation (bool) – use random affine and elastic data augmentation for training

  • pseudo3d_dim (Optional[int]) – concatenate images along this axis and swap it for channel dimension

static add_arguments(parent_parser: jsonargparse.ArgumentParser) jsonargparse.ArgumentParser[source]
classmethod from_csv(*, train_csv: str, valid_csv: str, **kwargs) tiramisu_brulee.experiment.data.TrainDataModule[source]
setup(stage: Optional[str] = None) None[source]

Called at the beginning of fit (train + validate), validate, test, and predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.

Parameters

stage – either 'fit', 'validate', 'test', or 'predict'

Example:

class LitModel(...):
    def __init__(self):
        self.l1 = None

    def prepare_data(self):
        download_data()
        tokenize()

        # don't do this
        self.something = else

    def setup(stage):
        data = Load_data(...)
        self.l1 = nn.Linear(28, data.num_classes)
train_dataloader() torch.utils.data.DataLoader[source]

Implement one or more PyTorch DataLoaders for training.

Returns

A collection of torch.utils.data.DataLoader specifying training samples. In the case of multiple dataloaders, please see this page.

The dataloader you return will not be reloaded unless you set reload_dataloaders_every_n_epochs to a positive integer.

For data processing use the following pattern:

  • download in prepare_data()

  • process and split in setup()

However, the above are only necessary for distributed processing.

Warning

do not assign state in prepare_data

Note

Lightning adds the correct sampler for distributed and arbitrary hardware. There is no need to set it yourself.

Example:

# single dataloader
def train_dataloader(self):
    transform = transforms.Compose([transforms.ToTensor(),
                                    transforms.Normalize((0.5,), (1.0,))])
    dataset = MNIST(root='/path/to/mnist/', train=True, transform=transform,
                    download=True)
    loader = torch.utils.data.DataLoader(
        dataset=dataset,
        batch_size=self.batch_size,
        shuffle=True
    )
    return loader

# multiple dataloaders, return as list
def train_dataloader(self):
    mnist = MNIST(...)
    cifar = CIFAR(...)
    mnist_loader = torch.utils.data.DataLoader(
        dataset=mnist, batch_size=self.batch_size, shuffle=True
    )
    cifar_loader = torch.utils.data.DataLoader(
        dataset=cifar, batch_size=self.batch_size, shuffle=True
    )
    # each batch will be a list of tensors: [batch_mnist, batch_cifar]
    return [mnist_loader, cifar_loader]

# multiple dataloader, return as dict
def train_dataloader(self):
    mnist = MNIST(...)
    cifar = CIFAR(...)
    mnist_loader = torch.utils.data.DataLoader(
        dataset=mnist, batch_size=self.batch_size, shuffle=True
    )
    cifar_loader = torch.utils.data.DataLoader(
        dataset=cifar, batch_size=self.batch_size, shuffle=True
    )
    # each batch will be a dict of tensors: {'mnist': batch_mnist, 'cifar': batch_cifar}
    return {'mnist': mnist_loader, 'cifar': cifar_loader}
val_dataloader() torch.utils.data.DataLoader[source]

Implement one or multiple PyTorch DataLoaders for validation.

The dataloader you return will not be reloaded unless you set reload_dataloaders_every_n_epochs to a positive integer.

It’s recommended that all data downloads and preparation happen in prepare_data().

Note

Lightning adds the correct sampler for distributed and arbitrary hardware There is no need to set it yourself.

Returns

A torch.utils.data.DataLoader or a sequence of them specifying validation samples.

Examples:

def val_dataloader(self):
    transform = transforms.Compose([transforms.ToTensor(),
                                    transforms.Normalize((0.5,), (1.0,))])
    dataset = MNIST(root='/path/to/mnist/', train=False,
                    transform=transform, download=True)
    loader = torch.utils.data.DataLoader(
        dataset=dataset,
        batch_size=self.batch_size,
        shuffle=False
    )

    return loader

# can also return multiple dataloaders
def val_dataloader(self):
    return [loader_a, loader_b, ..., loader_n]

Note

If you don’t need a validation dataset and a validation_step(), you don’t need to implement this method.

Note

In the case where you return multiple validation dataloaders, the validation_step() will have an argument dataloader_idx which matches the order here.

class tiramisu_brulee.experiment.data.Mixup(alpha: float)[source]

Bases: object

mixup for data augmentation

See also

Zhang, Hongyi, et al. “mixup: Beyond empirical risk minimization.” arXiv preprint arXiv:1710.09412 (2017).

Parameters

alpha (float) – parameter for beta distribution

static add_arguments(parent_parser: jsonargparse.ArgumentParser) jsonargparse.ArgumentParser[source]
tiramisu_brulee.experiment.data.csv_to_subjectlist(filename: str, *, strict: bool = True, check_dicom: bool = False) List[torchio.Subject][source]

Convert a csv file to a list of torchio subjects

Parameters
  • filename – pathlib.Path to csv file formatted with subject in a column, describing the id/name of the subject (must be unique). Row will fill in the filenames per type. Other columns headers must be one of: ct, flair, label, pd, t1, t1c, t2, weight, div (label should correspond to a segmentation mask) (weight and div should correspond to a float)

  • strict – if affine matrices are different enough (according to torchio tolerance), raise a runtime error. Otherwise, resample the images of the subject to the first image.

  • check_dicom – if true, check dicom images for uniform spacing and warn the user about image if there is serious non-uniformity in slice distances

Returns

list of torchio Subjects

Return type

subject_list (List[torchio.Subject])

tiramisu_brulee.experiment.lesion_tools module

Functions specific to handling/processing lesion segmentations Author: Jacob Reinhold <jcreinhold@gmail.com> Created on: May 16, 2021

tiramisu_brulee.experiment.lesion_tools.almost_isbi15_score(pred: torch.Tensor, target: torch.Tensor, *, return_dice_ppv: bool = False) Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]][source]

ISBI 15 MS challenge score excluding the LTPR & LFPR components

tiramisu_brulee.experiment.lesion_tools.clean_segmentation(label: numpy.ndarray, *, fill_holes: bool = True, minimum_lesion_size: int = 3) numpy.ndarray[source]

clean binary array by removing small objs & filling holes

tiramisu_brulee.experiment.parse module

Parsing functions for argparse and config files Author: Jacob Reinhold <jcreinhold@gmail.com> Created on: May 17, 2021

tiramisu_brulee.experiment.parse.dict_to_csv(modality_path: Dict[str, str], open_file: IO) None[source]

takes a dictionary of modalities and paths (one for each modality) and an open file (e.g., open(“file.csv”, “w”)) and writes the modalities as headers and the paths as entries under those headers

used for to wrangle single time-point prediction into the same interface as multi time-point prediction

tiramisu_brulee.experiment.parse.fix_type_funcs(parser: jsonargparse.ArgumentParser) None[source]

fixes type functions in pytorch-lightning’s add_argparse_args

tiramisu_brulee.experiment.parse.generate_predict_config_yaml(exp_dirs: List[pathlib.Path], parser: jsonargparse.ArgumentParser, dict_args: dict, best_model_paths: Optional[List[pathlib.Path]] = None) List[str][source]

generate config yaml file(s) for prediction, store in experiment dir

tiramisu_brulee.experiment.parse.generate_train_config_yaml(exp_dirs: List[pathlib.Path], parser: jsonargparse.ArgumentParser, dict_args: dict, best_model_paths: Optional[List[pathlib.Path]] = None) List[str][source]

generate config yaml file(s) for training, store in experiment dir

tiramisu_brulee.experiment.parse.get_best_model_path(checkpoint_callback: pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint, only_best: bool = False) pathlib.Path[source]

gets the best model path from a ModelCheckpoint instance

tiramisu_brulee.experiment.parse.get_experiment_directory(model_path: Union[str, os.PathLike]) pathlib.Path[source]

gets the experiment directory from a checkpoint model path

tiramisu_brulee.experiment.parse.none_string_to_none(args: jsonargparse.Namespace) jsonargparse.Namespace[source]

goes through an instance of parsed args and maps ‘None’ -> None

tiramisu_brulee.experiment.parse.parse_unknown_to_dict(unknown: List[str], *, names_only: bool = False) Dict[str, Optional[str]][source]

parse unknown arguments (usually modalities and their path) to dict

tiramisu_brulee.experiment.parse.path_to_str(args: jsonargparse.Namespace) jsonargparse.Namespace[source]

goes through an instance of parsed args and maps Path -> str

tiramisu_brulee.experiment.parse.remove_args(parser: jsonargparse.ArgumentParser, args: Iterable[str]) None[source]

remove a set of args from a parser

tiramisu_brulee.experiment.seg module

Training and prediction lightning modules

Training and prediction logic for segmentation (usually lesion segmentation). Also, an implementation of the Tiramisu network with the training and prediction logic built-in.

Author: Jacob Reinhold <jcreinhold@gmail.com> Created on: May 14, 2021

class tiramisu_brulee.experiment.seg.LesionSegLightningBase(*args: Any, **kwargs: Any)[source]

Bases: pytorch_lightning.core.lightning.LightningModule

PyTorch-Lightning module for lesion segmentation

Includes framework for both training and prediction, just drop in a PyTorch neural network module

Parameters
  • network (nn.Module) – PyTorch neural network

  • n_epochs (int) – number of epochs to train the network

  • learning_rate (float) – learning rate for the optimizer

  • betas (Tuple[float, float]) – momentum parameters for adam

  • weight_decay (float) – weight decay for optimizer

  • loss_function (str) – loss function to use in training

  • pos_weight (Optional[float]) – weight for positive class in focal/bce loss if using combo loss function

  • focal_gamma (float) – gamma param for focal loss if using combo loss function (0. -> BCE)

  • combo_weight (float) – weight by which to balance focal and Dice losses in combo loss function

  • decay_after (int) – decay learning rate linearly after this many epochs

  • rmsprop (bool) – use rmsprop instead of adamw

  • soft_labels (bool) – use non-binary labels for training

  • threshold (float) – threshold by which to decide on positive class

  • min_lesion_size (int) – minimum lesion size in voxels in output prediction

  • fill_holes (bool) – use binary fill holes operation on label

  • predict_probability (bool) – save a probability image instead of a binary one

  • mixup (bool) – use mixup in training

  • mixup_alpha (float) – mixup parameter for beta distribution

  • num_input (int) – number of different images input to the network, differs from in_channels when using pseudo3d

  • num_classes (int) – number of different images output by the network differs from out_channels when using pseudo3d

  • _model_num (ModelNum) – internal param for ith of n models

static add_io_arguments(parent_parser: Union[argparse.ArgumentParser, jsonargparse.ArgumentParser]) Union[argparse.ArgumentParser, jsonargparse.ArgumentParser][source]
static add_other_arguments(parent_parser: Union[argparse.ArgumentParser, jsonargparse.ArgumentParser]) Union[argparse.ArgumentParser, jsonargparse.ArgumentParser][source]
static add_testing_arguments(parent_parser: Union[argparse.ArgumentParser, jsonargparse.ArgumentParser]) Union[argparse.ArgumentParser, jsonargparse.ArgumentParser][source]
static add_training_arguments(parent_parser: Union[argparse.ArgumentParser, jsonargparse.ArgumentParser]) Union[argparse.ArgumentParser, jsonargparse.ArgumentParser][source]
configure_optimizers() Tuple[List[torch.optim.Optimizer], List[torch.optim.lr_scheduler.LambdaLR]][source]

Choose what optimizers and learning-rate schedulers to use in your optimization. Normally you’d need one. But in the case of GANs or similar you might have multiple.

Returns

Any of these 6 options.

  • Single optimizer.

  • List or Tuple of optimizers.

  • Two lists - The first list has multiple optimizers, and the second has multiple LR schedulers (or multiple lr_scheduler_config).

  • Dictionary, with an "optimizer" key, and (optionally) a "lr_scheduler" key whose value is a single LR scheduler or lr_scheduler_config.

  • Tuple of dictionaries as described above, with an optional "frequency" key.

  • None - Fit will run without any optimizer.

The lr_scheduler_config is a dictionary which contains the scheduler and its associated configuration. The default configuration is shown below.

lr_scheduler_config = {
    # REQUIRED: The scheduler instance
    "scheduler": lr_scheduler,
    # The unit of the scheduler's step size, could also be 'step'.
    # 'epoch' updates the scheduler on epoch end whereas 'step'
    # updates it after a optimizer update.
    "interval": "epoch",
    # How many epochs/steps should pass between calls to
    # `scheduler.step()`. 1 corresponds to updating the learning
    # rate after every epoch/step.
    "frequency": 1,
    # Metric to to monitor for schedulers like `ReduceLROnPlateau`
    "monitor": "val_loss",
    # If set to `True`, will enforce that the value specified 'monitor'
    # is available when the scheduler is updated, thus stopping
    # training if not found. If set to `False`, it will only produce a warning
    "strict": True,
    # If using the `LearningRateMonitor` callback to monitor the
    # learning rate progress, this keyword can be used to specify
    # a custom logged name
    "name": None,
}

When there are schedulers in which the .step() method is conditioned on a value, such as the torch.optim.lr_scheduler.ReduceLROnPlateau scheduler, Lightning requires that the lr_scheduler_config contains the keyword "monitor" set to the metric name that the scheduler should be conditioned on.

Metrics can be made available to monitor by simply logging it using self.log('metric_to_track', metric_val) in your LightningModule.

Note

The frequency value specified in a dict along with the optimizer key is an int corresponding to the number of sequential batches optimized with the specific optimizer. It should be given to none or to all of the optimizers. There is a difference between passing multiple optimizers in a list, and passing multiple optimizers in dictionaries with a frequency of 1:

  • In the former case, all optimizers will operate on the given batch in each optimization step.

  • In the latter, only one optimizer will operate on the given batch at every step.

This is different from the frequency value specified in the lr_scheduler_config mentioned above.

def configure_optimizers(self):
    optimizer_one = torch.optim.SGD(self.model.parameters(), lr=0.01)
    optimizer_two = torch.optim.SGD(self.model.parameters(), lr=0.01)
    return [
        {"optimizer": optimizer_one, "frequency": 5},
        {"optimizer": optimizer_two, "frequency": 10},
    ]

In this example, the first optimizer will be used for the first 5 steps, the second optimizer for the next 10 steps and that cycle will continue. If an LR scheduler is specified for an optimizer using the lr_scheduler key in the above dict, the scheduler will only be updated when its optimizer is being used.

Examples:

# most cases. no learning rate scheduler
def configure_optimizers(self):
    return Adam(self.parameters(), lr=1e-3)

# multiple optimizer case (e.g.: GAN)
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    return gen_opt, dis_opt

# example with learning rate schedulers
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    dis_sch = CosineAnnealing(dis_opt, T_max=10)
    return [gen_opt, dis_opt], [dis_sch]

# example with step-based learning rate schedulers
# each optimizer has its own scheduler
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    gen_sch = {
        'scheduler': ExponentialLR(gen_opt, 0.99),
        'interval': 'step'  # called after each training step
    }
    dis_sch = CosineAnnealing(dis_opt, T_max=10) # called every epoch
    return [gen_opt, dis_opt], [gen_sch, dis_sch]

# example with optimizer frequencies
# see training procedure in `Improved Training of Wasserstein GANs`, Algorithm 1
# https://arxiv.org/abs/1704.00028
def configure_optimizers(self):
    gen_opt = Adam(self.model_gen.parameters(), lr=0.01)
    dis_opt = Adam(self.model_dis.parameters(), lr=0.02)
    n_critic = 5
    return (
        {'optimizer': dis_opt, 'frequency': n_critic},
        {'optimizer': gen_opt, 'frequency': 1}
    )

Note

Some things to know:

  • Lightning calls .backward() and .step() on each optimizer and learning rate scheduler as needed.

  • If you use 16-bit precision (precision=16), Lightning will automatically handle the optimizers.

  • If you use multiple optimizers, training_step() will have an additional optimizer_idx parameter.

  • If you use torch.optim.LBFGS, Lightning handles the closure function automatically for you.

  • If you use multiple optimizers, gradients will be calculated only for the parameters of current optimizer at each training step.

  • If you need to control how often those optimizers step or override the default .step() schedule, override the optimizer_step() hook.

decay_rule(epoch: int) float[source]
forward(tensor: torch.Tensor) torch.Tensor[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

on_predict_batch_end(pred_step_outputs: torch.Tensor, batch: Union[tiramisu_brulee.experiment.data.PatchesImagePredictBatch, tiramisu_brulee.experiment.data.WholeImagePredictBatch], batch_idx: int, dataloader_idx: int) Union[tiramisu_brulee.experiment.data.PatchesImagePredictBatch, tiramisu_brulee.experiment.data.WholeImagePredictBatch][source]

Called in the predict loop after the batch.

Parameters
  • outputs – The outputs of predict_step_end(test_step(x))

  • batch – The batched data as it is returned by the test DataLoader.

  • batch_idx – the index of the batch

  • dataloader_idx – the index of the dataloader

predict_step(batch: Union[tiramisu_brulee.experiment.data.PatchesImagePredictBatch, tiramisu_brulee.experiment.data.WholeImagePredictBatch], batch_idx: int, dataloader_idx: Optional[int] = None) torch.Tensor[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(tpu_cores=8) as predictions won’t be returned.

Example

class MyModel(LightningModule):

    def predicts_step(self, batch, batch_idx, dataloader_idx):
        return self(batch)

dm = ...
model = MyModel()
trainer = Trainer(gpus=2)
predictions = trainer.predict(model, dm)
Parameters
  • batch – Current batch

  • batch_idx – Index of current batch

  • dataloader_idx – Index of the current dataloader

Returns

Predicted output

setup(stage: Optional[str] = None) None[source]

Called at the beginning of fit (train + validate), validate, test, and predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.

Parameters

stage – either 'fit', 'validate', 'test', or 'predict'

Example:

class LitModel(...):
    def __init__(self):
        self.l1 = None

    def prepare_data(self):
        download_data()
        tokenize()

        # don't do this
        self.something = else

    def setup(stage):
        data = Load_data(...)
        self.l1 = nn.Linear(28, data.num_classes)
training_step(batch: Tuple[torch.Tensor, torch.Tensor], batch_idx: int) torch.Tensor[source]

Here you compute and return the training loss and some additional metrics for e.g. the progress bar or logger.

Parameters
  • batch (Tensor | (Tensor, …) | [Tensor, …]) – The output of your DataLoader. A tensor, tuple or list.

  • batch_idx (int) – Integer displaying index of this batch

  • optimizer_idx (int) – When using multiple optimizers, this argument will also be present.

  • hiddens (Any) – Passed in if truncated_bptt_steps > 0.

Returns

Any of.

  • Tensor - The loss tensor

  • dict - A dictionary. Can include any keys, but must include the key 'loss'

  • None - Training will skip to the next batch. This is only for automatic optimization.

    This is not supported for multi-GPU, TPU, IPU, or DeepSpeed.

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

If you define multiple optimizers, this step will be called with an additional optimizer_idx parameter.

# Multiple optimizers (e.g.: GANs)
def training_step(self, batch, batch_idx, optimizer_idx):
    if optimizer_idx == 0:
        # do training_step with encoder
        ...
    if optimizer_idx == 1:
        # do training_step with decoder
        ...

If you add truncated back propagation through time you will also get an additional argument with the hidden states of the previous step.

# Truncated back-propagation through time
def training_step(self, batch, batch_idx, hiddens):
    # hiddens are the hidden states from the previous truncated backprop step
    out, hiddens = self.lstm(data, hiddens)
    loss = ...
    return {"loss": loss, "hiddens": hiddens}

Note

The loss value shown in the progress bar is smoothed (averaged) over the last values, so it differs from the actual loss returned in train/validation step.

validation_epoch_end(outputs: List[Any]) None[source]

Called at the end of the validation epoch with the outputs of all validation steps.

# the pseudocode for these calls
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    val_outs.append(out)
validation_epoch_end(val_outs)
Parameters

outputs – List of outputs you defined in validation_step(), or if there are multiple dataloaders, a list containing a list of outputs for each dataloader.

Returns

None

Note

If you didn’t define a validation_step(), this won’t be called.

Examples

With a single dataloader:

def validation_epoch_end(self, val_step_outputs):
    for out in val_step_outputs:
        ...

With multiple dataloaders, outputs will be a list of lists. The outer list contains one entry per dataloader, while the inner list contains the individual outputs of each validation step for that dataloader.

def validation_epoch_end(self, outputs):
    for dataloader_output_result in outputs:
        dataloader_outs = dataloader_output_result.dataloader_i_outputs

    self.log("final_metric", final_value)
validation_step(batch: Tuple[torch.Tensor, torch.Tensor], batch_idx: int) Dict[str, Any][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.

# the pseudocode for these calls
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    val_outs.append(out)
validation_epoch_end(val_outs)
Parameters
  • batch (Tensor | (Tensor, …) | [Tensor, …]) – The output of your DataLoader. A tensor, tuple or list.

  • batch_idx (int) – The index of this batch

  • dataloader_idx (int) – The index of the dataloader that produced this batch (only if multiple val dataloaders used)

Returns

  • Any object or value

  • None - Validation will skip to the next batch

# pseudocode of order
val_outs = []
for val_batch in val_data:
    out = validation_step(val_batch)
    if defined("validation_step_end"):
        out = validation_step_end(out)
    val_outs.append(out)
val_outs = validation_epoch_end(val_outs)
# 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):
    ...

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.

# CASE 2: multiple validation dataloaders
def validation_step(self, batch, batch_idx, dataloader_idx):
    # 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.

class tiramisu_brulee.experiment.seg.LesionSegLightningTiramisu(*args: Any, **kwargs: Any)[source]

Bases: tiramisu_brulee.experiment.seg.LesionSegLightningBase

3D Tiramisu-based PyTorch-Lightning module for lesion segmentation

See also

Jégou, Simon, et al. “The one hundred layers tiramisu: Fully convolutional densenets for semantic segmentation.” CVPR. 2017.

Zhang, Huahong, et al. “Multiple sclerosis lesion segmentation with Tiramisu and 2.5D stacked slices.” International Conference on Medical Image Computing and Computer-Assisted Intervention. Springer, Cham, 2019.

Parameters
  • network_dim (int) – use a 2D or 3D convolutions

  • in_channels (int) – number of input channels

  • num_classes (int) – number of classes to segment with the network

  • down_blocks (Collection[int]) – number of layers in each block in down path

  • up_blocks (Collection[int]) – number of layers in each block in up path

  • bottleneck_layers (int) – number of layers in the bottleneck

  • growth_rate (int) – number of channels to grow by in each layer

  • first_conv_out_channels (int) – number of output channels in first conv

  • dropout_rate (float) – dropout rate/probability

  • init_type (str) – method to initialize the weights of network

  • gain (float) – gain parameter for initialization

  • n_epochs (int) – number of epochs to train the network

  • learning_rate (float) – learning rate for the optimizer

  • betas (Tuple[float, float]) – momentum parameters for adam

  • weight_decay (float) – weight decay for optimizer

  • loss_function (str) – loss function to use in training

  • pos_weight (Optional[float]) – weight for positive class in focal/bce loss if using combo loss function

  • focal_gamma (float) – gamma param for focal loss if using combo loss function (0. -> BCE)

  • combo_weight (float) – weight by which to balance focal and Dice losses in combo loss function

  • decay_after (int) – decay learning rate linearly after this many epochs

  • rmsprop (bool) – use rmsprop instead of adamw

  • soft_labels (bool) – use non-binary labels for training

  • threshold (float) – threshold by which to decide on positive class

  • min_lesion_size (int) – minimum lesion size in voxels in output prediction

  • fill_holes (bool) – use binary fill holes operation on label

  • predict_probability (bool) – save a probability image instead of a binary one

  • mixup (bool) – use mixup in training

  • mixup_alpha (float) – mixup parameter for beta distribution

  • num_input (int) – number of different images input to the network, differs from in_channels when using pseudo3d

  • _model_num (ModelNum) – internal param for ith of n models

static add_model_arguments(parent_parser: Union[argparse.ArgumentParser, jsonargparse.ArgumentParser]) Union[argparse.ArgumentParser, jsonargparse.ArgumentParser][source]

tiramisu_brulee.experiment.type module

Experiment-specific types Author: Jacob Reinhold <jcreinhold@gmail.com> Created on: May 28, 2021

class tiramisu_brulee.experiment.type.ModelNum(num, out_of)

Bases: tuple

property num

Alias for field number 0

property out_of

Alias for field number 1

class tiramisu_brulee.experiment.type.TiramisuBruleeInfo(version, commit)

Bases: tuple

property commit

Alias for field number 1

property version

Alias for field number 0

class tiramisu_brulee.experiment.type.file_path[source]

Bases: tiramisu_brulee.experiment.type._ParseType

tiramisu_brulee.experiment.type.new_parse_type(func: Callable, name: str) tiramisu_brulee.experiment.type.NewParseType[source]
class tiramisu_brulee.experiment.type.nonnegative_float[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.nonnegative_int[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.nonnegative_int_or_none_or_all[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.positive_float[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.positive_float_or_none[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.positive_int[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.positive_int_or_none[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.positive_odd_int_or_none[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.probability_float[source]

Bases: tiramisu_brulee.experiment.type._ParseType

class tiramisu_brulee.experiment.type.probability_float_or_none[source]

Bases: tiramisu_brulee.experiment.type._ParseType

tiramisu_brulee.experiment.util module

Miscellaneous tools for experiments Author: Jacob Reinhold <jcreinhold@gmail.com> Created on: May 16, 2021

class tiramisu_brulee.experiment.util.BoundingBox3D(i_low: int, i_high: int, j_low: int, j_high: int, k_low: int, k_high: int, *, original_shape: Optional[Tuple[int, int, int]] = None)[source]

Bases: object

crop_to_bbox(tensor: torch.Tensor) torch.Tensor[source]

returns the tensor cropped around the saved bbox

static find_bbox(mask: torch.Tensor, *, pad: int = 0) Tuple[int, int, int, int, int, int][source]
classmethod from_batch(batch: torch.Tensor, *, pad: int = 0, channel: int = 0, foreground_min: float = 0.0001) tiramisu_brulee.experiment.util.T[source]

create bbox that works for a batch of 3d vols

classmethod from_image(image: torch.Tensor, *, pad: int = 0, foreground_min: float = 0.0001) tiramisu_brulee.experiment.util.T[source]

find a bounding box for a 3D tensor (with optional padding)

static get_shape(image: torch.Tensor) Tuple[int, int, int][source]
uncrop(tensor: torch.Tensor) torch.Tensor[source]

places a tensor back into the saved original shape

uncrop_batch(batch: torch.Tensor) torch.Tensor[source]

places a batch back into the saved original shape

tiramisu_brulee.experiment.util.append_num_to_filename(filepath: Union[str, pathlib.Path], *, num: int) pathlib.Path[source]

append num to the filename of filepath and return the modified path

tiramisu_brulee.experiment.util.image_one_hot(image: torch.Tensor, *, num_classes: int) torch.Tensor[source]
tiramisu_brulee.experiment.util.minmax_scale_batch(x: torch.Tensor) torch.Tensor[source]

rescale a batch of image PyTorch tensors to be between 0 and 1

tiramisu_brulee.experiment.util.reshape_for_broadcasting(tensor: torch.Tensor, *, ndim: int) torch.Tensor[source]

expand dimensions of a 0- or 1-dimensional tensor to ndim for broadcast ops

tiramisu_brulee.experiment.util.setup_log(verbosity: int) None[source]

set logger with verbosity logging level and message

tiramisu_brulee.experiment.util.split_filename(filepath: Union[str, pathlib.Path]) Tuple[pathlib.Path, str, str][source]

split a filepath into the directory, base, and extension

tiramisu_brulee.experiment.util.to_np(x: torch.Tensor) numpy.ndarray[source]

convert a PyTorch torch.Tensor (potentially on GPU) to a numpy array

Module contents

Segmentation module for tiramisu_brulee including CLI.