{ "cells": [ { "cell_type": "markdown", "id": "13142858", "metadata": {}, "source": [ "# Deepvisiontools: Getting started\n", "\n", "**Tutorial time: about 1 hour**\n", "\n", "Welcome to deepvisiontools' getting started tutorial.\n", "\n", "deepvisiontools is a Python library, built on top of PyTorch, that provides an integrated framework for computer vision tasks. With deepvisiontools, you can train models and run inference for various tasks: detection, segmentation, and instance segmentation. This library is designed both for non-experts who want fast solutions to simple problems and for more advanced users who need fully customizable pipelines.\n", "\n", "The required prior knowledge for deepvisiontools is:\n", "- very basic Python: starting a script, using a Jupyter notebook, etc.\n", "- very basic knowledge of machine learning / deep learning concepts\n", "\n", "This tutorial is dedicated to newcomers. It presents the basic usage of the library.\n", "\n", "This tutorial will cover:\n", "- Global configuration\n", "- Data types, datasets, and dataloaders\n", "- Using the available models\n", "- Training and monitoring\n", "- Putting everything together\n", "- Inference\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 will also need matplotlib to display visualizations during the tutorial:\n", "\n", "```bash\n", "pip install matplotlib\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", "### 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).\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ba200f5c", "metadata": {}, "outputs": [], "source": [ "import torch\n", "\n", "torch.cuda.is_available()" ] }, { "cell_type": "markdown", "id": "b3520753", "metadata": {}, "source": [ "## Global configuration\n", "\n", "deepvisiontools uses global variables to set up fallback parameters when they are not explicitly defined by the user for the different tasks. To simplify everything else, we strongly recommend that every project starts by declaring the adapted values for these parameters.\n", "\n", "Here, we are going to set up everything adapted to the demo datasets you just downloaded. To do so, you only need to modify the global config, adapt the device type, and set the number of classes for the 3 tasks we will cover here: detection, instance segmentation, and semantic segmentation.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "c5a6568e", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import current, set_current, use_config\n", "\n", "cfg = current()\n", "\n", "print(cfg)\n", "\n", "cfg = cfg.update_device(\"cuda\")\n", "cfg = cfg.update_bbox(num_classes=1) # we are going to do single class box detection\n", "cfg = cfg.update_instance_mask(num_classes=6) # we are going to do multiclass instance segmentation\n", "cfg = cfg.update_semantic_mask(num_classes=1) # we are goind to do binary segmentation, target class = 1. \n", "\n", "set_current(cfg)\n", "\n", "print(current().data_box, \"\\n\")\n", "print(current().data_instance_mask, \"\\n\")\n", "print(current().data_semantic_mask, \"\\n\")\n", "print(current().device)" ] }, { "cell_type": "markdown", "id": "ac889c7d", "metadata": {}, "source": [ "As you can see, you can easily modify multiple default fallback configs. Note that for semantic segmentation, multiclass segmentation with a total number of classes equal to 2 should be avoided. Indeed, either you have background + target class, and then you are in a binary situation (1 target class), or you have more than 1 target class (let's say 2), and in that case the background must be considered as a target class too (therefore `num_classes` must be set to 3).\n", "\n", "You can use a temporary configuration using a context manager:\n" ] }, { "cell_type": "code", "execution_count": null, "id": "e924576a", "metadata": {}, "outputs": [], "source": [ "tmp_cfg = current().update_bbox(num_classes=158)\n", "\n", "with use_config(tmp_cfg):\n", " # temporary set current to tmp_cfg\n", " print(current().data_box.num_classes)\n", "\n", "# restored current\n", "print(current().data_box.num_classes)" ] }, { "cell_type": "markdown", "id": "cd585da2", "metadata": {}, "source": [ "## Data type, datasets, and dataloaders\n", "\n", "The first step to fine-tune any model on a supervised task is to have an available labelled dataset. Then, you must be able to load the dataset in your Python script. PyTorch uses a `Dataset` class, from which deepvisiontools derives a library-specific dataset class called `DeepVisionDataset`. We are going to create a `DeepVisionDataset` for the three tasks we will cover in this tutorial.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a0fd0faa", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import DeepVisionDataset, DeepVisionLoader\n", "\n", "# relative or absolute path work, here we have this notebook in folder named tutos sitting right next to the folder demo_datasets\n", "dice_dataset = DeepVisionDataset(\"../demo_datasets/DiceDataset\", reader = \"coco\", data_type_reader=\"bbox\")\n", "vegann_dataset = DeepVisionDataset(\"../demo_datasets/VegannSubDataset\", reader = \"semantic_mask_folder\")\n", "coco6cls_dataset = DeepVisionDataset(\"../demo_datasets/coco_6cls_subset/train\", reader = \"coco\", data_type_reader=\"instance_mask\") # for this dataset we already have a train/valid/test split\n", "\n", "# Each item returns a tuple of three elements : image, target, name of image\n", "dice_img, dice_target, dice_sample_name = dice_dataset[7] \n", "veg_img, veg_target, veg_sample_name = vegann_dataset[3]\n", "coco_img, coco_target, coco_sample_name = coco6cls_dataset[12]\n", "\n", "print(type(dice_img), type(dice_target), dice_sample_name)\n", "print(type(veg_img), type(veg_target), veg_sample_name)\n", "print(type(coco_img), type(coco_target), coco_sample_name)\n" ] }, { "cell_type": "markdown", "id": "d7f21b95", "metadata": {}, "source": [ "First of all, it is important to note that, by default, deepvisiontools expects a certain format for the datasets.\n", "\n", "For COCO-style datasets (bounding boxes or instance segmentation/polygons), they need to have the following structure:\n", "\n", " . Dataset Name\n", " ├── images\n", " ├── name01.png\n", " ├── name02.png\n", " └── ...\n", " └── coco_annotations.json\n", "\n", "Note that images can have a large variety of standard formats (png, jpeg, tif, etc.). The COCO json file must be in COCO format (you can search on the web for more information).\n", "\n", "For semantic masks, the structure must be as follows:\n", "\n", " . Dataset Name\n", " ├── images\n", " ├── name01.png\n", " ├── name02.png\n", " └── ...\n", " ├── masks\n", " ├── name01.png\n", " ├── name02.png\n", " └── ...\n", "\n", "\n", "As you can see, each sample of a given dataset is a tuple containing the image as a torch tensor, the target as a special deepvisiontools object called `BaseData` that is specific to the task (`BboxData`, `InstanceMaskData`, `SemanticMaskData`), and the name of the image.\n", "\n", "For people not familiar with torch, think of tensors as numpy arrays that allow GPU (CUDA) computation. Anyway, if you stick to the basics of deepvisiontools, you will not need to learn more than the fact that they behave like numpy arrays. You can also convert them to numpy simply by using `mytensor.numpy()`.\n", "\n", "Let's have a closer look at the `BaseData` objects.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "c3160f22", "metadata": {}, "outputs": [], "source": [ "print(dice_target)\n", "print(veg_target)\n", "print(coco_target)" ] }, { "cell_type": "markdown", "id": "9369705a", "metadata": {}, "source": [ "Each of them contains multiple attributes, such as `canvas_size`, which is the shape of the associated image, the shape of its value tensor, the number of objects it contains, etc. Let's have a look at the `value` attribute.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "38fb8680", "metadata": {}, "outputs": [], "source": [ "print(dice_target.value)\n", "print(veg_target.value, f\"with unique values : {veg_target.value.unique()}\")\n", "print(coco_target.value, f\"with unique values : {coco_target.value.unique()}\")" ] }, { "cell_type": "markdown", "id": "cfa90777", "metadata": {}, "source": [ "You can see that the value of `dice_target` is a special torch tensor called `BoundingBoxes` (actually, it is a torchvision `tv_tensor`). It contains the coordinates of the bounding boxes contained in the images.\n", "\n", "The `veg_target` value is actually a `Mask` tensor that has the same height and width as the image, and each entry is the class that the pixel belongs to. Here, it is a binary task, so we have either 0 for background or 1 for vegetation.\n", "\n", "Finally, `coco_target` is a `Mask` as well, but this time every unique value corresponds to one specific object.\n", "\n", "All this will become clearer when we do a visualization just a bit later :)\n", "\n", "Just before that, let's have a look at the labels:\n" ] }, { "cell_type": "code", "execution_count": null, "id": "1e06818d", "metadata": {}, "outputs": [], "source": [ "print(dice_target.labels)\n", "print(veg_target.labels)\n", "print(coco_target.labels)" ] }, { "cell_type": "markdown", "id": "f8750b60", "metadata": {}, "source": [ "As you can see, the labels are the corresponding classes of the objects present. For `dice_target`, we have only one class, so they should all be zeros (class 0 = dice).\n", "\n", "For `veg_target`, the labels are just the unique values. Here, we simply have background and vegetation, so classes 0 and 1.\n", "\n", "Finally, for `coco_target`, there are multiple classes, so you can end up with different values there.\n", "\n", "Let's finally create some visualizations to make things clearer. deepvisiontools `BaseData` objects have a visualization function to help you visualize your targets or predictions.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "6693afbf", "metadata": {}, "outputs": [], "source": [ "dice_visu = dice_target.visualize(dice_img) # you can pass an image tensor to draw the visualization on it, or let it as None to draw it on a black picture. \n", "veg_visu = veg_target.visualize(veg_img)\n", "coco_visu = coco_target.visualize(coco_img)\n", "\n", "import matplotlib.pyplot as plt\n", "\n", "plt.imshow(dice_visu.permute(1, 2, 0).numpy())\n", "plt.show()\n", "plt.imshow(veg_visu.permute(1, 2, 0).numpy())\n", "plt.show()\n", "plt.imshow(coco_visu.permute(1, 2, 0).numpy())\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "fa902337", "metadata": {}, "source": [ "Oops! That's weird, right? Why do we end up with black pictures instead of actual pictures?\n", "\n", "Well, it is simply because `DeepVisionDataset` comes with default preprocessing! For those who are not experts, preprocessing is needed when you train neural networks. It typically scales values to the [0, 1] range and can also normalize them using dataset statistics. There are many ways to normalize images. For example, Ultralytics usually simply divides all pixel values by 255, so they fall in the 0-1 range. deepvisiontools uses default ImageNet preprocessing, which normalizes images to the standard ImageNet image distribution. Why? Because most models proposed by deepvisiontools are pretrained on ImageNet.\n", "\n", "To change the preprocessing, you can simply do:\n" ] }, { "cell_type": "code", "execution_count": null, "id": "fcb2d4f5", "metadata": {}, "outputs": [], "source": [ "def yolo_preprocessing(x):\n", " return x/255.0\n", "\n", "dice_dataset.preprocessing = yolo_preprocessing" ] }, { "cell_type": "markdown", "id": "7a9d3cdb", "metadata": {}, "source": [ "And voilà! You can customize your preprocessing if needed.\n", "\n", "Anyway, we want to do visualizations, so let's set the preprocessing to `None` for now.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "41cf73b8", "metadata": {}, "outputs": [], "source": [ "# change datasets preprocessing to None\n", "dice_dataset.preprocessing = None\n", "vegann_dataset.preprocessing = None \n", "coco6cls_dataset.preprocessing = None\n", "# re-sample the values\n", "dice_img, dice_target, dice_sample_name = dice_dataset[7] \n", "veg_img, veg_target, veg_sample_name = vegann_dataset[3]\n", "coco_img, coco_target, coco_sample_name = coco6cls_dataset[12]\n", "# regenerate the visus\n", "dice_visu = dice_target.visualize(dice_img) # you can pass an image tensor to draw the visualization on it, or let it as None to draw it on a black picture. \n", "veg_visu = veg_target.visualize(veg_img)\n", "coco_visu = coco_target.visualize(coco_img)\n", "\n", "# display the visus\n", "plt.imshow(dice_visu.permute(1, 2, 0).numpy())\n", "plt.show()\n", "plt.imshow(veg_visu.permute(1, 2, 0).numpy())\n", "plt.show()\n", "plt.imshow(coco_visu.permute(1, 2, 0).numpy())\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "063c4534", "metadata": {}, "source": [ "To conclude this part, we need to see 2 last things: dataloaders and a series of tiny helpers regarding datasets.\n", "\n", "First, let's start with the dataloader. Dataloaders are objects that allow you to create batches of data. Indeed, it is strongly recommended to optimize on multiple samples simultaneously. Basically, you provide n images with n targets in a single forward pass, and call the optimizer on those n samples. This helps gradient stability and is usually much faster than providing samples one by one. The best batch size values usually lie in the 16-64 range, but depending on the models, your GPU, and the image size, you might not have enough CUDA memory.\n", "\n", "PyTorch implements dataloader objects, and deepvisiontools builds its own dataloader on top of them. You can use the same kwargs as you would in a torch dataloader, but the deepvisiontools dataloader keeps things compatible with the library and enforces shuffling of the samples (you can disable that, but we do not suggest doing so).\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ac61320a", "metadata": {}, "outputs": [], "source": [ "dice_loader = DeepVisionLoader(dice_dataset, batch_size=8)\n", "\n", "vegg_loader = DeepVisionLoader(vegann_dataset, batch_size=12)\n", "\n", "for batch in dice_loader:\n", " imgs, targs, names = batch \n", " print(imgs.shape)\n", " print(targs, \"\\n\", targs.datas)\n", " print(names)\n", " break" ] }, { "cell_type": "markdown", "id": "a7454718", "metadata": {}, "source": [ "As you can see, `targs` are wrapped into a `BatchData` class and contain 8 objects. All the individual `BaseData` objects are registered under `targs.datas`. Finally, you can see that `imgs` has the dimension `[n_batch, 3, H, W]`, meaning you have `n_batch` images stacked into a single tensor.\n", "\n", "Let's conclude this part with a small series of functionalities associated with `DeepVisionDataset`.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "05b67a9b", "metadata": {}, "outputs": [], "source": [ "# dataset splitting\n", "\n", "train_dice, valid_dice, test_dice = dice_dataset.split((0.7, 0.15, 0.15)) # random selection of 3 partitions\n", "\n", "print(len(train_dice), len(valid_dice), len(test_dice))\n", "\n", "# dataset export\n", "\n", "valid_dice.export(\"valid_dice_exported\", num_visualizations=3)\n", "\n", "# Augmentations\n", "import torchvision.transforms.v2 as v2\n", "\n", "AUGS = [v2.RandomHorizontalFlip(), v2.RandomVerticalFlip(), v2.ColorJitter(hue=0.25, saturation=0.15, brightness=0.15, contrast=0.15), v2.RandomGrayscale(0.5)]\n", "\n", "coco6cls_dataset.augmentation = AUGS\n", "\n", "for _ in range(5):\n", " coco_img, coco_target, coco_sample_name = coco6cls_dataset[12]\n", " coco_visu = coco_target.visualize(coco_img)\n", "\n", " plt.imshow(coco_visu.permute(1, 2, 0).numpy())\n", " plt.show()\n", " " ] }, { "cell_type": "markdown", "id": "d6d50cc6", "metadata": {}, "source": [ "As you can see, you are able to split and export datasets in deepvisiontools. This is particularly useful when you want to prepare your splits and keep them identical across trainings.\n", "\n", "Furthermore, you can see that you can generate some visualizations during the exports.\n", "\n", "Finally, you can apply a wide series of augmentations. Basically, all torchvision v2 transforms are compatible: https://docs.pytorch.org/vision/stable/auto_examples/transforms/plot_transforms_illustrations.html\n", "\n", "\n", "## Available models\n", "\n", "In deepvisiontools, we provide a wide series of models for detection, instance segmentation, and semantic segmentation.\n", "\n", "The key idea is that we create model wrappers, either by directly using an associated library such as Ultralytics or segmentation_models.pytorch, or by implementing them ourselves.\n", "\n", "To see the full list of models and create a model, please use the `ModelFactory` builder.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "531799c5", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import ModelFactory\n", "import segmentation_models_pytorch as smp\n", "\n", "ModelFactory.available_configs()\n", "\n", "yolo11n = ModelFactory(\"yolo\", arch=\"yolo11n\") # apart from the model wrapper (\"yolo\" here, all arguments must be non positional)\n", "\n", "unet_resnet50 = ModelFactory(\n", " \"smp\",\n", " arch=\"Unet\",\n", " encoder_name=\"resnet50\",\n", " loss=smp.losses.DiceLoss(mode=\"binary\"),\n", " encoder_weights=\"imagenet\",\n", ")" ] }, { "cell_type": "markdown", "id": "e3683795", "metadata": {}, "source": [ "In the near future, we should add a more extensive description for the full set of models.\n", "\n", "Here are some basic insights for you:\n", "\n", "- `smp` models are segmentation_models.pytorch wrappers. You can use the full range of smp models: https://github.com/qubvel-org/segmentation_models.pytorch\n", "- YOLOs: you can use all Ultralytics architectures. https://docs.ultralytics.com/#yolo-a-brief-history When you have a detection / instance segmentation task, we strongly suggest you start from there, as the models are fully pretrained on COCO and YOLOs have pretty good performance while being quite fast. It will at least establish a clean benchmark.\n", "- `detector` / `tabdet`: those two are implemented in deepvisiontools, but strongly inspired by mmdet / detectron2. Basically, they are much heavier detectors (VFNet and Cascade R-CNN type) which are much more accurate. However, if your dataset is small, they may be worse than YOLOs, because they were not fully pretrained on COCO (only the encoder was pretrained on ImageNet). They are basically compatible with all timm encoders.\n", "\n", "deepvisiontools provides ways to implement your own custom models, but this topic will be covered in more advanced tutorials.\n", "\n", "\n", "## Training and monitoring\n", "\n", "Let's jump now to the core of the library: training some models. We have a dataset, we have models, and now we will see how you can very easily train models with deepvisiontools.\n", "\n", "The complete training setup will be controlled through one particular class: `TrainerConfig`. This object will be digested by the `Trainer` class, which will be in charge of running the full training.\n", "\n", "In deepvisiontools, we tried to keep maximum flexibility for the user while providing a very simple and user-friendly API for people who are not experts in coding or deep learning.\n", "\n", "The best way to create a `TrainerConfig` object is to start from an existing registered one and then modify the parts you want to customize. There are a lot of options; we will cover only the most important ones here. In another tutorial, we will go into more detail about all the training options you can use.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f10777bd", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import Trainer, TrainerConfig\n", "\n", "# Let's start by redefining our datasets/dataloader with a preprocessing\n", "\n", "AUGS = [v2.RandomHorizontalFlip(), v2.RandomVerticalFlip(), v2.ColorJitter(hue=0.15, saturation=0.15, brightness=0.15, contrast=0.15), v2.RandomGrayscale(0.05)]\n", "#datasets\n", "dice_dataset = DeepVisionDataset(\"../demo_datasets/DiceDataset\", reader = \"coco\", data_type_reader=\"bbox\", augmentation=AUGS)\n", "vegann_dataset = DeepVisionDataset(\"../demo_datasets/VegannSubDataset\", reader = \"semantic_mask_folder\")\n", "coco6cls_dataset = DeepVisionDataset(\"../demo_datasets/coco_6cls_subset/train\", reader = \"coco\", data_type_reader=\"instance_mask\") \n", "#splits\n", "train_dice, valid_dice, test_dice = dice_dataset.split((0.7, 0.15, 0.15))\n", "train_veg, valid_veg, test_veg = vegann_dataset.split((0.7, 0.15, 0.15))\n", "train_coco, valid_coco, test_coco = coco6cls_dataset.split((0.7, 0.15, 0.15))\n", "#loaders\n", "train_dice_loader, valid_dice_loader = DeepVisionLoader(train_dice, batch_size=4), DeepVisionLoader(valid_dice, batch_size=4)\n", "train_veg_loader, valid_veg_loader = DeepVisionLoader(train_veg, batch_size=4), DeepVisionLoader(valid_veg, batch_size=4)\n", "train_coco_loader, valid_coco_loader = DeepVisionLoader(train_coco, batch_size=4), DeepVisionLoader(valid_coco, batch_size=4)\n", "\n", "# Then we list the full set of registered configs\n", "\n", "TrainerConfig.available_configs()\n", "\n", "config_dice = TrainerConfig.build_registered_config(model=\"yolo\", config=\"yolo11n\", train_loader=train_dice_loader, valid_loader=valid_dice_loader)\n", "config_veg = TrainerConfig.build_registered_config(model=\"smp\", config=\"smp_unet_resnet50\", train_loader=train_veg_loader, valid_loader=valid_veg_loader)\n", "config_coco = TrainerConfig.build_registered_config(model=\"yoloseg\", config=\"yolo11m-seg\", train_loader=train_coco_loader, valid_loader=valid_coco_loader)" ] }, { "cell_type": "markdown", "id": "00252ee7", "metadata": {}, "source": [ "You can see that we created 3 configs, so basically we can train 3 models on 3 datasets in a really fast way.\n", "\n", "The next steps are trivial: we are going to change the number of epochs to keep training fast (this is a tutorial after all), then we are going to pass our configs to the `Trainer` class and run the `fit` method.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "07865b35", "metadata": {}, "outputs": [], "source": [ "config_dice.epochs = 3\n", "config_veg.epochs = 3\n", "config_coco.epochs = 3\n", "# define launch function (it's optional but it allows to use the launch helper that automatically distribute to the visible devices)\n", "def main_dice():\n", " Trainer(config_dice).fit()\n", " \n", "def main_veg():\n", " Trainer(config_veg).fit()\n", " \n", "def main_coco():\n", " Trainer(config_coco).fit()\n", " \n", "from deepvisiontools.train import launch\n", "# launch is an optional helper that handles hardware distribution. You can setup the devices you want to use, but the auto mode is going to use everything visible.\n", "# if cuda is not available it will launch on cpu, which is not recommended ...\n", " \n", "launch(main_dice, devices=\"auto\") # start training on the dice dataset/configuration\n", "launch(main_veg, devices=\"auto\") # start training on the vegan dataset/configuration\n", "launch(main_coco, devices=\"auto\") # start training on the coco dataset/configuration" ] }, { "cell_type": "markdown", "id": "3d9c09d4", "metadata": {}, "source": [ "deepvisiontools provides a default monitoring environment using MLflow. You can therefore monitor a wide series of metrics, losses, learning rate evolution, etc. using the `mlruns/` folder, which contains an `mlflow.db` SQLite database with all monitored values. Furthermore, all best models are saved by default, as well as periodic checkpoints to help restart a training run that would have been interrupted.\n", "\n", "To display the MLflow web interface, you have 2 options:\n", "\n", "- Open it in a web browser:\n", "\n", "```bash\n", "mlflow server --backend-store-uri sqlite:////$(pwd)/mlruns/mlflow.db --default-artifact-root file:$(pwd)/mlruns --host 127.0.0.1 --port 5000\n", "```\n", "\n", "Then open http://127.0.0.1:5000 in your web browser (we recommend that you use private browsing, as we identified that some duplication occurs if the run is not completed in normal windows...).\n", "\n", "- Open it in a Jupyter notebook cell: we are going to show that option in the next cell.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d34650ee", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import subprocess, sys, time, socket\n", "from IPython.display import IFrame, display\n", "\n", "db_path = (Path.cwd() / \"mlruns\" / \"mlflow.db\").resolve()\n", "port = 5000\n", "\n", "backend_uri = f\"sqlite:///{db_path.as_posix()}\"\n", "\n", "cmd = [\n", " sys.executable, \"-m\", \"mlflow\", \"server\",\n", " \"--backend-store-uri\", backend_uri,\n", " \"--host\", \"127.0.0.1\",\n", " \"--port\", str(port),\n", " \"--x-frame-options\", \"NONE\",\n", " \"--cors-allowed-origins\", \"http://127.0.0.1:8888,http://localhost:8888\",\n", "]\n", "\n", "proc = subprocess.Popen(cmd, \n", " stdout=subprocess.DEVNULL, # this is just to remove logger pollution coming from subprocesses\n", " stderr=subprocess.DEVNULL, # this is just to remove logger pollution coming from subprocesses\n", " )\n", "\n", "for _ in range(50):\n", " with socket.socket() as s:\n", " if s.connect_ex((\"127.0.0.1\", port)) == 0:\n", " break\n", " time.sleep(0.2)\n", "\n", "display(IFrame(src=f\"http://127.0.0.1:{port}\", width=\"100%\", height=700))" ] }, { "cell_type": "markdown", "id": "3901621f", "metadata": {}, "source": [ "As you can see, you can view all your runs under Experiments / runs (you may need to switch from GenAI to Model training in the top-left corner first to see the runs). When you click on a run, you have access to a bunch of items: Model metrics is where all dynamic variables are logged during training (learning rate evolution, metrics, losses, etc.). In the artifact section, you can see your models, the summary of your best model in YAML format, and, quite importantly, the configuration (`TrainerConfig`) you used for this particular training. This can be quite convenient when traceability is required.\n", "\n", "Let's properly close MLflow before continuing.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "986b3fc2", "metadata": {}, "outputs": [], "source": [ "proc.terminate()" ] }, { "cell_type": "markdown", "id": "63276f72", "metadata": {}, "source": [ "We are now ready to conduct a complete training. We will demonstrate a complete training script, starting from scratch on the COCO dataset.\n", "\n", "The idea is:\n", "\n", "- Restart from the dataset declaration\n", "- Declare the dataloader\n", "- Generate a training configuration\n", "- Modify a couple of important settings, so you know how to change basic settings such as the learning rate, scheduler, etc.\n", "- Perform the training\n", "- Explore the results with MLflow\n", "\n", "For your own usage, you can pretty much copy and paste the following script and adapt it to your own datasets. Note that training the model might take about 15 minutes if running on GPU (on CPU it is damn longer...).\n", "\n", "Note that we resized to 640x640 in the augmentations: this is the typical resize used by YOLO. While not mandatory, this helps prevent very large images that can occur in the COCO dataset.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "81d47a6e", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import DeepVisionDataset, DeepVisionLoader, current, set_current\n", "from deepvisiontools import Trainer, TrainerConfig, launch\n", "import torchvision.transforms.v2 as v2\n", "import torch\n", "\n", "# config for coco instance dataset\n", "\n", "set_current(current().update_instance_mask(num_classes=6).update_device(\"cuda\"))\n", "\n", "# =================== datasets (train/valid/test split already exists) ==============================\n", "\n", "# we are going to use standard yolo preprocessing here.\n", "def yolo_preprocessing(x):\n", " return x/255.0\n", "\n", "AUGS = [v2.RandomHorizontalFlip(), v2.ColorJitter(hue=0.15, saturation=0.15, brightness=0.15, contrast=0.15), v2.RandomGrayscale(0.05), v2.Resize(640)]\n", "train_set = DeepVisionDataset(\"../demo_datasets/coco_6cls_subset/train\", reader = \"coco\", data_type_reader=\"instance_mask\", augmentation=AUGS, preprocessing=yolo_preprocessing)\n", "valid_set = DeepVisionDataset(\"../demo_datasets/coco_6cls_subset/valid\", reader = \"coco\", data_type_reader=\"instance_mask\", augmentation=[v2.Resize(640)], preprocessing=yolo_preprocessing)\n", "\n", "BATCH_SIZE = 4\n", "trainloader = DeepVisionLoader(train_set, batch_size=BATCH_SIZE)\n", "validloader = DeepVisionLoader(valid_set, batch_size=BATCH_SIZE)\n", "\n", "# ============================== config ==========================================\n", "\n", "config2 = TrainerConfig.build_registered_config(model=\"yoloseg\", config=\"yolo11n-seg\", train_loader=trainloader, valid_loader=validloader) # start from the same config\n", "config2.logging.mlflow_experiment_name = \"Train-config-yolo11m-seg\"\n", "config2.logging.mlflow_run_name = \"run 1\"\n", "config2.epochs = 10\n", "config2.ema.decay = 0.95\n", "# change the optimizer\n", "config2.optim.optimizer = torch.optim.AdamW\n", "config2.optim.optim_args = {\"lr\": 1e-4}\n", "# change lr scheduler, by default the registered configs use CosineAnnealing with automatic epochs adjustement.\n", "config2.sched.scheduler = torch.optim.lr_scheduler.ExponentialLR\n", "config2.sched.scheduler_args = {\"gamma\": 0.93}\n", "config2.sched.step_on = \"epoch\" # this is required since we want to apply exponential lr at the end of epochs. By default it is set as \"step\"\n", "# change model\n", "config2.model_spec.builder = \"yoloseg\"\n", "config2.model_spec.kwargs = {\"arch\": \"yolo11m-seg\"} # we've changed the model from yolo11n to yolo11m\n", "\n", "# start training\n", "\n", "def main():\n", " Trainer(config2).fit()\n", "\n", "launch(main)" ] }, { "cell_type": "code", "execution_count": null, "id": "b95ac1ff", "metadata": {}, "outputs": [], "source": [ "# ================================== mlflow results =============================\n", "\n", "from pathlib import Path\n", "import subprocess, sys, time, socket\n", "from IPython.display import IFrame, display\n", "\n", "db_path = (Path.cwd() / \"mlruns\" / \"mlflow.db\").resolve()\n", "port = 5000\n", "\n", "backend_uri = f\"sqlite:///{db_path.as_posix()}\"\n", "\n", "cmd = [\n", " sys.executable, \"-m\", \"mlflow\", \"server\",\n", " \"--backend-store-uri\", backend_uri,\n", " \"--host\", \"127.0.0.1\",\n", " \"--port\", str(port),\n", " \"--x-frame-options\", \"NONE\",\n", " \"--cors-allowed-origins\", \"http://127.0.0.1:8888,http://localhost:8888\",\n", "]\n", "\n", "proc = subprocess.Popen(cmd, \n", " stdout=subprocess.DEVNULL, # this is just to remove logger pollution coming from subprocesses\n", " stderr=subprocess.DEVNULL, # this is just to remove logger pollution coming from subprocesses\n", " )\n", "\n", "for _ in range(50):\n", " with socket.socket() as s:\n", " if s.connect_ex((\"127.0.0.1\", port)) == 0:\n", " break\n", " time.sleep(0.2)\n", "\n", "display(IFrame(src=f\"http://127.0.0.1:{port}\", width=\"100%\", height=700))" ] }, { "cell_type": "code", "execution_count": null, "id": "65c0c04e", "metadata": {}, "outputs": [], "source": [ "# let's close mlflow run\n", "\n", "proc.terminate()" ] }, { "cell_type": "markdown", "id": "3580e760", "metadata": {}, "source": [ "Now that you have a fully operational example, you can do the same for the Vegann and dice datasets!\n", "\n", "Here are some tricks to help you out:\n", "\n", "- Do not forget to always start by configuring the library through `set_current`! We already did it previously in the tutorial, but it is good practice to do it.\n", "- The dataset paths and declarations were introduced at the beginning of this tutorial. You can use the same augmentations (minus the `Resize` one, since all images in dice or Vegann are 512 x 512) that we used in the previous example. You can use dataset splitting to separate train/valid/test. In the COCO example above, the split was already done within three separate folders.\n", "- Do not pass `yolo_preprocessing` to Vegann datasets; leave the default preprocessing (ImageNet), as your pretrained smp will probably have been pretrained on ImageNet.\n", "- We suggest using the default registered config for your model while still changing EMA decay and the number of epochs.\n", "- Then, if you want, you can change the model, the learning rate, etc.\n", "- If you end up with a CUDA memory error, it probably means that you tried a model that is too heavy and/or have a batch size that is too large.\n", "\n", "We strongly suggest that you implement the small training scripts to become autonomous on pretty much every task you can solve with deepvisiontools. Note that training those models should be much faster than the COCO dataset if you use the default config.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "15f0a53e", "metadata": {}, "outputs": [], "source": [ "# Your vegann training script" ] }, { "cell_type": "code", "execution_count": null, "id": "31fd5c9f", "metadata": {}, "outputs": [], "source": [ "# Your dice training script" ] }, { "cell_type": "markdown", "id": "dccff8bc", "metadata": {}, "source": [ "## Inference and evaluation\n", "\n", "Let's now have a look at inference in deepvisiontools. After training, when you open MLflow, choose an experiment and a run, and go into the artifact section. In the artifacts section, you will see multiple folders: open the models section. In there, you should see 1 or 2 files named `best_model_epoch*.pt` and `best_model_epoch*_ema.pt`. If you used EMA (which you have probably done in this tutorial), the one you want is the EMA model, because we used EMA weights for validation. Otherwise, pick the other one.\n", "\n", "Those are the models that achieved the best performance during training, and therefore they are the models you want to run for inference.\n", "\n", "You can simply download them by clicking on the model in the MLflow UI and then clicking on the download button on the right side. You can then save it somewhere.\n", "\n", "We are going to demonstrate how to run inference from the YOLO11 model trained on the COCO dataset.\n", "\n", "Go to the MLflow config 2 run (if you used the training cell above for `yolo11m-seg` on COCO instance segmentation, it should be under experiment: \"Train-config-yolo11m-seg\" and \"run 1\"), and select the best EMA `.pt` file from artifacts/models. Download it to the same place as the tutorial and name it `best_model_yolo_ema.pt`, so we will have the exact same path.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "315e8084", "metadata": {}, "outputs": [], "source": [ "# use this cell to reopen mlflow ui and download the model.\n", "\n", "from pathlib import Path\n", "import subprocess, sys, time, socket\n", "from IPython.display import IFrame, display\n", "\n", "db_path = (Path.cwd() / \"mlruns\" / \"mlflow.db\").resolve()\n", "port = 5000\n", "\n", "backend_uri = f\"sqlite:///{db_path.as_posix()}\"\n", "\n", "cmd = [\n", " sys.executable, \"-m\", \"mlflow\", \"server\",\n", " \"--backend-store-uri\", backend_uri,\n", " \"--host\", \"127.0.0.1\",\n", " \"--port\", str(port),\n", " \"--x-frame-options\", \"NONE\",\n", " \"--cors-allowed-origins\", \"http://127.0.0.1:8888,http://localhost:8888\",\n", "]\n", "\n", "proc = subprocess.Popen(cmd)\n", "\n", "for _ in range(50):\n", " with socket.socket() as s:\n", " if s.connect_ex((\"127.0.0.1\", port)) == 0:\n", " break\n", " time.sleep(0.2)\n", "\n", "display(IFrame(src=f\"http://127.0.0.1:{port}\", width=\"100%\", height=700))" ] }, { "cell_type": "markdown", "id": "f50c33f1", "metadata": {}, "source": [ "We are now going to use deepvisiontools' `Predictor` class to run inference. By default, the preprocessing is the ImageNet one that comes naturally when creating a dataset. **However, if you changed the preprocessing in the dataset, you must use the same preprocessing here; otherwise, you cannot expect the model to work.**\n" ] }, { "cell_type": "code", "execution_count": null, "id": "9eff3c70", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import Predictor\n", "from PIL import Image\n", "\n", "def yolo_preprocessing(x):\n", " return x/255.0\n", "\n", "my_yolo_predictor = Predictor(\"best_model_yolo_ema.pt\", preprocessing=yolo_preprocessing) # use the same preprocessing as we did for training.\n", "\n", "image_path = \"../demo_datasets/coco_6cls_subset/test/images/000000001966_jpg.rf.8a0cf2aba01097f298ef5ae21ed26006.jpg\"\n", "\n", "batch_results = my_yolo_predictor.predict(image_path, generate_visu=True, visu_names=\"dice_visu.png\")\n", "single_results = batch_results.datas[0]\n", "\n", "\n", "print(\"\\n =================== Results ======================== \\n\")\n", "print(\"batch results: \", batch_results)\n", "print(\"result for the one image: \", single_results)\n", "print(\"number of object (dice) detected: \", single_results.nb_object)\n", "print(\"bounding boxes coordinates: \", single_results.value)\n", "\n", "Image.open(\"dice_visu.png\").resize([1024, 512])\n", "\n" ] }, { "cell_type": "markdown", "id": "0d12ef55", "metadata": {}, "source": [ "As you can see, it is extremely easy! Just create a predictor with the path to your `model.pt` file, and run `predict`. You can optionally generate the associated visualizations. Note that you can provide a list of files to run the predictor by batch, change the prediction parameters, and many other things like that. All prediction options will be covered in the advanced tutorial.\n", "\n", "However, keep in mind that inference can sometimes be tricky:\n", "\n", "- Sometimes models can contain resizing to a fixed input resolution. While in deepvisiontools we explicitly avoid any resizing, you can end up with artifacts if your training images are not exactly like your inference images...\n", "- Typically for segmentation, and in particular with transformer encoders, we strongly suggest using sliding window inference where the window size is fixed to the training image dimension, when inferring on large images while training occurred on small crops.\n", "- It is sometimes important to play with inference hyperparameters such as confidence threshold, maximum number of detections, etc.\n", "\n", "Ok, let's finally move to the final point of this tutorial: evaluation of the `Predictor` on the test set.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f1337e6c", "metadata": {}, "outputs": [], "source": [ "from deepvisiontools import Evaluator, DeepVisionDataset, DeepVisionLoader\n", "from deepvisiontools.metrics import InstanceSegSuite\n", "\n", "test_loader = DeepVisionLoader(DeepVisionDataset(\"../demo_datasets/coco_6cls_subset/test\", \"coco\", data_type_reader=\"instance_mask\", preprocessing=None), batch_size=4) # we delegate to Predictor the preprocessing part\n", "\n", "my_yolo_predictor = Predictor(\"best_model_yolo_ema.pt\", preprocessing=yolo_preprocessing) # use the same preprocessing as we did for training.\n", "\n", "evaluator = Evaluator(my_yolo_predictor, InstanceSegSuite(6))\n", "\n", "evaluator.evaluate(test_loader, \"eval_test_coco\", nb_visu=10)" ] }, { "cell_type": "markdown", "id": "47044f37", "metadata": {}, "source": [ "As you can see, we generated a result folder that contains exactly 10 visualizations and one xlsx report.\n", "\n", "The xlsx report contains all the metrics from the chosen metric suite, as well as individual image metrics, which can help detect when the model fails.\n", "\n", "With this tool, you can carefully evaluate your newly trained model :)\n", "\n", "\n", "#### This part concludes the first tutorial on deepvisiontools!\n" ] } ], "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 }