Code: github.com/PhilippMarquardt/VisualDL

VisualDL: A Deep Learning Framework for Computer Vision

VisualDL started as a side project, out of interest. I kept writing the same training script for every new dataset, each with its own bugs, and wanted to know how far one framework could go: a dataset folder and one YAML file, and nothing else, to train classification, segmentation, instance segmentation or detection models, with the checkpoint loading back for inference in one call. I wrote it by hand, before coding assistants existed.

It grew over about 210 commits between May 2021 and November 2024. Along the way HS Analysis adopted it as the training backend of its software, whose models run daily in hospitals and at industry customers. From then on it met real datasets: tissue in microscopy slides, cells in fluorescence images, organs in scans, parts in industrial images. They were often small, sometimes had more than three channels, and were usually labelled only as segmentation masks, and much of what follows was built to handle them.

What it supports
Tasks8 trainers: classification, semantic segmentation, instance segmentation, object detection, detection-guided segmentation, time series, video and MLPs
ModelsAny timm classifier; every Segmentation Models PyTorch decoder with any of its encoders; 8 extra segmentation architectures; Mask R-CNN; YOLOv5
Small, hard datasetsBorder weight maps, distance-map outputs, class weights, combined losses, multi-channel input, partial weight loading
DeploymentSelf-describing checkpoints, one inference API for every task, post-processing for clean masks, offline training without pretrained weights

1. One config for every task

The type field picks the trainer. Everything else is the same idea in every task: data folders, a list of models, settings and augmentations.

TaskModelsData
ClassificationAny of the hundreds of timm models, pretrainedOne folder per class
Semantic segmentationU-Net, U-Net++, FPN, DeepLabV3+ and the other SMP decoders on any encoder, plus 8 custom architectures (section 2)images/ and labels/
Instance segmentationMask R-CNNThe same segmentation masks (section 4)
Object detectionYOLOv5, from my fork that stores the training metadata inside the checkpointYOLO format
Detection + segmentationA YOLO model finds object centres, a segmentation model the pixels, and a watershed splits touching objects (section 5)Both models
Time series1D CNN with an optional bidirectional LSTM, predicting classes and continuous values at onceJSON
VideoA timm encoder per frame and a bidirectional LSTM over the framesFrame sequences
MLPSmall fully connected networks, used for example to predict spectra from concentrationsJSON

A segmentation config trains several models in one run. Each entry in models is an encoder and a decoder, with its own batch size and its own starting weights:

type: "segmentation"

data:
  train: "dataset/train"
  valid: "dataset/valid"
  test: "dataset/valid"
  weights: ["None", "None", "previous_run.pt"]
  save_folder: "runs"

models:
  - backbone: "tu-resnest50d"
    decoder: "Unet"
  - backbone: "efficientnet-b4"
    decoder: "UnetPlusPlus"
  - backbone: "resnet50"
    decoder: "DoubleUnet"

settings:
  nc: 3
  in_channels: 4                # e.g. fluorescence channels
  epochs: 3000
  optimizer: "AdamW"
  lr: 1e-4
  workers: 4
  batch_size: [16, 8, 8]        # one per model
  gradient_accumulation: 16
  max_image_size: 512           # needed by transformer models
  scales: "None"
  use_attention: False          # scSE attention in the decoder
  add_object_detection_model: False
  criterions: ["DiceLoss", "CrossEntropyLoss"]
  metrics:
    - name: "IoU"
      params: "num_classes=3"
  monitor_metric_name: "IoU"
  monitor_metric_params: "num_classes=3"
  class_weights: True
  calculate_weight_map: True
  calculate_distance_maps: True
  early_stopping: 500
  tensorboard_log_dir: "tensorboard_log"
  custom_data: {}               # stored in the checkpoint

transforms:                     # any Albumentations transform
  Resize: width = 512, height = 512
  HorizontalFlip: p=0.25
  VerticalFlip: p=0.25
  RandomRotate90: p=0.15
  Affine: p=0.15
  RandomBrightnessContrast: p=0.15
from visualdl import vdl
vdl.train("segmentation.yaml")

2. The segmentation models

Most projects were segmentation, so that is where most of the work went. Beyond every decoder and encoder in Segmentation Models PyTorch (including all timm encoders), VisualDL brings eight architectures from papers, wired so that they take the same config, the same losses and the same multi-channel input:

