{ "cells": [ { "cell_type": "markdown", "id": "277e99cb", "metadata": {}, "source": [ "# Deepvisiontools: Advanced usages\n", "\n", "**Tutorial time: about 1h30**\n", "\n", "Welcome to deepvisiontools' advanced usages tutorials.\n", "\n", "The required prior knowledge for this tutorial is basic knowledge about deepvisiontools. Average knowledge about python, while not required, might be helpful as well. To get started with deepvisiontools (installation and basic usages) we recommend that you first complete the getting_started tutorial.\n", "\n", "The difficulty of this tutorial is crescent, the easiest parts are covered first\n", "\n", "This tutorial will cover:\n", "1. Exhaustive global configuration capacities\n", "2. Exhaustive training configuration overview\n", "3. Inference customizable parameters\n", "4. Custom Reader/writers for DeepVisionDataset\n", "5. Custom Model implementation using DeepVisionModel\n", "\n", "**We strongly recommend that you have CUDA available on your machine to train on GPU.**\n", "\n", "To get started, please set up a Python environment (>= 3.10) and install the latest version of deepvisiontools with:\n", "\n", "```bash\n", "pip install deepvisiontools\n", "```\n", "\n", "You can download the demo datasets by running the following command in a shell:\n", "\n", "```bash\n", "deepvisiontools download-demo-datasets\n", "```\n", "\n", "You should obtain 3 datasets located in a `demo_datasets` folder:\n", "- Dice dataset: bounding box detection of dice\n", "- Vegann subset: vegetation vs. background segmentation in an agricultural context\n", "- COCO subset: common-object instance segmentation (1 mask per object present)\n", "\n", "The complete original datasets were found here:\n", "\n", "- The dice dataset was downloaded from Kaggle: https://www.kaggle.com/datasets/nellbyler/d6-dice\n", "- The VegannSubDataset is a small portion from: https://zenodo.org/records/7636408\n", "- The coco_6cls_subset was obtained from: https://universe.roboflow.com/nan-ixwz3/coco-y1tdb\n", "\n", "**Important: To have the same paths as the ones used in the tutorials, we suggest creating a root folder containing 2 folders: `tutos` (for all tutorials) and `demo_datasets` (for all datasets). Otherwise, you will need to change all paths accordingly.**\n", "\n", "For time considerations, this tutorial uses the Dice detection dataset.\n", "\n", "### Check that CUDA is available on your machine\n", "\n", "First, check that CUDA is available. If the output of the cell is `True`, then you can continue. Otherwise, we advise you to test deepvisiontools on a machine where CUDA is available (GPU + proper libraries installed)." ] }, { "cell_type": "code", "execution_count": null, "id": "2ff02b20", "metadata": {}, "outputs": [], "source": [ "import torch\n", "\n", "torch.cuda.is_available()" ] }, { "cell_type": "markdown", "id": "54ce8463", "metadata": {}, "source": [ "\n", "The output is a quick environment check. If it prints `True`, the notebook can use `device=\"cuda\"`. If it prints `False`, the configuration cells still work, but training should either be skipped or switched to `\"cpu\"`.\n", "\n", "## Global configuration\n", "\n", "Let's start by having a deeper look at the global configuration in deepvisiontools. The global configuration must be considered as a generic fallback and most of the important elements can be directly controlled in the various part of the library. For example, you can default the device to \"cuda\" in the config, but when using `launch` to actually start training, you can pass \"cpu\" as argument and the whole training will occur in cpu. The behaviour is similar for amp (automatic mixed precision). If use_amp is enabled at the model or training level, no matter what the global configuration says, amp will be enabled.\n", "\n", "The global configuration remains important, and we strongly suggest that you parametrize it as close as you can from the actual expected behaviour as it will provides an additional safety in case you forget to explicitly state it somewhere in your scripts ...\n", "\n", "Let's have a look at what is currently available in the global config by creating one from scratch. Note that in most cases, you only need to use the default one and changes what you want to change by using the helpers. But it's worth having a deep look to exhibit all possible configuration options.\n", "\n", "The global config is handled by a specific object, `DVConfig` composed of multiple sub config dedicated to specific part of the library. Note that the classes are non mutable, to preserve stability when having distributed computation, therefore the easiest way of modifying it is by using the various helpers showed in the getting started tutorial.\n", "\n", "Here we display everything that is set by default in deepvisiontools, so you can understand on what you can play." ] }, { "cell_type": "code", "execution_count": null, "id": "b91b22ab", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import current, set_current\n", "from deepvisiontools.config import VizCfg, LogCfg, DVConfig, BboxCfg, InstanceMaskCfg, SemanticMaskCfg\n", "import logging\n", "\n", "# The logging config allows to control the warning level.\n", "# To be fair, this is not fully exploited yet in deepvisiontools but might become in future releases\n", "\n", "log_config = LogCfg(\n", " level=logging.WARNING,\n", " enabled=True,\n", " duplicate_filter=True\n", ")\n", "\n", "# This part controls the visualizations (from datasets / predictor / evaluator) created in deepvisiontools\n", "\n", "viz_config = VizCfg(\n", " window_mode=\"dual\", # single or dual -> either produce a single window with only the visualization or concat with original image\n", " desired_min_size=1200, # deepvisiontools resize the visualizations produced. This is the resulting size of the smallest side of the image after resizing \n", " mask_alpha=0.6, # transparency of the masks\n", " box_line_width=3,\n", " outline_width=2,\n", " class_colors=None, # you can pass custom colors\n", " instance_colors=None, # idem\n", " show_scores=True, \n", " categories=None # you can name the categories you are considering to display them instead of numbers in visualizations. It must be a dict associating a label with the category name\n", ")\n", "\n", "# The following handles the BboxData behaviour + detection model post process\n", "# Note that the best way to handle postprocess is via the PredParams option directly in the model as we will see later, but this is a safety fallback\n", "\n", "box_config = BboxCfg(\n", " type = \"bbox\", # the name : don't touch it\n", " num_classes=1,\n", " min_size=5, # the minimal side of a box: if a box has shorted side, it will be removed by sanitize. This is particularly helpful when using augmentations / crops that can cut most of the object but leaves some tiny portion alive.\n", " conf_threshold=0.5, # confidence threshold in inference\n", " nms_threshold=0.5, # nms threshold in inference\n", " max_det=500 # maximum number of object per image in inference\n", ")\n", "\n", "# similar but for InstanceMaskData\n", "\n", "instance_config = InstanceMaskCfg(\n", " type=\"instance_mask\",\n", " num_classes=1,\n", " min_size=5, # same as for bouding box but this is actually the number of pixel present in the mask.\n", " conf_threshold=0.5,\n", " nms_threshold=0.5,\n", " mask_logits_threshold=0.5, # instance segmentation produce also logits for the masks, you can decide at which threshold they should be kept or not\n", " max_det=0.5\n", ")\n", "\n", "# similar but for SemanticMaskData\n", "\n", "semantic_config = SemanticMaskCfg(\n", " type=\"semantic_mask\",\n", " num_classes=1, # remember that in binary task it must be set to 1, and in 2 or more target classes you must also add the background! (so num_classes=2 never exist)\n", " min_size=0,\n", " binary_logits_threshold=0.5,\n", " logits_combine=\"avg\" # This is the way we are merging multiple semantic masks when running sliding window inference. You can use max or min as well.\n", ")\n", "\n", "# The overall config \n", "\n", "config = DVConfig(\n", " device=\"cpu\",\n", " log=log_config,\n", " viz=viz_config,\n", " data_box=box_config,\n", " data_instance_mask=instance_config,\n", " data_semantic_mask=semantic_config,\n", " amp=True # torch automatic precision default setup. Can be overriden later in TrainerConfig\n", ")\n", "\n", "# set the config to current global config\n", "\n", "set_current(config)" ] }, { "cell_type": "markdown", "id": "29312bae", "metadata": {}, "source": [ "As you can see, there is already a lot you can customize. The most important are of course the device and the data." ] }, { "cell_type": "markdown", "id": "62e56ee4", "metadata": {}, "source": [ "## Exhaustive Training configuration\n" ] }, { "cell_type": "markdown", "id": "c4b03869", "metadata": {}, "source": [ "We are going to all training configuration capacities, built from scratch, to exhibit the whole set of parameters you can customize. In the various subsections we will cover in more detail each part so you can a complete overview on the advanced training tricks that are parametrizable in deepvisiontools.\n", "\n", "Let's start by defining the dataloaders, which are mandatory parts of the `TrainerConfig` (we will use the dice dataset as an example, cf. demo-datasets you used in getting_started tutorial)" ] }, { "cell_type": "code", "execution_count": null, "id": "e45bd59c", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import DeepVisionDataset, DeepVisionLoader\n", "import torchvision.transforms.v2 as v2\n", "\n", "def yolo_preprocessing(x):\n", " return x / 255.0\n", "\n", "train_aug = [\n", " v2.RandomHorizontalFlip(p=0.5),\n", " v2.ColorJitter(\n", " brightness=0.15,\n", " contrast=0.15,\n", " saturation=0.15,\n", " hue=0.05,\n", " ),\n", "]\n", "\n", "dice_dataset = DeepVisionDataset(\n", " \"../demo_datasets/DiceDataset\",\n", " reader=\"coco\",\n", " data_type_reader=\"bbox\",\n", " augmentation=train_aug,\n", " preprocessing=yolo_preprocessing,\n", ")\n", "\n", "train_set, valid_set, test_set = dice_dataset.split([0.7, 0.2, 0.1])\n", "\n", "train_loader = DeepVisionLoader(\n", " train_set,\n", " batch_size=8,\n", " shuffle=True,\n", ")\n", "valid_loader = DeepVisionLoader(\n", " valid_set,\n", " batch_size=8,\n", " shuffle=False,\n", ")" ] }, { "cell_type": "markdown", "id": "62b1b129", "metadata": {}, "source": [ "Let's build from scratch a first base TrainerConfig example" ] }, { "cell_type": "code", "execution_count": null, "id": "66f26ed7", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools.train import TrainerConfig, ModelSpec\n", "\n", "def build_base_dice_config():\n", " model_kwargs = {\n", " \"arch\": \"yolo11n\",\n", " \"pretrained\": True,\n", " \"num_classes\": 1,\n", " \"device\": None,\n", " \"use_amp\": None,\n", " }\n", "\n", " # The minimum set for TrainerConfig is a) model b) train and valid dataloader\n", "\n", " config = TrainerConfig(\n", " model_spec=ModelSpec(\n", " builder=\"yolo\",\n", " kwargs=model_kwargs,\n", " ),\n", " train_loader=train_loader,\n", " valid_loader=valid_loader,\n", " epochs=3,\n", " output_dir=\"advanced_dice_runs\",\n", " )\n", "\n", " # configuration of the device part\n", "\n", " config.devices.device = \"cuda\"\n", " config.devices.strategy = \"auto\"\n", " config.devices.num_workers = 0\n", " config.devices.pin_memory = True\n", "\n", " # Optimization part\n", "\n", " config.optim.optimizer = torch.optim.AdamW\n", " config.optim.optim_args = {\n", " \"lr\": 2e-4,\n", " \"betas\": (0.9, 0.999),\n", " }\n", " config.optim.weight_decay = 1e-4\n", "\n", " # scheduler\n", "\n", " config.sched.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR\n", " config.sched.scheduler_args = {\n", " \"T_max\": \"auto\",\n", " \"eta_min\": 1e-6,\n", " }\n", " config.sched.step_on = \"epoch\"\n", "\n", " # monitoring\n", "\n", " config.logging.backends = [\"mlflow\"]\n", " config.logging.mlflow_experiment_name = \"advanced_dice\"\n", " config.logging.mlflow_run_name = \"baseline\"\n", "\n", " # checkpoint\n", "\n", " config.checkpoint.monitor = (\"valid/loss\", \"loss\") # this part is important : it defines how deepvisiontools selects best models. Note that you should privilege metrics such as mAP, IoU etc. with the \"max\" argument\n", " config.checkpoint.mode = \"min\"\n", " config.checkpoint.save_every_n_epochs = 1\n", " config.checkpoint.keep_last_n = 2\n", " config.checkpoint.export_model_artifact = True\n", " config.checkpoint.export_when = \"best\"\n", "\n", " return config\n", "\n", "base_config = build_base_dice_config()\n", "base_config.validate()\n", "\n", "print(base_config)" ] }, { "cell_type": "markdown", "id": "46edcb9b", "metadata": {}, "source": [ "\n", "This baseline config is the reference object for the rest of the tutorial. `ModelSpec` stores how to rebuild the model, `optim` and `sched` define optimization, `logging` defines the experiment metadata, and `checkpoint` decides what is saved." ] }, { "cell_type": "markdown", "id": "897503f8", "metadata": {}, "source": [ "### EMA: smoother weights for validation and export\n", "\n", "EMA means **Exponential Moving Average**. During training, deepvisiontools keeps a second copy of the model weights. After each optimizer step, the EMA copy is updated as:\n", "\n", "```text\n", "ema_weight = decay * ema_weight + (1 - decay) * current_weight\n", "```\n", "\n", "The idea is simple: the normal model weights can move a lot from one step to the next, while the EMA weights are smoother.\n", "\n", "```text\n", "optimizer step ──> model weights ──> next step\n", " │\n", " └──> EMA shadow weights ──> validation / best *_ema artifact\n", "```\n", "\n", "The main parameters are:\n", "\n", "- `enabled`: turn EMA on or off.\n", "- `decay`: smoothing strength. Higher values make EMA slower but smoother.\n", "- `update_every`: update EMA every N optimizer steps.\n", "- `warmup_steps`: ramp the effective decay at the beginning of training.\n", "- `eval_with_ema`: use EMA weights during validation." ] }, { "cell_type": "code", "execution_count": null, "id": "8d25ba3a", "metadata": {}, "outputs": [], "source": [ "from copy import deepcopy\n", "\n", "ema_config = deepcopy(base_config)\n", "\n", "ema_config.ema.enabled = True\n", "ema_config.ema.decay = 0.995\n", "ema_config.ema.update_every = 1\n", "ema_config.ema.warmup_steps = 100\n", "ema_config.ema.eval_with_ema = True\n", "\n", "print(ema_config.ema)" ] }, { "cell_type": "markdown", "id": "e462dc0c", "metadata": {}, "source": [ "\n", "You just enabled EMA and selected how the shadow weights are updated. `update_every=1` updates EMA after each optimizer step, while `eval_with_ema=True` means validation evaluates metrics with the smoother EMA weights." ] }, { "cell_type": "markdown", "id": "eb202cc5", "metadata": {}, "source": [ "A few practical rules:\n", "\n", "- For short demo trainings, `decay=0.95` or `0.99` reacts faster.\n", "- For longer trainings, `0.995` to `0.9998` is usually more stable.\n", "- If you validate with EMA, use the exported EMA model for inference too.\n", "\n", "You can of course disable EMA" ] }, { "cell_type": "code", "execution_count": null, "id": "adc89b5d", "metadata": {}, "outputs": [], "source": [ "no_ema_config = deepcopy(base_config)\n", "\n", "no_ema_config.ema.enabled = False\n", "no_ema_config.ema.eval_with_ema = False\n", "\n", "print(no_ema_config.ema)" ] }, { "cell_type": "markdown", "id": "5f19b5fd", "metadata": {}, "source": [ "Note that EMA is known to increase generalization capability and increasing performances. However, it often required a couple more epochs to actually see the model improving during training, which depend of course on the decay parameter." ] }, { "cell_type": "markdown", "id": "4fc2842b", "metadata": {}, "source": [ "### LLRD: smaller learning rates in early layers\n", "\n", "LLRD means **Layer-wise Learning Rate Decay**. The key idea is to preserve earlier layer from loosing the often massive pretrained advantage while still fine-tuning the model.\n", "\n", "The intuition is:\n", "\n", "```text\n", "early backbone ──> middle backbone ──> late backbone ──> neck/head\n", " very small LR small LR medium LR base LR\n", "```\n", "\n", "If `base_lr = 1e-4` and `layer_decay = 0.85`, deepvisiontools assigns lower learning rates to earlier units:\n", "\n", "```text\n", "head_lr = base_lr\n", "previous_lr = base_lr * 0.85\n", "older_lr = base_lr * 0.85 ** 2\n", "...\n", "```\n", "\n", "The important parameters are:\n", "\n", "- `optim.param_groups=\"flat\"`: one parameter group, same LR everywhere.\n", "- `optim.param_groups=\"llrd\"`: generic LLRD grouping.\n", "- `optim.param_groups=\"layer_aware_llrd\"`: LLRD using semantic groups such as backbone, neck, head, encoder, decoder, etc.\n", "- `optim.layer_decay`: multiplier applied when moving from later layers to earlier layers.\n", "\n", "LLRD is especially useful for large backbones that were already pretrained. It is less important for very small YOLO demo runs, but the configuration is the same." ] }, { "cell_type": "code", "execution_count": null, "id": "eb3eef57", "metadata": {}, "outputs": [], "source": [ "llrd_config = deepcopy(base_config)\n", "\n", "llrd_config.optim.param_groups = \"layer_aware_llrd\"\n", "llrd_config.optim.layer_decay = 0.85\n", "llrd_config.optim.optim_args = {\n", " \"lr\": 2e-4,\n", " \"betas\": (0.9, 0.999),\n", "}\n", "llrd_config.optim.weight_decay = 0.05\n", "\n", "print(llrd_config.optim)" ] }, { "cell_type": "markdown", "id": "e21490c8", "metadata": {}, "source": [ "\n", "This asks the trainer to create several optimizer parameter groups instead of a single flat group. The head keeps the base learning rate and earlier backbone blocks receive smaller learning rates controlled by `layer_decay`." ] }, { "cell_type": "markdown", "id": "894ef75a", "metadata": {}, "source": [ "You can inspect the actual optimizer groups before running a full training. This is often useful to verify that the groups have names such as `backbone_*`, `neck_*`, or `head_*`.\n", "\n", "For big models, this print can be long. Here we only display a compact summary." ] }, { "cell_type": "code", "execution_count": null, "id": "5d734f39", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools.train.trainer import build_param_groups\n", "\n", "model_for_inspection = llrd_config.build_model()\n", "param_groups = build_param_groups(model_for_inspection, llrd_config)\n", "\n", "for group in param_groups[:8]:\n", " name = group.get(\"name\", \"unnamed\")\n", " lr = group.get(\"lr\", llrd_config.optim.optim_args[\"lr\"])\n", " wd = group.get(\"weight_decay\", llrd_config.optim.weight_decay)\n", " n_params = len(group[\"params\"])\n", " print(f\"{name:35s} lr={lr:.3e} wd={wd} n={n_params}\")" ] }, { "cell_type": "markdown", "id": "c531fcd0", "metadata": {}, "source": [ "\n", "The printed list is a preview of the optimizer groups that will be passed to `AdamW`. Seeing several different learning rates confirms that LLRD was actually applied to the model structure." ] }, { "cell_type": "markdown", "id": "d586b670", "metadata": {}, "source": [ "### Backbone and BatchNorm freezing\n", "\n", "Freezing is useful when the dataset is small or when the first epochs are unstable. BatchNorm freezing is often quite important if you are training on multiple GPU while having a small micro-batch. Indeed, BatchNorm can become instable in case the number of samples per batch is not large enough.\n", "\n", "There are two different ideas:\n", "\n", "1. **Backbone freezing**: temporarily freeze backbone parameter groups at the beginning of training.\n", "2. **BatchNorm freezing**: keep BatchNorm statistics fixed, which is often safer with tiny batch sizes.\n", "\n", "For backbone freezing, deepvisiontools looks for optimizer parameter groups whose name is `backbone` or starts with `backbone_`. This means it works best together with LLRD / layer-aware LLRD groups.\n", "\n", "The parameters are:\n", "\n", "- `freezing.freeze_epochs`: number of first epochs during which backbone groups are frozen.\n", "- `freezing.backbone_group_name`: group-name prefix to freeze. Default is `\"backbone\"`." ] }, { "cell_type": "code", "execution_count": null, "id": "d0689383", "metadata": {}, "outputs": [], "source": [ "freeze_config = deepcopy(llrd_config)\n", "\n", "freeze_config.freezing.freeze_epochs = 2\n", "freeze_config.freezing.backbone_group_name = \"backbone\"\n", "\n", "print(freeze_config.freezing)" ] }, { "cell_type": "markdown", "id": "99ab354d", "metadata": {}, "source": [ "\n", "Here, the backbone is frozen only during the first two epochs. The detection head adapts first, then the backbone is unfrozen for normal fine-tuning. This often stabilizes small-dataset training." ] }, { "cell_type": "markdown", "id": "7c21a1e1", "metadata": {}, "source": [ "BatchNorm freezing is controlled by `normalization.policy`.\n", "\n", "The available policies are:\n", "\n", "- `\"auto\"`: freeze BatchNorm when the local micro-batch size is too small.\n", "- `\"none\"`: do not touch normalization layers.\n", "- `\"freeze_bn\"`: freeze BatchNorm / SyncBatchNorm layers.\n", "- `\"sync_bn\"`: convert BatchNorm to SyncBatchNorm under DDP + CUDA.\n", "- `\"sync_or_freeze_bn\"`: use SyncBatchNorm under DDP + CUDA, otherwise freeze BatchNorm.\n", "\n", "The two additional flags control what is frozen:\n", "\n", "- `freeze_affine=True`: freeze BatchNorm learnable `weight` and `bias`.\n", "- `freeze_running_stats=True`: keep running mean / variance fixed." ] }, { "cell_type": "code", "execution_count": null, "id": "5cb83c91", "metadata": {}, "outputs": [], "source": [ "freeze_config.normalization.policy = \"sync_or_freeze_bn\"\n", "freeze_config.normalization.freeze_affine = True\n", "freeze_config.normalization.freeze_running_stats = True\n", "freeze_config.normalization.verbose = True\n", "\n", "print(freeze_config.normalization)" ] }, { "cell_type": "markdown", "id": "f8f0a737", "metadata": {}, "source": [ "### Precision, accumulation, gradient clipping, and warmup\n", "\n", "The `precision` block controls mixed precision and gradient handling.\n", "\n", "- `precision.amp=None`: fallback to `current().amp`.\n", "- `precision.amp=True`: request AMP explicitly.\n", "- `precision.amp=False`: force full precision.\n", "- `precision.amp_dtype`: `\"bf16\"`, `\"fp16\"`, or `\"fp32\"`.\n", "- `precision.accumulate_steps`: perform one optimizer step every N batches.\n", "- `precision.grad_clip`: clip gradients before the optimizer step.\n", "\n", "You can see the fallback logic of amp here: if precision.amp is set to None, it uses the one defined in global config. However, the TrainerConfig wins in case a clear information is passed. grad clipping impose a hard limit on the gradient norm. This can help in case of unstable training by limiting the impact of specific batchs that could make the optimization diverge if the gradient is too large. Typical values are within the 1 - 10 range.\n", "\n", "accumulate step is a nice simple trick, that allow to mimic larger batch on smaller GPU: if you're limited by GPU memory, you can optimize once for every n batch. So the effective batch size (in terms of gradient stability) is simply batch size x accumulate steps." ] }, { "cell_type": "code", "execution_count": null, "id": "28dae182", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools.train import WarmupConfig\n", "\n", "precision_config = deepcopy(base_config)\n", "\n", "precision_config.precision.amp = True\n", "precision_config.precision.amp_dtype = \"bf16\"\n", "precision_config.precision.accumulate_steps = 2\n", "precision_config.precision.grad_clip = 5.0\n", "\n", "precision_config.sched.step_on = \"step\"\n", "precision_config.sched.warmup = WarmupConfig(\n", " steps=100,\n", " steps_unit=\"step\",\n", " ratio=1.0,\n", " start_factor=0.001,\n", ")\n", "\n", "precision_config.validate()\n", "print(precision_config.precision)\n", "print(precision_config.sched.warmup)" ] }, { "cell_type": "markdown", "id": "8d302770", "metadata": {}, "source": [ "\n", "Warmup lives in the scheduler config. If warmup is expressed in optimizer steps, the scheduler must follows. Warmup is progressively increasing the learning rate, starting really low, during the first steps/epochs of a training (typically 500 ish steps). This is particularly useful when you use optimizers that rely on momentum accumulation like Adam or AdamW." ] }, { "cell_type": "markdown", "id": "6c01d751", "metadata": {}, "source": [ "\n", "This configuration combines AMP, gradient accumulation, gradient clipping, and scheduler warmup. Because warmup is expressed in optimizer steps, the scheduler is also set to step mode so both mechanisms use the same unit." ] }, { "cell_type": "markdown", "id": "ea5eaaa9", "metadata": {}, "source": [ "### Checkpoints and model artifacts\n", "\n", "Checkpointing has two different roles:\n", "\n", "1. Restartable training checkpoints: optimizer, scheduler, scaler, EMA state, etc.\n", "2. Portable model artifacts: model builder + kwargs + weights for inference.\n", "\n", "The master switch is `checkpoint.enable_checkpointing`. For normal training, keep it enabled. For large Optuna runs (hyperparameters optimization), disabling it avoids writing many heavy artifacts." ] }, { "cell_type": "code", "execution_count": null, "id": "c1a15327", "metadata": {}, "outputs": [], "source": [ "checkpoint_config = deepcopy(base_config)\n", "\n", "checkpoint_config.checkpoint.enable_checkpointing = True\n", "checkpoint_config.checkpoint.monitor = (\"valid/loss\", \"loss\")\n", "checkpoint_config.checkpoint.mode = \"min\"\n", "checkpoint_config.checkpoint.filename = \"checkpoint\"\n", "checkpoint_config.checkpoint.save_every_n_epochs = 1\n", "checkpoint_config.checkpoint.keep_last_n = 2\n", "checkpoint_config.checkpoint.export_model_artifact = True\n", "checkpoint_config.checkpoint.export_when = \"best\"\n", "\n", "print(checkpoint_config.checkpoint)" ] }, { "cell_type": "markdown", "id": "9677de14", "metadata": {}, "source": [ "\n", "This is the normal experiment setup: restart checkpoints are written periodically, old checkpoints are pruned, and the best portable model artifact is exported according to the monitored validation loss." ] }, { "cell_type": "code", "execution_count": null, "id": "c124567b", "metadata": {}, "outputs": [], "source": [ "no_checkpoint_config = deepcopy(base_config)\n", "\n", "no_checkpoint_config.checkpoint.enable_checkpointing = False\n", "no_checkpoint_config.checkpoint.save_every_n_epochs = 0\n", "no_checkpoint_config.checkpoint.export_model_artifact = False\n", "\n", "print(no_checkpoint_config.checkpoint)" ] }, { "cell_type": "markdown", "id": "4301a6a3", "metadata": {}, "source": [ "\n", "This disables artifact/checkpoint writing while keeping training, validation, and logging active. It is especially useful for quick experiments and large Optuna studies where hundreds of checkpoints would be wasteful." ] }, { "cell_type": "markdown", "id": "65c5ce7f", "metadata": {}, "source": [ "### Metrics configuration\n", "\n", "Loss is always monitored during validation. If you also want task metrics, provide a `MetricsSpec`.\n", "\n", "For this Dice example, the task is bounding box detection, so we use `kind=\"bbox\"` and `num_classes=1`." ] }, { "cell_type": "code", "execution_count": null, "id": "ad396c13", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools.train import EvalConfig, MetricsSpec\n", "\n", "metrics_config = deepcopy(base_config)\n", "\n", "metrics_config.eval = EvalConfig(\n", " eval_every_n_steps=0,\n", " eval_on=\"valid\",\n", " metrics=MetricsSpec(\n", " kind=\"bbox\",\n", " num_classes=1,\n", " ),\n", ")\n", "\n", "metrics_config.validate() # useful to check that the whole config is interpretable by deepvisiontools\n", "\n", "print(metrics_config.eval)" ] }, { "cell_type": "markdown", "id": "10b4643f", "metadata": {}, "source": [ "\n", "The validation loop will now compute detection metrics in addition to loss. We still monitor `valid/loss` here, but the same monitor fields could point to a metric if that is the quantity you want to optimize.\n", "\n", "**If you use a registered TrainerConfig, metric will always be adapted to the model you've selected**" ] }, { "cell_type": "markdown", "id": "1794f953", "metadata": {}, "source": [ "### Device and DDP strategy\n", "\n", "The most common setting is:\n", "\n", "```python\n", "config.devices.device = \"cuda\"\n", "config.devices.strategy = \"auto\"\n", "```\n", "\n", "With `strategy=\"auto\"`, deepvisiontools stays in a normal single process unless the training is launched through `launch(...)` / `torchrun` with more than one process.\n", "\n", "Use `launch(main, devices=\"auto\")` to let deepvisiontools use all visible GPUs, or pass a specific subset such as `[0, 1]`." ] }, { "cell_type": "code", "execution_count": null, "id": "66ff2591", "metadata": {}, "outputs": [], "source": [ "ddp_config = deepcopy(base_config)\n", "\n", "ddp_config.devices.device = \"cuda\"\n", "ddp_config.devices.strategy = \"auto\"\n", "ddp_config.find_unused_parameters = False\n", "\n", "print(ddp_config.devices)" ] }, { "cell_type": "markdown", "id": "7c15e36e", "metadata": {}, "source": [ "\n", "The config is DDP-ready, but it does not force DDP by itself. The actual process layout is decided by `launch(...)`, so the same script can run on one GPU or several GPUs." ] }, { "cell_type": "markdown", "id": "acbcddd6", "metadata": {}, "source": [ "A minimal DDP-compatible training entry point looks like this:" ] }, { "cell_type": "code", "execution_count": null, "id": "93089c16", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import Trainer, launch\n", "\n", "ddp_config.epochs = 1\n", "\n", "def main():\n", " trainer = Trainer(ddp_config)\n", " trainer.fit(resume=None)\n", "\n", "# Single GPU / CPU fallback, or one process per visible GPU depending on your hardware configuration.\n", "launch(main, devices=\"auto\")" ] }, { "cell_type": "markdown", "id": "f8f60a0c", "metadata": {}, "source": [ "\n", "The important pattern is to create the `Trainer` inside `main()`. When `launch(...)` starts multiple processes, every process runs this function and the trainer binds itself to the correct rank/device." ] }, { "cell_type": "markdown", "id": "2828bbce", "metadata": {}, "source": [ "### Portable YAML export and reload\n", "\n", "Deepvisiontools propose some possibilities to export/load your Config using yaml files. This guarantee maximal reproducibility of your setup. However this comes at at a minor price in terms of ergonomy: TrainerConfig parameters must be exportable to yaml (str, int etc.). For some specific parts deepvisiontools does the conversion itself.\n", "\n", "A portable YAML config needs importable objects. For optimizers and schedulers, deepvisiontools converts classes such as `torch.optim.AdamW` to import specs. For models, use `ModelSpec`. This is why in the base configuration we used ModelSpec and optimizer was defined by separating the class and the kwargs.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ff51da94", "metadata": {}, "outputs": [], "source": [ "yaml_config = deepcopy(base_config)\n", "\n", "yaml_config.export_yaml(\n", " \"advanced_dice_config.yaml\",\n", " portable=True,\n", " include_meta=True,\n", ")\n", "\n", "reloaded_config = TrainerConfig.from_yaml(\n", " \"advanced_dice_config.yaml\",\n", " train_loader=train_loader,\n", " valid_loader=valid_loader,\n", ")\n", "\n", "print(reloaded_config.model_spec)\n", "print(reloaded_config.optim.optimizer)" ] }, { "cell_type": "markdown", "id": "1cde4737", "metadata": {}, "source": [ "\n", "The YAML file contains portable import specs for the optimizer/scheduler and a portable `ModelSpec` for the model. The dataloaders are passed again at reload time because they are runtime objects, not YAML content." ] }, { "cell_type": "markdown", "id": "96313153", "metadata": {}, "source": [ "## 3. Direct model building and prediction parameters\n", "\n", "You can build a model directly with `ModelFactory`. This is useful for quick experiments or for inference scripts.\n", "\n", "Most detection / instance segmentation wrappers expose prediction parameters such as confidence threshold, NMS IoU, and maximum detections. These parameters are stored on the model and are used by `predict`." ] }, { "cell_type": "code", "execution_count": null, "id": "57fc4cd9", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools.models import ModelFactory\n", "\n", "model = ModelFactory(\n", " \"yolo\",\n", " arch=\"yolo11n\",\n", " pretrained=True,\n", " num_classes=1,\n", " device=\"cuda\",\n", ")\n", "\n", "model.set_pred_params(\n", " conf_threshold=0.30,\n", " nms_iou=0.50,\n", " max_det=100,\n", ")\n", "\n", "print(model.pred_params)" ] }, { "cell_type": "markdown", "id": "86b7b553", "metadata": {}, "source": [ "\n", "`set_pred_params` changes only inference decoding. The model weights are unchanged; predictions are simply filtered with the new confidence threshold, NMS IoU threshold, and maximum detection count.\n", "\n", "Note that the actual parameters depend on the model wrapper. You can check the documentation of the models to see which one are customizable.\n", "\n", "Finally, for a proper inference we always recommend to use the `Predictor` class instead. In that case, the safest way to handle postprocessing args is to pass the proper model wrapper's `PredParam`" ] }, { "cell_type": "code", "execution_count": null, "id": "bac8c28c", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import Predictor\n", "from deepvisiontools.models.yolo import YoloPredParams\n", "\n", "params = YoloPredParams(conf_threshold=0.25, nms_iou=0.34, max_det=1000)\n", "\n", "predictor = Predictor(model=model, preprocessing=yolo_preprocessing, pred_params=params)" ] }, { "cell_type": "markdown", "id": "8c00fa25", "metadata": {}, "source": [ "Then use the standard `predictor.predict` method and the passed params will be used." ] }, { "cell_type": "markdown", "id": "904019b8", "metadata": {}, "source": [ "## 4. Custom dataset reader and writer\n", "\n", "DeepVisionDataset is intentionally format-agnostic. The registered COCO and\n", "semantic-mask-folder readers are convenient defaults, but they are not special\n", "inside the dataset class. A reader only needs to expose a small annotation API,\n", "and a writer only needs to know how to serialize one target at a time.\n", "\n", "In this section, we build a minimal YOLO-style detection format for the Dice\n", "dataset:\n", "\n", "```text\n", "yolo_dice_dataset/\n", "├── images/\n", "├── labels/\n", "│ ├── image_001.txt\n", "│ └── image_002.txt\n", "└── classes.txt\n", "```\n", "\n", "Each `.txt` file contains one box per line:\n", "\n", "```text\n", "class_id center_x center_y width height\n", "```\n", "\n", "The coordinates are normalized to `[0, 1]`, as in the usual YOLO layout.\n", "Inside deepvisiontools, however, the model-ready object remains a normal\n", "`BboxData` with pixel coordinates and a canvas size. The reader and writer are\n", "only responsible for converting between those two representations." ] }, { "cell_type": "code", "execution_count": null, "id": "357c6f52", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "from shutil import rmtree\n", "\n", "from PIL import Image\n", "\n", "from deepvisiontools.data import BaseData, BboxData\n", "from deepvisiontools.datasets.base import AnnotationReader, AnnotationWriter\n", "\n", "\n", "YOLO_DICE_ROOT = Path(\"yolo_dice_dataset\")" ] }, { "cell_type": "markdown", "id": "2ff4b031", "metadata": {}, "source": [ "We start with the writer because it gives us a simple way to create a\n", "YOLO-style copy of the existing Dice COCO dataset.\n", "\n", "The writer receives already-loaded targets from `DeepVisionDataset.export`.\n", "That means it does not need to know how the source dataset was stored. It only\n", "sees an image name, the image tensor, the current `BboxData`, and the category\n", "mapping.\n", "\n", "The important steps are:\n", "\n", "1. copy the target so we can change its box format without mutating the dataset,\n", "2. convert boxes to `CXCYWH`,\n", "3. normalize x/width by image width and y/height by image height,\n", "4. write one text file per image,\n", "5. write `classes.txt` once in `finalize`." ] }, { "cell_type": "code", "execution_count": null, "id": "f25c2985", "metadata": {}, "outputs": [], "source": [ "class YoloBBoxWriter(AnnotationWriter):\n", " supported_types = {\"bbox\"}\n", "\n", " def __init__(\n", " self,\n", " *,\n", " labels_subdir: str = \"labels\",\n", " classes_file: str = \"classes.txt\",\n", " ) -> None:\n", " self.labels_subdir = labels_subdir\n", " self.classes_file = classes_file\n", " self._records: list[tuple[str, list[str]]] = []\n", " self._categories: dict[int, str] = {}\n", "\n", " @property\n", " def file_extension(self) -> str:\n", " return \"txt\"\n", "\n", " def write_item(\n", " self,\n", " image_name: str,\n", " image: torch.Tensor,\n", " target: BaseData,\n", " categories: dict[int, str],\n", " ) -> None:\n", " if not isinstance(target, BboxData):\n", " raise TypeError(\"YoloBBoxWriter expects BboxData targets.\")\n", "\n", " self._categories.update({int(k): str(v) for k, v in categories.items()})\n", "\n", " box_target = target._new_like()\n", " box_target.boxformat = \"CXCYWH\"\n", "\n", " height, width = int(image.shape[-2]), int(image.shape[-1])\n", " boxes = torch.as_tensor(box_target.value).detach().cpu().float()\n", " labels = box_target.labels.detach().cpu().long()\n", "\n", " lines = []\n", " for label, box in zip(labels.tolist(), boxes.tolist(), strict=False):\n", " cx, cy, bw, bh = box\n", " normalized = [\n", " cx / width,\n", " cy / height,\n", " bw / width,\n", " bh / height,\n", " ]\n", " values = \" \".join(f\"{v:.6f}\" for v in normalized)\n", " lines.append(f\"{int(label)} {values}\")\n", " self._categories.setdefault(int(label), f\"class_{int(label)}\")\n", "\n", " label_name = Path(image_name).with_suffix(\".txt\").name\n", " self._records.append((label_name, lines))\n", "\n", " def finalize(self, destination_root: str | Path) -> None:\n", " root = Path(destination_root)\n", " labels_dir = root / self.labels_subdir\n", " labels_dir.mkdir(parents=True, exist_ok=True)\n", "\n", " for label_name, lines in self._records:\n", " text = \"\\n\".join(lines)\n", " if text:\n", " text += \"\\n\"\n", " (labels_dir / label_name).write_text(text, encoding=\"utf-8\")\n", "\n", " max_class = max(self._categories, default=-1)\n", " class_names = [\n", " self._categories.get(i, f\"class_{i}\")\n", " for i in range(max_class + 1)\n", " ]\n", " classes_text = \"\\n\".join(class_names)\n", " if classes_text:\n", " classes_text += \"\\n\"\n", " (root / self.classes_file).write_text(classes_text, encoding=\"utf-8\")\n", "\n", " self._records.clear()\n", " self._categories.clear()" ] }, { "cell_type": "markdown", "id": "ac989c9f", "metadata": {}, "source": [ "Now we use the writer with the normal Dice COCO dataset.\n", "\n", "Two details matter here:\n", "\n", "- `preprocessing=None` keeps the exported images as normal image tensors. If we\n", " kept ImageNet preprocessing, the exported images would be normalized model\n", " inputs rather than ordinary images.\n", "- The source reader is still the built-in COCO reader. The custom part is only\n", " the output format." ] }, { "cell_type": "code", "execution_count": null, "id": "417c476d", "metadata": {}, "outputs": [], "source": [ "if YOLO_DICE_ROOT.exists(): # remove if it already exists\n", " rmtree(YOLO_DICE_ROOT)\n", "\n", "# load standard coco dice, but change the writer to be able to export as yolo format\n", "dice_source_for_export = DeepVisionDataset(\n", " \"../demo_datasets/DiceDataset\",\n", " reader=\"coco\",\n", " data_type_reader=\"bbox\",\n", " writer=YoloBBoxWriter(),\n", " preprocessing=None,\n", ")\n", "\n", "# exporting to yolo format\n", "dice_source_for_export.export(\n", " YOLO_DICE_ROOT,\n", " num_visualizations=2,\n", ")" ] }, { "cell_type": "markdown", "id": "f2fe69fb", "metadata": {}, "source": [ "The custom writer produced a regular dataset folder that no longer depends on\n", "the original COCO annotations. To use this folder for training, we now need the\n", "opposite conversion: a reader that turns YOLO `.txt` annotations back into\n", "`BboxData`.\n", "\n", "A reader needs to implement the small `AnnotationReader` interface:\n", "\n", "- `scan()` returns the ordered image names,\n", "- `read_item(index)` returns `(image_name, target)`,\n", "- `category_ids` gives class names for visualization / validation,\n", "- `out_type` tells `DeepVisionDataset` which `BaseData` type is returned.\n", "\n", "Here we added the validation report that is optional but helpeful." ] }, { "cell_type": "code", "execution_count": null, "id": "c01d933a", "metadata": {}, "outputs": [], "source": [ "class YoloBBoxReader(AnnotationReader):\n", " def __init__(\n", " self,\n", " dataset_root: str | Path,\n", " *,\n", " labels_subdir: str = \"labels\",\n", " classes_file: str = \"classes.txt\",\n", " ) -> None:\n", " self.root = Path(dataset_root)\n", " self.image_dir = self.root / \"images\"\n", " self.label_dir = self.root / labels_subdir\n", " self.classes_path = self.root / classes_file\n", " self._imgs = sorted(p.name for p in self.image_dir.iterdir())\n", " self._cat_ids = self._read_categories()\n", "\n", " @property\n", " def category_ids(self) -> dict[int, str]:\n", " return self._cat_ids\n", "\n", " @property\n", " def out_type(self) -> str:\n", " return \"bbox\"\n", "\n", " def __len__(self) -> int:\n", " return len(self._imgs)\n", "\n", " def scan(self) -> list[str]:\n", " return self._imgs\n", "\n", " def read_item(self, index: int) -> tuple[str, BboxData]:\n", " image_name = self._imgs[index]\n", " image_path = self.image_dir / image_name\n", "\n", " with Image.open(image_path) as img:\n", " width, height = img.size\n", "\n", " label_path = self.label_dir / Path(image_name).with_suffix(\".txt\").name\n", " rows = self._read_rows(label_path)\n", "\n", " if not rows:\n", " return image_name, BboxData.empty((height, width))\n", "\n", " labels = torch.tensor([row[0] for row in rows], dtype=torch.long)\n", " boxes = torch.tensor([row[1:] for row in rows], dtype=torch.float32)\n", " boxes[:, [0, 2]] *= float(width)\n", " boxes[:, [1, 3]] *= float(height)\n", "\n", " target = BboxData(\n", " value=boxes,\n", " labels=labels,\n", " canvas_size=(height, width),\n", " boxformat=\"CXCYWH\",\n", " )\n", " return image_name, target\n", "\n", " def validation_report(self, indices=None) -> dict[str, object]:\n", " selected = range(len(self._imgs))\n", " if indices is not None:\n", " selected = [int(i) for i in indices]\n", "\n", " selected_list = list(selected)\n", " used_ids: set[int] = set()\n", " num_annotations = 0\n", "\n", " for i in selected_list:\n", " image_name = self._imgs[i]\n", " label_path = self.label_dir / Path(image_name).with_suffix(\".txt\").name\n", " rows = self._read_rows(label_path)\n", " num_annotations += len(rows)\n", " used_ids.update(int(row[0]) for row in rows)\n", "\n", " declared_ids = sorted(self._cat_ids)\n", " used_ids_sorted = sorted(used_ids)\n", "\n", " return {\n", " \"reader\": \"custom_yolo_bbox\",\n", " \"num_images\": len(selected_list),\n", " \"num_annotations\": int(num_annotations),\n", " \"declared_category_ids\": declared_ids,\n", " \"declared_category_names\": dict(self._cat_ids),\n", " \"used_category_ids\": used_ids_sorted,\n", " \"unused_declared_category_ids\": [\n", " i for i in declared_ids if i not in used_ids\n", " ],\n", " \"undeclared_used_category_ids\": [\n", " i for i in used_ids_sorted if i not in self._cat_ids\n", " ],\n", " }\n", "\n", " def _read_categories(self) -> dict[int, str]:\n", " if self.classes_path.exists():\n", " names = self.classes_path.read_text(encoding=\"utf-8\").splitlines()\n", " return {i: name for i, name in enumerate(names) if name}\n", "\n", " used_ids: set[int] = set()\n", " for image_name in self._imgs:\n", " label_path = self.label_dir / Path(image_name).with_suffix(\".txt\").name\n", " rows = self._read_rows(label_path)\n", " used_ids.update(int(row[0]) for row in rows)\n", " return {i: f\"class_{i}\" for i in sorted(used_ids)}\n", "\n", " @staticmethod\n", " def _read_rows(label_path: Path) -> list[list[float]]:\n", " if not label_path.exists():\n", " return []\n", "\n", " rows = []\n", " for line in label_path.read_text(encoding=\"utf-8\").splitlines():\n", " line = line.strip()\n", " if not line:\n", " continue\n", " parts = line.split()\n", " rows.append([int(parts[0]), *[float(v) for v in parts[1:5]]])\n", " return rows" ] }, { "cell_type": "markdown", "id": "5e0942ee", "metadata": {}, "source": [ "Finally, we instantiate `DeepVisionDataset` with the reader object directly.\n", "No registry entry is required: registries are convenient when you want a\n", "format to be available by name everywhere, but passing an object is enough for\n", "local project code and tutorials.\n", "\n", "The dataset below behaves like any other detection dataset in deepvisiontools.\n", "It returns image tensors, `BboxData` targets, and image names; therefore it can\n", "be used by `DeepVisionLoader`, the trainer, the evaluator, and visualization\n", "utilities." ] }, { "cell_type": "code", "execution_count": null, "id": "47f84039", "metadata": {}, "outputs": [], "source": [ "yolo_dice_reader = YoloBBoxReader(YOLO_DICE_ROOT)\n", "\n", "yolo_dice_dataset = DeepVisionDataset(\n", " YOLO_DICE_ROOT,\n", " reader=yolo_dice_reader,\n", " writer=YoloBBoxWriter(),\n", " preprocessing=yolo_preprocessing,\n", ")\n", "\n", "image, target, image_name = yolo_dice_dataset[0]\n", "\n", "print(image_name)\n", "print(image.shape)\n", "print(target)\n", "print(target.boxformat)\n", "print(yolo_dice_dataset.category_ids)" ] }, { "cell_type": "markdown", "id": "cc718ca3", "metadata": {}, "source": [ "A quick loader smoke test confirms that batching still works.\n", "\n", "`BatchData` pads annotations to a common canvas when needed, keeps the data\n", "type information, and exposes the same target API used by every model wrapper.\n", "From this point on, the training code does not care whether the annotations\n", "came from COCO JSON, YOLO text files, a database, or a fully custom layout." ] }, { "cell_type": "code", "execution_count": null, "id": "bc9e3e1e", "metadata": {}, "outputs": [], "source": [ "yolo_dice_loader = DeepVisionLoader(\n", " yolo_dice_dataset,\n", " batch_size=4,\n", " shuffle=True,\n", ")\n", "\n", "images, targets, names = next(iter(yolo_dice_loader))\n", "\n", "print(images.shape)\n", "print(targets)\n", "print(names[:2])" ] }, { "cell_type": "markdown", "id": "c678a74e", "metadata": {}, "source": [ "The same custom writer can also be attached to the YOLO-backed dataset and used\n", "to re-export a subset. This is useful when you create train/valid/test splits,\n", "filter bad samples, or convert one custom layout into another.\n", "\n", "The example is left commented to avoid writing another copy every time the\n", "notebook is run." ] }, { "cell_type": "code", "execution_count": null, "id": "209054ec", "metadata": {}, "outputs": [], "source": [ "small_yolo_subset = yolo_dice_dataset.keep_indices(range(5))\n", "small_yolo_subset.set_writer(YoloBBoxWriter())\n", "small_yolo_subset.preprocessing = None\n", "\n", "small_yolo_subset.export(\n", " \"yolo_dice_subset\",\n", " num_visualizations=\"all\",\n", ")" ] }, { "cell_type": "markdown", "id": "47e0460d", "metadata": {}, "source": [ "This is the complete dataset extension pattern.\n", "\n", "Use a **reader** when deepvisiontools needs to consume a new annotation layout,\n", "and use a **writer** when deepvisiontools needs to export to a new layout. For\n", "reusable library code, place the classes in a Python module and optionally\n", "register factories with `register_reader` / `register_writer`. For one-off\n", "project code, passing instantiated reader and writer objects is often cleaner." ] }, { "cell_type": "markdown", "id": "16161f85", "metadata": {}, "source": [ "## 5. Custom DeepVisionModel with torchvision Faster R-CNN\n", "\n", "In this section we will see how you actually write your own custome model wrappers suitable for deepvisiontools. This is done through implementing a specific `DeepVisionModel` object that contains all the minimal API to adapt the runs in deepvisiontools.\n", "\n", "A `DeepVisionModel` is a small façade around four parts:\n", "\n", "```text\n", "images, targets\n", " │\n", " v\n", "preprocessor ──> backend ──> loss\n", " │\n", " v\n", " postprocessor ──> BatchData predictions\n", "```\n", "\n", "For a custom model, you generally need:\n", "\n", "- a backend: wraps the actual `torch.nn.Module`.\n", "- a preprocessor: converts deepvisiontools `BatchData` targets to the backend format. You can inforce resizing or padding here.\n", "- a postprocessor: converts backend predictions back to `BatchData`. It also must reverse the padding, resizing etc. performed by the preprocessor.\n", "- a loss adapter: converts backend losses into a dict containing at least `\"loss\"`.\n", "\n", "Here, we use torchvision Faster R-CNN as a detection backend. Note that torchvision detection labels reserve `0` for background, while deepvisiontools labels start at `0`, so the preprocessor adds `+1` and the postprocessor subtracts `1`." ] }, { "cell_type": "code", "execution_count": null, "id": "34a7163d", "metadata": {}, "outputs": [], "source": [ "from dataclasses import dataclass\n", "from typing import Any\n", "\n", "import torch\n", "from torch import nn\n", "from torchvision.models.detection import (\n", " FasterRCNN_MobileNet_V3_Large_FPN_Weights,\n", " fasterrcnn_mobilenet_v3_large_fpn,\n", ")\n", "from torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n", "from torchvision.ops import nms\n", "\n", "from deepvisiontools.data import BatchData, BboxData\n", "from deepvisiontools.models.base.basemodel import (\n", " BaseLoss,\n", " BasePredParams,\n", " DeepVisionModel,\n", " MODEL_REGISTRY,\n", ")\n", "from deepvisiontools.models.base.protocols import Capabilities\n", "\n", "\n", "\n", "\n", "# first, declare a PredParam for customizable post processing.\n", "@dataclass\n", "class FasterRCNNPredParams(BasePredParams):\n", " conf_threshold: float = 0.25\n", " nms_iou: float = 0.50\n", " max_det: int = 100\n", "\n", " # this part is the default setup\n", " @staticmethod\n", " def default_from_config():\n", " box_cfg = current().data_box\n", " return FasterRCNNPredParams(\n", " conf_threshold=float(box_cfg.conf_threshold),\n", " nms_iou=float(box_cfg.nms_threshold),\n", " max_det=int(box_cfg.max_det),\n", " )\n", " # this part is the metrics setup : typically, for mAP, you'd like to be quite low in threshold to not interfere with mAP (mAP formal definition uses all predictions, \n", " # but a cut-off at 1e-2 usually does not affect the values and save a large amount of computing time)\n", " def pred_params_for_metrics(self):\n", " return FasterRCNNPredParams(\n", " conf_threshold=1e-2,\n", " nms_iou=0.95,\n", " max_det=1000,\n", " )" ] }, { "cell_type": "markdown", "id": "4884aa48", "metadata": {}, "source": [ "\n", "This object keeps the custom model compatible with the rest of the deepvisiontools inference API. The normal thresholds are used by `predict`, while the permissive metric thresholds avoid hiding low-confidence predictions before metric computation." ] }, { "cell_type": "code", "execution_count": null, "id": "d989478a", "metadata": {}, "outputs": [], "source": [ "class FasterRCNNPre(nn.Module):\n", " def images_only(self, images: torch.Tensor) -> torch.Tensor:\n", " return images\n", "\n", " def images_targets(\n", " self,\n", " images: torch.Tensor,\n", " targets: BatchData,\n", " ) -> tuple[torch.Tensor, list[dict[str, torch.Tensor]]]:\n", " out_targets = []\n", "\n", " for item in targets.datas:\n", " if not isinstance(item, BboxData):\n", " raise TypeError(\"Faster R-CNN expects BboxData targets.\")\n", "\n", " box_item = item._new_like()\n", " box_item.boxformat = \"XYXY\"\n", "\n", " boxes = torch.as_tensor(\n", " box_item.value,\n", " dtype=torch.float32,\n", " device=images.device,\n", " )\n", " labels = box_item.labels.to(images.device).long() + 1\n", "\n", " out_targets.append(\n", " {\n", " \"boxes\": boxes,\n", " \"labels\": labels,\n", " }\n", " )\n", "\n", " return images, out_targets" ] }, { "cell_type": "code", "execution_count": null, "id": "98076a77", "metadata": {}, "outputs": [], "source": [ "class FasterRCNNBackend(nn.Module):\n", " def __init__(\n", " self,\n", " *,\n", " num_classes: int,\n", " pretrained: bool = True,\n", " ) -> None:\n", " super().__init__()\n", "\n", " weights = None\n", " if pretrained:\n", " weights = FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT\n", "\n", " self.model = fasterrcnn_mobilenet_v3_large_fpn(weights=weights)\n", " in_features = self.model.roi_heads.box_predictor.cls_score.in_features\n", "\n", " self.model.roi_heads.box_predictor = FastRCNNPredictor(\n", " in_features,\n", " num_classes + 1,\n", " )\n", "\n", " def forward(\n", " self,\n", " x: torch.Tensor,\n", " *,\n", " extra_args: dict[str, Any] | None = None,\n", " ) -> dict[str, Any]:\n", " images = [img for img in x]\n", " targets = None\n", "\n", " if isinstance(extra_args, dict):\n", " targets = extra_args.get(\"targets\")\n", "\n", " if self.training:\n", " losses = self.model(images, targets)\n", " return {\"losses\": losses, \"predictions\": None}\n", "\n", " predictions = self.model(images)\n", "\n", " if targets is None:\n", " return {\"losses\": None, \"predictions\": predictions}\n", "\n", " self.model.train()\n", " losses = self.model(images, targets)\n", " self.model.eval()\n", "\n", " return {\"losses\": losses, \"predictions\": predictions}" ] }, { "cell_type": "markdown", "id": "25262d52", "metadata": {}, "source": [ "\n", "The backend isolates the torchvision-specific calling convention. It converts the input batch to `list[Tensor]`, calls Faster R-CNN, and returns a simple raw dictionary containing losses and/or predictions." ] }, { "cell_type": "code", "execution_count": null, "id": "13f86988", "metadata": {}, "outputs": [], "source": [ "class FasterRCNNLoss(BaseLoss):\n", " def forward(\n", " self,\n", " raw_outputs: dict[str, Any],\n", " targets: Any,\n", " ) -> dict[str, torch.Tensor]:\n", " losses = raw_outputs[\"losses\"]\n", " total = sum(losses.values())\n", "\n", " out = {\"loss\": total}\n", " for name, value in losses.items():\n", " out[f\"loss_{name}\"] = value\n", "\n", " return out" ] }, { "cell_type": "markdown", "id": "a4cb8eff", "metadata": {}, "source": [ "\n", "The loss adapter turns torchvision's loss dictionary into the format expected by the trainer. The key `\"loss\"` is the global value used for backpropagation and monitoring; the other keys (loss details) remain available for logging." ] }, { "cell_type": "code", "execution_count": null, "id": "a52a09fe", "metadata": {}, "outputs": [], "source": [ "# the post processing converts the raw backend output to proper deepvisiontools' BatchData\n", "# Note that this is typically the place to run nms\n", "\n", "class FasterRCNNPost(nn.Module):\n", " def preds_from_raw(\n", " self,\n", " raw_outputs: dict[str, Any],\n", " aux: Any | None = None,\n", " ) -> BatchData:\n", " pred_params = FasterRCNNPredParams.default_from_config()\n", " canvas_size = None\n", "\n", " if isinstance(aux, dict):\n", " canvas_size = aux.get(\"canvas_size\")\n", " if aux.get(\"pred\") is not None:\n", " pred_params = aux[\"pred\"]\n", "\n", " predictions = raw_outputs[\"predictions\"]\n", " out_items = []\n", "\n", " for pred in predictions:\n", " boxes = pred[\"boxes\"].to(dtype=torch.float32)\n", " scores = pred[\"scores\"].to(dtype=torch.float32)\n", " labels = pred[\"labels\"].to(dtype=torch.long) - 1\n", "\n", " keep = scores >= float(pred_params.conf_threshold)\n", " boxes = boxes[keep]\n", " scores = scores[keep]\n", " labels = labels[keep]\n", "\n", " if boxes.numel() > 0:\n", " keep_idx = nms(\n", " boxes,\n", " scores,\n", " float(pred_params.nms_iou),\n", " )\n", " keep_idx = keep_idx[: int(pred_params.max_det)]\n", " boxes = boxes[keep_idx]\n", " scores = scores[keep_idx]\n", " labels = labels[keep_idx]\n", "\n", " if canvas_size is None:\n", " canvas_size = (0, 0)\n", "\n", " if boxes.numel() == 0:\n", " item = BboxData.empty(\n", " canvas_size=canvas_size,\n", " boxformat=\"XYXY\",\n", " device=boxes.device,\n", " )\n", " else:\n", " item = BboxData(\n", " value=boxes,\n", " labels=labels,\n", " scores=scores,\n", " canvas_size=canvas_size,\n", " boxformat=\"XYXY\",\n", " device=boxes.device,\n", " )\n", "\n", " out_items.append(item)\n", "\n", " device = predictions[0][\"boxes\"].device if predictions else \"cpu\"\n", " return BatchData(out_items, device=device)\n", "\n", " def undo_preproc(\n", " self,\n", " preds: BatchData,\n", " *,\n", " original_hw: tuple[int, int] | None = None,\n", " ) -> BatchData:\n", " return preds" ] }, { "cell_type": "markdown", "id": "5876327b", "metadata": {}, "source": [ "\n", "The postprocessor converts torchvision predictions back to `BatchData[BboxData]`. It reverses the label shift with `-1`, applies the custom confidence/NMS/max-det parameters, and returns empty `BboxData` objects when an image has no remaining detections." ] }, { "cell_type": "code", "execution_count": null, "id": "03b1b197", "metadata": {}, "outputs": [], "source": [ "def build_torchvision_fasterrcnn(\n", " *,\n", " num_classes: int = 1,\n", " pretrained: bool = True,\n", " device: str | torch.device | None = None,\n", " use_amp: bool | None = None,\n", ") -> DeepVisionModel:\n", " backend = FasterRCNNBackend(\n", " num_classes=num_classes,\n", " pretrained=pretrained,\n", " )\n", "\n", " model = DeepVisionModel(\n", " backend=backend,\n", " pre=FasterRCNNPre(),\n", " post=FasterRCNNPost(),\n", " loss_fn=FasterRCNNLoss(),\n", " pred_params=FasterRCNNPredParams.default_from_config(),\n", " caps=Capabilities(\n", " task=\"bbox\",\n", " supports_amp=True,\n", " description=\"torchvision Faster R-CNN demo backend\",\n", " ),\n", " device=device,\n", " use_amp=use_amp,\n", " )\n", "\n", " export_kwargs = {\n", " \"num_classes\": int(num_classes),\n", " \"pretrained\": False,\n", " \"device\": device,\n", " \"use_amp\": use_amp,\n", " }\n", " model.set_export_spec(\"torchvision_fasterrcnn_demo\", export_kwargs)\n", "\n", " return model" ] }, { "cell_type": "markdown", "id": "16b43df4", "metadata": {}, "source": [ "\n", "The builder now attaches an export spec to the returned `DeepVisionModel`. This is the metadata needed by portable artifacts and YAML export: a builder name plus YAML-safe kwargs. Notice that `pretrained=False` is used in the export spec because a saved artifact already contains trained weights; reloading should rebuild the architecture, then load the saved state dict." ] }, { "cell_type": "markdown", "id": "3dc36860", "metadata": {}, "source": [ "We can now build the custom model and run a single batch through `train_step`,\n", "`eval_step`, and `predict`.\n", "\n", "The builder attaches an export spec, so the model knows how it should be rebuilt\n", "for portable artifacts. In this notebook the builder is local, which is enough to\n", "inspect/export the spec. To reload a saved artifact or a YAML config in a fresh\n", "Python process, the builder must also be importable and registered under the same\n", "name." ] }, { "cell_type": "code", "execution_count": null, "id": "8cd2a5ad", "metadata": {}, "outputs": [], "source": [ "custom_model = build_torchvision_fasterrcnn(\n", " num_classes=1,\n", " pretrained=True,\n", " device=\"cuda\",\n", ")\n", "\n", "images, targets, names = next(iter(train_loader))\n", "\n", "train_output = custom_model.train_step(images, targets)\n", "eval_output = custom_model.eval_step(images, targets)\n", "pred_output = custom_model.predict(images)\n", "\n", "print(train_output.lossesdict())\n", "print(eval_output.preds)\n", "print(pred_output.preds)" ] }, { "cell_type": "markdown", "id": "d6c5c051", "metadata": {}, "source": [ "\n", "This smoke test checks the three public `DeepVisionModel` paths. `train_step`\n", "returns a loss dictionary, `eval_step` returns losses plus decoded predictions,\n", "and `predict` returns decoded predictions only. The same wrapper can therefore be\n", "used by the trainer, evaluator, and predictor-style inference code." ] }, { "cell_type": "markdown", "id": "0916547d", "metadata": {}, "source": [ "The export spec can be inspected directly. It is just a tuple:\n", "\n", "```text\n", "(builder_name, builder_kwargs)\n", "```\n", "\n", "For a custom model, this is the most important piece of metadata to keep portable\n", "training configs and saved model artifacts reproducible." ] }, { "cell_type": "code", "execution_count": null, "id": "ca942811", "metadata": {}, "outputs": [], "source": [ "builder_name, builder_kwargs = custom_model.export_spec()\n", "\n", "print(builder_name)\n", "print(builder_kwargs)" ] }, { "cell_type": "markdown", "id": "ced40997", "metadata": {}, "source": [ "\n", "The printed kwargs are intentionally simple: integers, booleans, strings, or `None`. Avoid storing runtime objects such as instantiated modules, datasets, loss objects, or lambdas in an export spec, because they cannot be represented cleanly in YAML or checkpoint metadata." ] }, { "cell_type": "markdown", "id": "62ba7459", "metadata": {}, "source": [ "The custom model can also be used by the `Trainer`. Because the model already has\n", "an export spec, the config can be exported to YAML and model artifacts can be\n", "saved.\n", "\n", "For artifact reload in a fresh process, register the builder under the same name.\n", "In a real project this should live in a normal Python module imported before\n", "loading the artifact. The small guard below keeps the notebook cell rerunnable." ] }, { "cell_type": "code", "execution_count": null, "id": "b8baf4b4", "metadata": {}, "outputs": [], "source": [ "if \"torchvision_fasterrcnn_demo\" not in MODEL_REGISTRY.available():\n", " MODEL_REGISTRY.register(\"torchvision_fasterrcnn_demo\")(build_torchvision_fasterrcnn)\n", "\n", "custom_train_config = TrainerConfig(\n", " model=custom_model,\n", " train_loader=train_loader,\n", " valid_loader=valid_loader,\n", " epochs=2,\n", " output_dir=\"custom_fasterrcnn_runs\",\n", ")\n", "\n", "custom_train_config.devices.device = \"cuda\"\n", "custom_train_config.optim.optimizer = torch.optim.AdamW\n", "custom_train_config.optim.optim_args = {\"lr\": 1e-4}\n", "custom_train_config.optim.weight_decay = 1e-4\n", "custom_train_config.sched.scheduler = None\n", "\n", "custom_train_config.checkpoint.enable_checkpointing = True\n", "custom_train_config.checkpoint.save_every_n_epochs = 1\n", "custom_train_config.checkpoint.export_model_artifact = True\n", "custom_train_config.checkpoint.export_when = \"best\"\n", "\n", "custom_train_config.logging.backends = [\"mlflow\"]\n", "custom_train_config.logging.mlflow_experiment_name = \"custom_fasterrcnn\"\n", "custom_train_config.logging.mlflow_run_name = \"demo\"\n", "\n", "custom_train_config.validate()\n", "custom_train_config.export_yaml(\n", " \"custom_fasterrcnn_config.yaml\",\n", " portable=True,\n", " include_meta=True,\n", ")\n", "\n", "print(custom_train_config.model_spec)\n", "\n", "# Uncomment to train the custom model.\n", "Trainer(custom_train_config).fit(resume=None)" ] }, { "cell_type": "markdown", "id": "52bc36bc", "metadata": {}, "source": [ "\n", "`TrainerConfig(model=custom_model, ...)` automatically captured the model export spec into `model_spec`. The exported YAML therefore contains the custom builder name and kwargs. The small registration block is only needed for reload/build workflows, because `ModelFactory` must know how to map that builder name back to Python code." ] }, { "cell_type": "markdown", "id": "70177270", "metadata": {}, "source": [ "#### This concludes the advanced usage tutorial." ] } ], "metadata": { "kernelspec": { "display_name": "dvtv2", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.12" } }, "nbformat": 4, "nbformat_minor": 5 }