mednet.models.temporal.vitgru

Vision Transformer + GRU for temporal classification.

architecture, img_size, and global_pool must match the timm backbone and the Resize in model_transforms (see mednet.config.temporal.models.vitgru).

Functions

apply_backbone_unfreeze_last_n(backbone, n)

Set requires_grad on a timm ViT-like backbone from its blocks only.

Classes

ViTGRU([loss_type, loss_arguments, ...])

Vision Transformer backbone followed by a GRU temporal head.

mednet.models.temporal.vitgru.apply_backbone_unfreeze_last_n(backbone, n)[source]

Set requires_grad on a timm ViT-like backbone from its blocks only.

Parameters:
  • backbone (Module) – Module with a blocks ModuleList (timm vision transformer).

  • n (int | None) – If None or n >= len(blocks), every parameter in backbone is trainable. Otherwise all backbone parameters are frozen, then the last n block modules are unfrozen (n == 0 freezes the full backbone).

Raises:
  • TypeError – If backbone has no blocks attribute.

  • ValueError – If n is negative or greater than len(blocks).

Return type:

None

class mednet.models.temporal.vitgru.ViTGRU(loss_type=torch.nn.BCEWithLogitsLoss, loss_arguments=None, optimizer_type=torch.optim.Adam, optimizer_arguments=None, scheduler_type=None, scheduler_arguments=None, model_transforms=None, augmentation_transforms=None, architecture='vit_small_patch16_224.augreg_in21k', pretrained=True, img_size=224, global_pool='token', hidden_dim=256, num_layers=1, dropout=0.2, bidirectional=False, num_classes=1, drop_path_rate=0.0, unfreeze_last_n_backbone_blocks=None, temporal_pooling='last')[source]

Bases: Model

Vision Transformer backbone followed by a GRU temporal head.

Parameters:
  • loss_type (type[Module]) – Loss to be used for training and evaluation.

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

  • optimizer_type (type[Optimizer]) – Optimizer type for training.

  • optimizer_arguments (dict[str, Any] | None) – Optimizer arguments after params.

  • scheduler_type (type[LRScheduler] | None) – Optional scheduler type.

  • scheduler_arguments (dict[str, Any] | None) – Optional scheduler arguments after optimizer.

  • model_transforms (Optional[Sequence[Callable[[Tensor], Tensor]]]) – Transforms to apply in the data pipeline before model input.

  • augmentation_transforms (Optional[Sequence[Callable[[Tensor], Tensor]]]) – Optional augmentations applied in training_step.

  • architecture (str) – Name of the ViT architecture to instantiate from timm.

  • pretrained (bool) – If set to True, loads pretrained backbone weights from timm.

  • img_size (int) – Input image size.

  • global_pool (Literal['', 'avg', 'avgmax', 'max', 'token', 'map']) – Pooling strategy for ViT features.

  • hidden_dim (int) – Hidden size of the GRU.

  • num_layers (int) – Number of GRU layers.

  • dropout (float) – Dropout on top of the GRU output.

  • bidirectional (bool) – If set, uses a bidirectional GRU.

  • num_classes (int) – Number of output classes.

  • drop_path_rate (float) – Stochastic depth rate on the timm ViT backbone.

  • unfreeze_last_n_backbone_blocks (int | None) – Train only the last n entries in backbone.blocks; stem, global norm, and earlier blocks stay frozen when n < len(blocks). None or n >= len(blocks) finetunes the entire backbone. n == 0 keeps the backbone frozen (GRU + classifier still train).

  • temporal_pooling (Literal['last', 'attention']) – How to aggregate GRU outputs into an exam vector. "last" uses the final hidden state (legacy). "attention" learns a softmax weight over all timesteps (padding and one_per_phase padding slots are masked).

property num_classes: int

Number of outputs (classes) for this model.

Returns:

The number of outputs supported by this model.

Return type:

int

forward_explain(images, lengths, phase_ids=None, *, return_prefix_logits=False)[source]

Like forward() but also returns attention weights (B, T).

For temporal_pooling == "attention" the weights are the learned softmax attention over timesteps. For temporal_pooling == "last" they are one-hot on the pooled frame (the last real timestep), so the same per-frame reporting works for both. Padding timesteps receive weight zero.

If return_prefix_logits is True, also returns prefix logits (B, T, C): the classifier applied to each GRU output timestep (running summary state after each frame). Padding positions are nan.

Parameters:
  • images (Tensor) – Input tensor shaped as (batch, time, channels, height, width).

  • lengths (Tensor) – Real sequence lengths for each batch sample.

  • phase_ids (Tensor | None) – Optional per-frame phase ids (batch, time).

  • return_prefix_logits (bool) – If True, also return per-timestep prefix logits (B, T, C).

Returns:

(logits, weights) or (logits, weights, prefix_logits) when return_prefix_logits is True.

Return type:

tuple[Tensor, Tensor] | tuple[Tensor, Tensor, Tensor]

forward(images, lengths, phase_ids=None)[source]

Run temporal inference.

Parameters:
  • images (Tensor) – Input tensor shaped as (batch, time, channels, height, width).

  • lengths (Tensor) – Real sequence lengths for each batch sample.

  • phase_ids (Tensor | None) – Optional per-frame phase ids (batch, time). one_per_phase padding slots (_PHASE_ID_PADDING) are zeroed before the GRU and masked in attention pooling.

Returns:

Class logits shaped as (batch, num_classes).

Return type:

Tensor

training_step(batch, batch_idx)[source]

Perform a training step.

Parameters:
  • batch – The batch to apply the training step on. Should contain image and target keys.

  • batch_idx – The index of the batch, will be ignored.

Returns:

Training loss for the batch.

Return type:

torch.Tensor

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

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)