ArchitectureIdea
U²-NetNested U-blocks inside a U-Net for multi-scale features without a pretrained backbone
DoubleUNetTwo stacked U-Nets, the second refining the first one's output
HRNetV2Keeps a high-resolution branch through the whole network
CaraNetReverse and axial attention for small objects, from polyp segmentation
DPTA vision transformer encoder (ViT-hybrid) with a convolutional decoder
UNETRA pure transformer encoder feeding a U-Net decoder
Medical TransformerGated axial attention for small medical datasets
TransInUnetA transformer block inside a U-Net

There is also an implementation of hierarchical multi-scale attention (Tao et al., 2020), which runs the network at several scales and learns per-pixel weights for combining them.

3. Training on small, hard datasets

Medical and microscopy datasets break the defaults: objects touch, classes are rare, there are four or more channels, and the PC that trains the model is often not allowed on the internet. These are the parts I am most proud of, because each came from a real dataset that didn't work without it.

Weight map, distance map and detector-seeded watershed on a toy mask

A toy mask with touching objects of two classes, and what VisualDL computes from it.

  • Weight maps. Pixels on the border between touching objects are what a segmentation model gets wrong, and they are a tiny fraction of the loss. VisualDL dilates the mask, finds the ring around each object, and weights those pixels three times as much in the cross-entropy loss, like the original U-Net paper.
  • Distance maps. With calculate_distance_maps, the model gets one extra output channel that predicts, for every object separately, the normalised distance from its border. It is trained with an MSE loss next to the class output. The model learns where object centres are, which is exactly the information needed to split touching objects later.
  • Class weights. Computed from the training masks (one minus the average share of each class), so rare classes are not ignored.
  • Combined losses and any metric. Several losses are summed (Dice plus cross-entropy by default). Any torchmetrics metric can be logged, and one of them decides the best checkpoint and early stopping.
  • Multi-channel images. Images can be TIFFs with any number of channels. in_channels reaches the encoder, and for Mask R-CNN the first convolution and the input normalisation are replaced.
  • Partial weight loading. Starting weights are copied tensor by tensor wherever the shapes match. A model trained for 3 classes can start a 5-class model, and an RGB model can start a 4-channel one.
  • Offline training. Before downloading pretrained weights VisualDL checks for an internet connection, and trains from scratch if there isn't one, instead of crashing on a hospital PC.
  • The usual, done once. Mixed precision, gradient accumulation, every Albumentations transform from the config, TensorBoard logging, and a checkpoint for the best validation score.

4. Instance segmentation from segmentation masks

For most projects only semantic masks existed: a pixel is "cell" or "background", but nobody had labelled which cell is which. Labelling instances again was not an option, so the instance trainer builds them itself. It finds every contour in the mask, takes its bounding box, gives it the class most of its pixels have, and turns it into a Mask R-CNN target. Every model type therefore trains from the same dataset, and switching from semantic to instance segmentation is a change of one word in the config.

5. Splitting touching objects

Counting cells or nuclei needs separate objects, and a segmentation mask merges everything that touches. VisualDL has a combined mode for this: a YOLO detector predicts the object centres, those centres seed a watershed on the distance transform of the segmentation mask, and the watershed draws the borders between touching objects (the right panel above).

Inference also has post-processing that came straight from customer feedback:

  • One class per object. Each connected region gets the class most of its pixels have, so a cell is never half one class and half another.
  • Minimum size. Regions below a given area are removed.
  • Hole filling. Holes inside objects are filled, class by class.

6. Checkpoints that describe themselves

A checkpoint stores the weights together with the code string that builds the model, the number of channels, whether it has a distance-map output, the train and validation metrics, and any custom data a project needs, such as the image size it was trained on. Inference therefore needs nothing but the file:

from visualdl import vdl
import cv2

model = vdl.get_inference_model("runs/tu-resnest50d, Unet.pt")    # segmentation by default
image = cv2.imread("image.png")[..., ::-1]                        # RGB
masks, distance_maps = model.predict([image], single_class_per_contour=True, min_size=50, fill_holes=True)

classifier = vdl.get_inference_model("classifier.pt", type="classification")
detector = vdl.get_inference_model("yolo.pt", type="od")

After training several models, the trainer can evaluate every combination of them on the test set, so you can see whether an ensemble of two or three models beats the best single one.

7. Looking back

VisualDL was written before coding assistants, and some choices show it. The config strings are turned into Python objects with eval, which made adding a new loss or metric a one-line change but turns a typo into a confusing error. Several architectures were copied in from their papers' repositories rather than kept as dependencies. And it never had a proper test suite: it was tested on the next real dataset.

Its successor is MMWrapper, which keeps the same one-config idea but builds on the OpenMMLab ecosystem for production use.